texts:
I've started to learn about graphs and how to represent them in code. Here is my attempt of making an adjacency list for an undirected graph. I'm looking for suggestions on how to improve it and what could've been done better.

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

struct vertex {
int name=0;
set<vertex> edges;

bool operator< (vertex const &rhs) const {       //needed for set
    return name<rhs.name;
}
bool operator== (vertex const &rhs) const {      //needed for find
    return name == rhs.name;
}

};

class graph {
private:

    std::vector<vertex> vertices;

public:
graph(int size = 0) { vertices.resize(size+1); };

int V;

void addVertex(vertex a) {
    vertices[a.name]=a;
}

void addEdge(int a, int b) {
    vertex f,s;
    f.name = a;
    s.name = b;

    if(!exists(f, vertices))                //checks if vertex was already given
    addVertex(f);

    if (!exists(s, vertices))
    addVertex(s);

    vertices[a].edges.emplace(s);
    vertices[b].edges.emplace(f);
}
void printGraph() {
    for (int i = 1; i<vertices.size(); i++) {

            cout << vertices[i].name << " -> ";
            for (auto it2 : vertices[i].edges) {
                cout << it2.name << " -> ";
            }

            cout << endl;

    }
}

bool exists(vertex a, vector<vertex> b) {
    auto it = find(b.begin(), b.end(), a);
    return (it != b.end());
}

};

int main() {
int v;
cin >>v;            //enter number of vertices

graph Graph(v);

int e;              //enter number of edges
cin >>e;

while (e--) {

    int a, b;
    cin >> a >> b;      //input vertices on the end of an edge
    Graph.addEdge(a, b);
}
Graph.printGraph();

return 0;
}

Each vertex has a name, its number, which is also his position in the "vertices" vector to make it easier to access. Because of that, vertices[0] is not used. Each time you input an edge between two vertices it checks if they are already in the vector and adds them. If they are not, then it adds the vertex to the set of vertices ("edges" set).

EDIT: I'm wanted to use this code to learn searching amd shortest path algorithm's (BFS, DFS, Dijkstra, Floyd-Warshall ...)for the competition


texts:
I solved the Circular-Array-Rotation problem on HackerRank.  I conceded defeat and looked at the answers given on HackerRank itself but the ones I saw used things like vectors, which are concepts I'm a noob at as my knowledge of C++ thus far extends only as far as virtual functions and classes and such (junior COE student). So here's the description of the problem:

  John Watson performs an operation called a right circular rotation on an array of integers, \$a[0], a[1], \dotsc, a[n-1]\$. After performing one right circular rotation operation, the array is transformed from \$a[0], a[1], \dotsc, a[n-1]\$ to \$a[n-1], a[0], \dotsc, a[n-2]\$.

  Watson performs this operation \$k\$ times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks \$q\$ queries, where each query consists of a single integer, \$m\$, for which you must print the element at index \$m\$ in the rotated array (i.e., the value of \$a[m]\$).

  Input Format

  The first line contains 3 space-separated integers, \$n\$, \$k\$, and \$q\$, respectively.

  The second line contains \$n\$ space-separated integers, where each integer \$i\$ describes array element \$a[i]\$ (where \$0 \le i < n\$).
  Each of the \$q\$ subsequent lines contains a single integer denoting \$m\$.

  Constraints

  \begin{align*}
  1 &\le n &&\le 10^5 \\
  1 &\le a[i] &&\le 10^5 \\
  1 &\le k &&\le 10^5 \\
  1 &\le q &&\le 500 \\
  0 &\le m &&\le n - 1
\end{align*}

  Output Format

  For each query, print the value of the element at index \$m\$ of the rotated array on a new line.

  Sample Input

3 2 3
1 2 3
0
1
2

  Sample Output

2
3
1

  Explanation

  After the first rotation, the array becomes \$[3,1,2]\$.
  After the second (and final) rotation, the array becomes \$[2,3,1]\$.

  Let's refer to the array's final state as array \$b\$. For each query, we just have to print the value of \$b[m]\$ on a new line:

  \$m = 0\$, so we print 0 on a new line.
  \$m = 1\$, so we print 1 on a new line.
  \$m = 2\$, so we print 2 on a new line.

This is my code, sadly it only works for a few of the test cases, and times out for the others. Any feedback welcome, including suggestions on learning new methods or anything.

int n;
int k;
int q;
cin >> n >> k >> q;
int *arr = new int[n];
int *query = new int[q];
for (int i = 0; i < n; i++)
{
    cin >> arr[i];
}
for (int j = 0; j < q; j++)
{
    cin >> query[j];
}

int *arr2 = new int[n];
int count = 0;
while (count < k)
{
    int temp = arr[n - 1];
    for (int j = 1; j < n; j++)
    {
        arr2[j] = arr[j - 1];
    }
    arr2[0] = temp;
    for (int j = 0; j < n; j++)
    {
        arr[j] = arr2[j];
    }
    count++;
}

for (int m = 0; m < q; m++)
{
    cout << arr2[query[m]] << endl;
}


texts: Makes a navbar for a website with object oriented php

texts:
I do this as sort of hobby and want to no if I can improve.
This is a simplified version of my code that normal works with bootstrap classes and id's.
At the bottom there is the input of the classes.
I have already a working version connected with SQL Database.
but want to take it a step further with object oriented php.

The next step for me is to create the content page underneath the navbar.
I work with a .htaccess file that redirects everything to index.php, and then use the URI to show the right content.

The main class

<?php

class Main
{
  public $URL;
  public $PageName;
  public function __construct($PageName)
  {
    $this->PageName = $PageName;
    $this->URL = $_SERVER['REQUEST_URI'];
  }
  public static function header() {
    echo '<!DOCTYPE html>

    ...
  ';
  }

  public static function navstart() {
    echo '
';
  }

  public static function navend() {
    echo '
';
  }
}

the navitem class is for making the items in the nav bar

class navItem extends Main
{

    public function __construct($PageName)
  {
    parent::__construct($PageName);
    $ActiveUrl = ($this->URL == "/".$this->PageName) ? " active " : " ";
    echo     '

      PageName.'">'.$this->PageName.'
 &nbsp;';
  }
}

The nav dropdown class to make the dropdown in the navbar

class navDropdown extends Main
{
  public function __construct($PageName, $Item)
  {
    parent::__construct($PageName);
    $shortURL = substr($this->URL, 0, strpos($this->URL, "_"));
    $ActiveUrl = ($shortURL == "/".$this->PageName) ? " active " : " ";
    echo '

        '.$this->PageName.'

';
        foreach ($Item as $Item) {
          $ActiveUrl = ($this->URL == "/".$this->PageName.'_'.$Item) ? " active " : " ";
          echo '
          PageName.'_'.$Item.'" >'.$Item.'';
        }
        echo '

 &nbsp;';
  }
}

the variables to make the page

main::header();
main::navstart();
$test = new navDropDown("test", array('test1' , 'test2', 'test3' , 'test4'));
$home = new navItem("home");
$about = new navItem("about");
$pages = new navDropDown("pages",array("one", "two", "three" ));
$contact = new navItem("contact");
main::navend();


texts:
This code takes a user input number which is a positive integer, and outputs a string representation of the number in binary.  For example, input 2 outputs '10' and input 25 outputs '11001'.  As far as I can tell it works correctly.
Please review it for good style and organization, and I'm especially looking for a critique of the algorithm and level of documentation.  My goals are correctness and that it is obvious what the code is doing.  My experience level is I've been using Python for about 7 years, hobbyist, haven't collaborated with other programmers ever, and I'm now in a Comp Sci degree program.
I chose the log2 function and the for loop to calculate how long to run, rather than trying to guess if the calc is over on each pass of the loop, but I assume there is a cleaner/simpler way to do that.
from math import log2, floor

def integer_to_binary_string(int_value):
    '''Converts integer to a string of base-2 bits,

    example: 20 becomes '10100'

    '''
    rev_str = integer_to_reverse_binary(int_value)
    forward_str = reverse_string(rev_str)
    return forward_str

def integer_to_reverse_binary(int_value):
    '''returns a string, not a numerical'''
    out_s = ''
    if int_value == 0:
        #to avoid ValueError on the log2 call
        return '0'
    #find length of bin string
    bin_digits = floor(log2(int_value)) + 1
    for i in range(bin_digits):
        out_s = out_s + str(int_value // 2**i % 2)
    return out_s

def reverse_string(s):
    return s[::-1]    #start:stop:step slice notation

if __name__ == '__main__':
    user_input = int(input())
    print(integer_to_binary_string(user_input))


texts: Computing the number of permutations of n consecutive numbers

texts:
I'm just starting to learn C++ and have been experimenting with various functions. Here is one that computes the number of permutations of n consecutive numbers as well as all possible permutations provided n. I'd love to receive any form of tips and criticisms on improving this function.

#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>

using namespace std;

string rotateRt(string input);
vector<string> permute(int num);

int main(){
    cout << "n: ";
    int n;
    cin >> n;
    vector<string> permutations(permute(n));
    ofstream myfile;
    myfile.open("rosalind_perm.txt");
    myfile << permutations.size() << endl;
    for(int i = 0; i < permutations.size(); i++){
        myfile << permutations.at(i) << endl;
    }
    myfile.close();
}

/* Rotate input string right by 1 character */
string rotateRt(string input){
    int len = input.length();
    string a, b;
    if(len == 0){
        return "";
    }
    else if(len == 1){
        return input;
    }
    else{
        a = input.substr(0, len - 2);
        b = input.substr(len - 1) + " ";
        return b + a;
    }
}

/* To compute permutations we compute the permutations of num - 1,
append num to the front of each permutation, and find every cyclic
rotation. */
vector<string> permute(int num){
    vector<string> permutations;
    ostringstream convert;
    if(num == 1){
        permutations.push_back("1");
    }
    else{
        vector<string> prevPermutations(permute(num - 1));
        int size = prevPermutations.size();
        string prefix, suffix, word;
        convert << num;
        prefix = convert.str();
        convert.str("");
        for(int i = 0; i < size; i++){
            suffix = prevPermutations.at(i);
            word = prefix +  " " + suffix;
            int length = word.length();
            for(int j = 0; j < length / 2 + 1; j++){
                permutations.push_back(word);
                word = rotateRt(word);
            }
        }
    }
    return permutations;
}


texts: A method that returns an array with no duplicates

texts:
I implemented a method in Java that returns an array of integers with no duplicates (i.e. an array that has no repeated numbers).

My solution seems rather long. I would like to know of ways to improve it...

public class IntArrayProcessor {

    private int[] a;

    public IntArrayProcessor(int[] a) {
        this.a = a;
    }

    /**
     *
     * @return Array with no repeated integers.
     */
    public int[] getSet() {
        /* creates an array with the same entries and length as this.a */
        int[] duplicateA = new int[this.a.length];

        /* stores the number of repeated entries in array this.a */
        int numberOfDuplicates = 0;

        /* is the integer a duplicate or not? */
        boolean isDuplicate;

        /**
         * Counts the number of duplicates in array this.a
         */
        for (int i = 0; i < this.a.length; i++) {
            duplicateA[i] = this.a[i];
        }

        for (int i = 0; i < duplicateA.length; i++) {
            isDuplicate = false;
            for (int j = i + 1; j < this.a.length; j++) {
                if (duplicateA[i] == this.a[j]) {
                    isDuplicate = true;
                }
            }
            if (isDuplicate) {
                numberOfDuplicates++;
            }
        }

        /*
         * the noDuplicate array has the lenght of the this.a array minus the
         * number of repeated entries
         */
        int[] noDuplicate = new int[this.a.length - numberOfDuplicates];

        /* to keep track of the noDuplicate indexes */
        numberOfDuplicates = 0;

        /**
         * An array with no repeated numbers
         */
        for (int i = 0; i < duplicateA.length; i++) {
            isDuplicate = false;
            for (int j = i + 1; j < this.a.length; j++) {
                if (duplicateA[i] == this.a[j]) {
                    isDuplicate = true;
                }
            }
            if (!(isDuplicate)) {
                noDuplicate[numberOfDuplicates] = duplicateA[i];
                numberOfDuplicates++;
            }
        }
        return noDuplicate;
    }
}


texts: Locality Sensitive Hash (similar to k-Nearest Neighbor), in Python+Numpy

texts:
I've tried implementing Locality Sensitive Hash, the algorithm that helps recommendation engines, and powers apps like Shazzam that can identify songs you heard at restaurants.

LSH is supposed to run far quicker than vanilla Nearest Neighbor, but alas mine is 10x slower. Can I get a hand?

Times:
nearest neighbor:  0.0012996239820495248
lsh             :  0.012921262998133898

I've kept things clean, and marginally documented, and it includes a test for timing as well as to compare the results:

import numpy as np
from scipy.spatial.distance import cosine
import timeit
np.random.seed(0)
np.set_printoptions(precision=3, suppress=True)

# ----------
# vanilla Nearest Neighbor

def nearest_neighbor(X, q, n=1):
    '''
    Nearest Neighbor, uses euclidean distance
    X :: data; ndarray(samples, dimensions)
    q :: query point; ndarray(dimensions)
    n :: number of neighbors to return
    '''
    dist = np.sqrt(np.sum((X - q) ** 2, axis=1))
    return X[dist.argsort()[:n]]

# ----------
# Cosine similarity of a matrix row-wise compared to a query vector

def cosine_mat1(X, q):
    return np.apply_along_axis(lambda x: cosine(x, q), 1, X)

def cosine_mat2(X, q):
    out = np.zeros(X.shape[0])
    for ix, x in enumerate(X):
        out[ix] = cosine(x, q)
    return out

def cosine_mat3(X, q):
    Xq = np.sum(X * q, axis=1)
    XX = np.sum(X ** 2, axis=1)
    qq = np.sum(q ** 2)
    return 1.0 - Xq / np.sqrt(XX * qq)

# ----------
# Locality Sensitive Hash

def nearest_neighbor_lsh(X, q, hash_len, n=1):
    '''
    Locality Sensitive Hashing
    X :: data points; ndarray(data point, dimension)
    q :: query
    '''

    hyperslope = np.random.normal(size=(hash_len, X.shape[1]))
    hyperbias = np.random.normal(size=hash_len)
    hashes = ((np.einsum('hd,nd->nh', hyperslope, X) + hyperbias) > 0)
    q_hash = ((np.einsum('hd,d->h', hyperslope, q) + hyperbias)   > 0)
    cosine_similarity = cosine_mat3(hashes, q_hash)
    return X[cosine_similarity.argsort()[:n]]

# ----------
# Timing

samples = 10000
dims = 5
nearest_k = 10
hash_len = 100

X = np.random.normal(size=(samples, dims)) # 100 5D samples
q = np.ones(dims) * 0

print()
t1 = timeit.Timer('nearest_neighbor(X, q, n=nearest_k)', 'from __main__ import nearest_neighbor, X, q, nearest_k')
print('nearest neighbor: ', t1.timeit(number=1))
t2 = timeit.Timer('nearest_neighbor_lsh(X, q, hash_len=hash_len, n=nearest_k)', 'from __main__ import nearest_neighbor_lsh, X, q, nearest_k, hash_len')
print('lsh             : ', t2.timeit(number=1))

# ----------
# Check accuracy

c1 = nearest_neighbor(X, q, n=nearest_k)
c2 = nearest_neighbor_lsh(X, q, hash_len=hash_len, n=nearest_k)
print()
print('avg distance to neighbors: ', np.mean(np.sqrt(np.sum((c1 - q) ** 2, axis=1))))
print('avg distance using lsh   : ', np.mean(np.sqrt(np.sum((c2 - q) ** 2, axis=1))))
rs = X[np.random.randint(samples, size=nearest_k*100)] # random samples
print('avg distance to random   : ', np.mean(np.sqrt(np.sum((rs - q) ** 2, axis=1))))


texts:
I need to get the value of item inside of this string and parse it as JSON. I've got some working code but I feel like it could be optimized (a lot) and cleaned up (a lot). Any tips or pointers are appreciated. Thanks!

My current code:

let result  = script.match(/item:(.*|[\s\S]*)onSelected/gm)[0];
result = result.replace('onSelected', '').replace('item:', '').trim().slice(0, -1);
JSON.parse(result);

Here's the string of javascript I need to pull from:

jQuery(function($) {

    new Selector('itemSelect', {
      item: {"id":9343513159,"title":"The thing","description":"\u003cp\u003eThis is the description\u003c\/p\u003e\n\u003cp\u003eIt has details\u003c\/p\u003e\n","published_at":"2016-12-10T10:08:00-05:00","available":true,"individuals":[{"id":34972221767},{"id":34972221768},{"id":34972221769}],"images":["\/\/cdn.site.com\/s\/files\/1\/0094\/2252\/items\/image.jpg?v=1481382473"],"options":["Time"],"content":""},
      onSelected: selectCallback,
      enableState: true
    });

   // Some stuff here

    $('.main:eq(0)').prepend('<label class="forever" for="time">Forever</label>');

});

window.mainItem = window.mainItem || {};

mainItem.variables = {
  available : false
};

(function() {
  if (true) {
    mainItem.variables.available = true;
  }
})();


texts:
I have a static homepage with some routes and thought about creating this with VueJs. I am totally new to this and just know NodeJs with Handlebars. So normally I would have something like this

#page {
  margin: 30px 0;
}

  Page 1
  Page 2
  Page 3

  Current Page (depends on URL)

  Footer

And I tried to create this by using VueJs

const header = new Vue({
  el: "#header",
  methods: {
    loadPage(pageToLoad) {
      page.$data.currentPage = "Current Page: " + pageToLoad;
    }
  }
});

const page = new Vue({
  el: "#page",
  data: {
    currentPage: "Current Page: 1"
  }
});
#page {
  margin: 30px 0;
}

  Page 1
  Page 2
  Page 3

  Footer

As you can see this example works fine. Instead of rendering the whole page I just change the "main content" of the page without reloading the header and footer.

Is this the correct way to go or how would you create a page with multiple routes?


texts: Constantly checking existence of dictionary elements in Python: a better way?

texts:
I use Python dictionaries to count words in a corpus:

words[a] = number of times I saw a in the corpus.

Every time before incrementing a counter (words[a] += 1), I need to check a condition:
does the dictionary entry words[a] actually exists?

My code:

    if a in words:
      words[a] += 1
    else:
      words[a] = 1

It there a way to improve it?


texts:
I tried to write a program in Prolog and describe a family tree:

parents(uranus, gaia, rhea).
parents(uranus, gaia, cronus).
parents(cronus, rhea, zeus).
parents(cronus, rhea, hera).
parents(cronus, rhea, demeter).
parents(zeus, leto, artemis).
parents(zeus, leto, apollo).
parents(zeus, demeter, persephone).

man(uranus).
man(cronus).
man(zeus).
man(apollo).
man(artemis).

woman(gaia).
woman(rhea).
woman(leto).
woman(demeter).
woman(persephone).
woman(hera).

father(X,Y) :- parents(X,_,Y).
mother(X,Y) :- parents(_,X,Y).

parent(X,Y) :- father(X,Y); mother(X,Y).

son(S,P) :- man(S), father(P,S).
daughter(D,P) :- woman(D), mother(P, D).

siblings(A,B) :- (parents(P,_,A), parents(P,_,B), A\=B) ; (parents(_,P,A), parents(_,P,B), A\=B).

sister(X, Y) :- woman(X), ((parents(F,_,X)), (parents(F,_,Y)); ((parents(_,M,X)), (parents(_,M,Y)).

uncle(U,N) :- man(U), (siblings(U,M); siblings(U,F)), parents(M, F, N).
aunt(U,N) :- woman(U), (siblings(U,M); siblings(U,F)), parents(M, F, N).

grandparent(G,N) :- (parents(G,_,X), parents(X,_,N)); (parents(_,G,X), parents(_,X,N)).

grandpa(G,N) :- (parents(G,_,X), parents(X,_,N)); (parents(_,G,X), parents(_,X,N)), man(G).
grandma(G,N) :- (parents(G,_,X), parents(X,_,N)); (parents(_,G,X), parents(_,X,N)), woman(G).

The question is, I don't know if I did it right - especially the siblings, uncle, aunt, grandpa and grandma relations. Could somebody say if it's good or not? Thank you.


texts: Query URL parameters in downloading pictures from network cameras

texts:
I have some URLs saved in my database, to download pictures from network cameras. Because each camera has it's own URL and parameters, we have to store the entire URL in a field in the database.

My code gets this URL from the database, creates a WebClient to make the call and downloads the byte array from it.

Some cameras use security credentials that we save as parameters in the URL, they are saved like this because it was determined it would be this way, I would have preferred to have fields in the database with username and password, but they decided to go this way, so my code got more messy.

Here is the part of the code that deals with the credentials:

var uri = new Uri(url);
if (uri.Query.Length > 0)
{
    var querys = uri.Query;
    if (querys.Contains("username") && querys.Contains("password"))
    {
        var userName = querys.Split('&').SkipWhile(x => !x.StartsWith("username")).First().Split('=').Last();
        var password = querys.Split('&').SkipWhile(x => !x.StartsWith("password")).First().Split('=').Last();
        var type = querys.Contains("type") ? querys.Split('&').SkipWhile(x => !x.StartsWith("type")).First().Split('=').Last() : "Digest";

        cache = new CredentialCache { { uri, type, new NetworkCredential(userName, password) } };
    }
}

Later on the code I will use the cache variable in the WebClient to make the call with it.

I used a lot of LINQ here to get the username and password from the URL.

My questions here are:

Is my code readable enough?
Is it the best approach? If not, how could I have made this better?
Should I be worried about performance in this implementation?

Here is an example of the URL:

http://192.168.2.33/cgi-bin/video.cgi?msubmenu=jpg&username=admin&password=4321&type=Digest


texts: Parse a contrived message protocol with first byte data length followed by data

texts:
I think this code to parse a contrived message protocol with first byte data length followed by data is a little ugly.  Has anyone got any suggestions on how to make it more elegant and more robust?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LENGTHBYTES 1

void splitmessages(unsigned char* bstream, int length);
void printmsg(unsigned char* msg);

int main() {

   unsigned char stream[] = {2, 'A', 'A', 1, 'B', 3, 'C', 'C', 'C', 1, 'D' };
   int len = sizeof(stream) / sizeof(stream[0]);

   printf("\nTest 1 - four messages together\n");
   splitmessages(stream, len); //works

   printf("\nTest 2 - two complete msgs, then 2 complete msgs\n");
   splitmessages(stream, len-2);  //works
   splitmessages(stream+9, 2);

   //split across a message - in data
   printf("\nTest 3 - messages split across data part\n");
   splitmessages(stream, len-4);  //works
   splitmessages(stream+7, 4);

   //split across a message - just after size
   printf("\nTest 4 - messages split just after size part\n");
   splitmessages(stream, len-5);
   splitmessages(stream+6, 5);

   //split across a message - just before size
   printf("\nTest 5 - messages split just before size part\n");
   splitmessages(stream, len-6);
   splitmessages(stream+5, 6);

   return 0;
}

void splitmessages(unsigned char* bstream, int length) {
   //Create msg as soon as you have size and save as static
   static unsigned char* msg = 0;
   static int tempbufposition = 0;
   static int tocompletemsg = 0;

   enum STAGE { SIZE, DATA };
   STAGE stage = SIZE;
   int size = 0;

   //adjust stage to DATA if already have start of msg
   if (tocompletemsg != 0)
      stage = DATA;

   //get cached size
   if(tempbufposition != 0 && msg)
      size = msg[0];

   for(int i=0; i<length; ++i){
     switch(stage) {
     case SIZE:
       size = bstream[i];
       if(msg) {
            free(msg);
            msg = 0;
            tempbufposition = 0;
            tocompletemsg = 0;
        }
        //re-create complete msg so add 1 byte for size
        msg = (unsigned char*)malloc(size+LENGTHBYTES);
        msg[0] = size;
        tempbufposition = 1;
        tocompletemsg = size;

        stage = DATA;
      break;
      case DATA:
         //do we have enough data for a complete message
         if(i + tocompletemsg <= length) {
            memcpy(msg+tempbufposition, &bstream[i], tocompletemsg);
            printmsg(msg);
            stage = SIZE;
            i += tocompletemsg-1;
            tocompletemsg = 0;
            tempbufposition = 0;
         } else {
            //add available data
            memcpy(msg+tempbufposition, &bstream[i], length-i);
            tempbufposition +=(length-i);
            tocompletemsg -= (length-i);
            i += (length-i)-1;
         }

           break;
         }
   }
}

void printmsg(unsigned char* msg) {
   if(msg && *msg) {
       int size = msg[0];
       printf("%d ", msg[0]);
       for(int i = 1; i <= size; ++i)
          printf("%c ", msg[i]);

       printf("\n");
   }
}


texts: Idiomatic Rust matches with pattern guards

texts:
I'm quite new to Rust, and am working on a virtual machine image decompiler. I have some working code that uses match to check opcode numbers, but it doesn't feel very idiomatic, and am wondering what alternatives I should consider.
First up is the cleanest case:
    // Stop, or next instruction?
    let next = match opcode {
        28 | 139 | 140 | 176 | 177 | 179 | 181 ..= 184 | 186 | 188 | 228 | 243 | 244 | 246 => None,
        _ => Some(image.position() as u32),
    };

I have only two paths here, and no guards. This seems like the kind of situation that match is ideal for. However, it is a lot of magic numbers.
This following match needs to guarded patterns because some of the opcodes change structure based on the image version. The same variable will be stored in each case however, so I used a match to produce a bool, and then took that to an if branch. Originally I just had a simple match statement and duplicated the Some(image.get_u8()). I'm still not sure that it wasn't better that way.
    // Store variable
    let store = if match opcode {
        8 | 9 | 15 ..= 25 | 129 ..= 132 | 136 | 142 | 143 | 224 | 231 | 236 | 246 ..= 248 |
            1000 ..= 1004 | 1009 | 1010 | 1012 | 1030 => true,
        181 | 182 if version == 4 => true,
        185 | 228 if version >= 5 => true,
        _ => false,
    } {
        Some(image.get_u8())
    } else {
        None
    };

Lastly we have a match with only one guarded pattern, but a much more complex calculation to follow, so I didn't want to just duplicating the code for each pattern.
    // Branch offset
    let branch = if match opcode {
        1 ..= 7 | 10 | 128 ..= 130 | 140 | 189 | 191 | 247 | 255 => true,
        181 | 182 if version == 3 => true,
        _ => false,
    } {
        let first_branch_byte = image.get_u8();
        let iftrue = first_branch_byte & 0x80 != 0;
        let twobytes = first_branch_byte & 0x40 == 0;
        let offset: i16 = if twobytes {
            (((((first_branch_byte & 0x3F) as u16) << 8) | image.get_u8() as u16) << 2) as i16 >> 2
        } else {
            (first_branch_byte & 0x3F) as i16
        };
        Some(Branch {
            iftrue,
            offset,
        })
    } else {
        None
    };

Because of all the magic numbers, I have considered whether it would be better to try to make some macros to produce the patterns from data elsewhere, or if I should just test for data in a HashMap instead of using match.


texts:
I am building a 2d dictionary with an altered list at the end Afterwords I want to find the min of each list. Is there a better way to do it? Better being faster or at least less of an eyesore.

#dummy function, will be replaced later so don't worry about it.
def alter(x, y, z,):
    a = list(x)
    for i, val in enumerate(x):
         a[i] = val + y + z
    return a

masterStats = {}
askStats = [0, 1, 2]
for numberServed in range(3):
    masterStats[numberServed] = {}
    for timeToServe in range(3):
        masterStats[numberServed][timeToServe] = alter(askStats, numberServed, timeToServe)

for numberServed in masterStats.keys():
    for timeToServe in masterStats[numberServed].keys():
        print(min(masterStats[numberServed][timeToServe]))

for numberServed in masterStats.keys():
    print(numberServed)
    for timeToServe in masterStats[numberServed].keys():
        print("    " + str(timeToServe))
        print("        " + str(masterStats[numberServed][timeToServe]))


texts: LINQ transforming hierachical data to flat list

texts:
The following code is pretty ugly. I suspect that there is a more functional and elegant way of achieving this result.

var lines =
new[]{
    new{Head="A",Value="1"},
    new{Head="",Value="2"},
    new{Head="",Value="3"},
    new{Head="",Value="4"},
    new{Head="B",Value="5"},
    new{Head="B",Value="6"},
    new{Head="C",Value="7"},
    new{Head="",Value="8"},
    new{Head="D",Value="9"},
    new{Head="",Value="10"}};

string currentHead="";
string currentValue="";

lines.Select(line=>{
        string newHead;
        string newValue;
        if (String.IsNullOrEmpty(line.Head))
        {
            newHead = currentHead;
        } else
        {
            newHead = line.Head;
            currentHead = line.Head;
        }
        if (String.IsNullOrEmpty(line.Value))
        {
            newValue = currentValue;
        } else
        {
            newValue = line.Value;
            currentValue = line.Value;
        }
        return new{Head=newHead,Value=newValue};}).ToList();

The desired output is to produce

A,1

A,2

A,3

A,4

B,5

B,6

C,7

C,8

D,9

D,10


texts: Using PHP's __call() to emulate a Class instead of Extending

texts:
I recently started working on a project that had been dropped by the previous dev. When looking through the existing code, I came across this singleton Database Class.

class Database{
private static $instance;
private $PDOInstance;

// Customize when ready
private function __construct(){
    try{
        $this->PDOInstance = new PDO("mysql:database=testdb;unix_socket=/tmp/mysql.sock", "username" , "password"/* , array driver_options*/);
    }catch(PDOException $e){
        throw $e;
    }
}

public static function getInstance(){
    if(!self::$instance){
        try{
            self::$instance = new self();
        }catch(PDOException $e){
            return false;
        }
    }
    return self::$instance;
}

public function __clone(){
    trigger_error("Cloning forbidden on Singleton", E_USER_ERROR);
}

public function __wakeup(){
    trigger_error("Unserializing forbidden on Singleton", E_USER_ERROR);
}

// PDO Function Aliasing
public function __call($function, $args){
    if(method_exists($this->PDOInstance, $function)){
        return call_user_func_array(array($this->PDOInstance, $function), $args);
    }
    trigger_error("Unknown PDO Method Called: $function()\n", E_USER_ERROR);
}
}

I suppose my question revolves around the use of __call() to alias PDO functions. Is this the best way to go about it, and if not, what should be done instead?

As for why the database class doesn't simply extend PDO, from what I understand, PDO has a public __construct(), and when it gets extended, it isn't possible to change the visibility to private, hence this work around.

My instinct is to scrap this class and just rewrite it as a simple PDO wrapper, but I thought I would ask around first.


texts: create weekly data for stocks faster based on daily data


texts:
This is in ASP.NET MVC, but that shouldn't make a difference. I have a large number of rows in my database for Songs.

var songIndex = Context.Songs.ToList().FindIndex(x => x.Id == 500);
var songs = Context.Songs.OrderBy(x => x.Id).Skip(songIndex).Take(10);

However, the ToList() and OrderBy seem pretty heavy just to take the next next 10 songs after the element with Id of 500.

Is there a better way to do this so I don't have to modify the entire list?


texts:
This is a pretty simple FizzBuzz variant. I'm more interested in my use of C (this is my first bit of C code) than I am in my actual FizzBuzz implementation, although I'm always open to suggestions.

In particular I'm pretty certain that my string manipulations are horrific, but I don't really know where to start improving.

I've also added in a little debug utility that I've created, with the purpose of implementing some stuff with header files, as those are completely new to me. All it does is toggle whether a print method will do anything, based on a global flag; I'm not sure if this is actually useful, or if I'm overlooking a better equivalent.

FizzBuzz Source

#include <string.h>
#include "debug_util.c"

void evaluate(char*, int, int, char*);
const int MAX_STRING_LEN = 17;
const int MAX_WORD_LEN = 7;
const int MAX_DIGIT_COUNT_LEN = 4;
const bool LOCAL_DEBUG_FLAG = false;

int main()
{
    DEBUG = LOCAL_DEBUG_FLAG;
    int i;
    char output[MAX_STRING_LEN];
    char intVal[MAX_DIGIT_COUNT_LEN];

    printDebug("Initial Loop Start\n");

    for (i = 1; i <= 100; i++)
    {
        printDebug("Setting initial output to null\n\n");
        /* Set first value in array to null termination,
         * effectively clearing the array,
         * if it is only read as a sequential string */
        output[0] = '\0';

        snprintf(intVal, MAX_DIGIT_COUNT_LEN,"%d",i);

        evaluate(output, 3, i, "Fizz");
        evaluate(output, 4, i, "Buzz");
        evaluate(output, 5, i, "Sizzle");

        output[sizeof(output)] = '\0';

        if (output[0] == '\0')
        {
            strncat(output, intVal, MAX_DIGIT_COUNT_LEN);
        }

        printf("%s\n", output);
    }
}

void evaluate(char *buf, int factor, int value, char *result)
{
    printDebug("Evaluating || Factor: %d, Value: %d, Success Result: %s\n", factor, value, result);
    char temp[MAX_WORD_LEN];

    strncpy(temp, ((value % factor == 0) ? result : ""), MAX_WORD_LEN -1);

    printDebug("Evaluating complete || Result: \"%s\"\n\n", temp);

    //Check array is not empty
    if (value % factor == 0)
    {
        strncat(buf, temp, MAX_STRING_LEN -1);
    }
}

Debug Util Header

#ifndef C_EXAMPLES_DEBUG_UTIL_H
#define C_EXAMPLES_DEBUG_UTIL_H

#ifndef _STDIO_H_
#include <stdio.h>
#endif

#include <zconf.h>

#ifndef _STDBOOL_H
#include <stdbool.h>
#endif

extern bool DEBUG;

#endif //C_EXAMPLES_DEBUG_UTIL_H

Debug Util C Source

#include "debug_util.h"

bool DEBUG = false;

//Only prints if the global DEBUG flag has been set to true
//Replicates code from printf()
int printDebug(const char *format, ...)
{
    int done = 0;
    if (DEBUG)
    {
        va_list arg;

        va_start (arg, format);
        done = vfprintf (stdout, format, arg);
        va_end (arg);
    }

    return done;
}


texts: Send html with nonce for each script and style tag on each request

texts:
This working code inserts a nonce attribute and value for each style and script tag inside an HTML file, for each GET request. It is using Express. nonce1 and dirViews are already defined. limiter is for rate limiting and is a node module found on npm.

//on get homepage
app.get('/', limiter.middleware(), function(req, res, next) {
    //send an edited index.html containing nonces
    fs.readFile(dirViews+'/index.html', 'utf8', function(err, html){
        let newHTML = html.replace(/<script/g, '<script nonce="'+nonce1+'"').replace(/<style/g, '<style nonce="'+nonce1+'"');
        res.send(newHTML);
    });
});

I am unsure if this is the correct way to do this (set nonce attributes on each GET request), and whether my code follows best practices.


texts: Many interfaces and lots of inheritance vs few interfaces and less inheritance?

texts:
I have a Visual Studio Solution which has a bunch of Projects in it. One of these projects is called "Services" and is basically the junction point between all remaining projects. When I built it originally I made it as generic as possible so I can expand on it. At the time I only had to work with Entity Framework backed implementations of it, but now I've added QuickBooks to the mix as well. It mostly worked out well, but I saw the need to refactor and redesign bits and pieces of it. To that end I've spent most of yesterday doing that and I have new code that takes care of the weirdness I had before, but, I find myself using lots of interfaces and lots of inheritance and I'm not exactly comfortable with it. For example here's my "DbService" implementations:

public class DbService<TEntity> :
    Service<TRepository>,
    IDbQueryableService<TEntity>,
    IQueryableService<TEntity> {}

public class DbService<TEntity, TKey> :
    DbService<TEntity>,
    IDbGettableService<TEntity>,
    IGettableService<TEntity, TKey>,
    IRemovableService<TEntity, TKey>,
    IRestorableService<TEntity, TKey> {}

public class DbService<TEntity, TEntityFormItem, TKey> :
    DbService<TEntity, TKey>,
    IAddableService<TEntityFormItem, TKey>,
    IUpdatableService<TEntityFormItem, TKey> {}

public class DbService<TEntity, TEntityFormItem, TEntityListItem, TKey> :
    DbService<TEntity, TEntityFormItem, TKey>,
    IDbListableService<TEntityListItem>,
    IListableService<TEntityListItem> {}

public class DbService<TEntity, TEntityFormItem, TEntityListItem, TEntitySelectItem, TKey> :
    DbService<TEntity, TEntityFormItem, TEntityListItem, TKey>,
    IDbSelectableService<TEntitySelectItem>,
    ISelectableService<TEntitySelectItem> {}

This is very similar to my current code and allows me to only inherit from a base class that has the functionality I want. For example, if a TEntity can be listed, but doesn't need to be displayed as a select list, then I'll inherit from the fourth DbService. This way I know I can upgrade or downgrade my inheritance as I need to. That being said, it itself has a lot of inheritance between base classes and interfaces. There's six levels of base class inheritance and 12 interfaces.

So, this morning I tried to bring it all together a little bit and came up with this:

public class DbService2<TEntity, TEntityListItem, TEntitySelectItem, TKey> :
    Service<TRepository>,
    IDbReadableService<TEntity, TEntityListItem, TEntitySelectItem>,
    IReadableService<TEntity, TEntityListItem, TEntitySelectItem, TKey> {}

public class DbService2<TEntity, TEntityFormItem, TEntityListItem, TEntitySelectItem, TKey> :
    DbService2<TEntity, TEntityListItem, TEntitySelectItem, TKey>,
    IWritableService<TEntity, TEntityFormItem, TKey> {}

Now this version obviously reduces the depth of inheritance on the base classes to three and the interfaces to three, but, it forces me in a position where some inheriting TEntity services will not be using all of the features so I'd have to use placeholders to fill in some of the TEntity* parameters and that feels like it will end up dirtier in the long run than the first code sample.

Also, I do realize that I'm using lots of generic parameters, but it works for my needs and this not being a publicly exposed API, I'm OK with it.

So, my question for you fine folks is, am I being too zealous in trying to reduce the base class and interface inheritances or am I OK to continue as is, which has worked so far (referring to the original code I was refactoring which is very close to the first example)? Visual Studio gives the first example a maintainability index of 86.5% (average), and 82.5% (average) for the second example, so if I follow VS assessment, I should continue with the first example?


texts: Finding remainder of stepping by multiple beyond a limit

texts:
Summary: Looking for more elegant version of Math.ceil(a/b)*b - a.

I'm writing code (QML Canvas) that draws a timeline, with tick marks every n pixels.

// Stepping across the width of the window, drawing tick marks
for (var x=0; x<windowWidth; x+=n) drawTickAndLabelAt(x);

The timeline can be scrolled such that time=0 moves off the left edge of the window. I need to figure out the correct x value to start at so that the ticks are still drawn at the same time. That value is the multiple of n that is just larger than the scroll offset, minus the scroll offset.

This is the naive representation of that formula:

var firstTickX = Math.ceil(scrollOffset/n)*n - scrollOffset;
for (var x=firstTickX; x<windowWidth; x+=n) drawTickAndLabelAt(x);

This works, but the formula feels inelegant, referencing both variables twice. Can you think of a simpler code path (using modulus, I'm assuming) that I'm failing to think of?


texts:
I'm currently working myself through K&R and just read about implementing getch() and ungetch().

In K&R these functions are implemented like this:

#include <stdio.h>

#define BUFSIZE 100
char buf[BUFSIZE];     /* buffer for ungetch */
int bufp = 0;          /* next free position in buf */

int getch(void) /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)    /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

As you can see this is implemented like a stack (last in -> first out). This somehow bothers me. In the example:

ungetch('a');
ungetch('b');
ungetch('c');

getch()will return 'c' at the first function call. 'b' on the second function call and 'a' on the third function call. I liked the idea of getting the first 'ungetch()'-ed char at the start and the last 'ungetch'-ed char in the end.

This is what I did:

#include <stdio.h>

#define BUFSIZE 10
static int reorder_buf(void);

char buf[BUFSIZE];
int bufrp = 0;    //buffer read position
int bufwp = 0;    //buffer write position

int getch(void)
{
    if (bufrp < bufwp)
        return buf[bufrp++];
    else {
        if(bufwp != 0)
            bufwp = bufrp = 0;

        return getchar();
    }
}

void ungetch(int c)
{
    if (bufwp < BUFSIZE)
        buf[bufwp++]=c;
    else
    {
        if (reorder_buf() != 0)     //successful reorder
        {
            buf[bufwp++]=c;
        } else                      //full buffer
        {
            printf("Failed to ungetch(%c).\n", c);
        }
    }
}

/**
 * Tries to move buffer content to the start of the buffer.
 *
 * @return 1 on successful reorder, 0 otherwise
 */
static int reorder_buf(void)
{
    if (bufrp > 0)
    {
        int i;
        for(i = 0; bufrp < bufwp; bufrp++, i++)
             buf[i] = buf[bufrp];

        bufrp = 0;
        bufwp = i;
        return 1;
     } else
     {
         return 0;
     }
}

I also had the idea to replace the error message in ungetch() with returning an int, which includes the information if the unget process was successful and provides it to the caller.


texts:
I'm new to java and was just wondering if you could see anything wrong with my code. The program works but I have a feeling it's not the right way to do it.

public class ShoppingItem {

private String ItemName;
    private double ItemPrice;
    private int ItemQty;

public ShoppingItem()
{
        ItemName = "Fruit";
        ItemPrice = 100;
        ItemQty = 1;

}

    public ShoppingItem(String ItemName, double ItemPrice, int ItemQty )
{
        this.ItemName = ItemName;
        this.ItemPrice = ItemPrice;
        this.ItemQty = ItemQty;

}

public String getItemName() {
    return ItemName;
}

public double getItemPrice() {
    return ItemPrice;
}

public double getItemTotalPrice() {
    return ItemPrice * ItemQty;
}

public int getItemQty() {
    return ItemQty;
}

public void setItemName(String ItemName)
{
    this.ItemName = ItemName;
}

    public void setItempPrice(double ItemPrice)
{
    this.ItemPrice = ItemPrice;
}

    public void setItemQty(int ItemQty)
{
    this.ItemQty = ItemQty;
}

    @Override
public String toString()
{
    String state = ItemName + " -  €" + ItemPrice + " x " + ItemQty;
    return state;
}
}

import java.util.ArrayList;
import java.util.Scanner;

public class ShoppingList {

    ArrayList<ShoppingItem> list = new ArrayList<ShoppingItem>();
    //Add a new ShoppingItem to the list
         public void addItem()
    {
            System.out.println();
            System.out.println("enter in the name of your item");
            Scanner keyboard = new Scanner(System.in);
            String ItemName = keyboard.nextLine();

            System.out.println("enter in the price of your item");
            double ItemPrice = keyboard.nextDouble();

            System.out.println("enter in the Qty of your item");
            int ItemQty = keyboard.nextInt();

            ShoppingItem Item = new ShoppingItem(ItemName, ItemPrice,
                        ItemQty);
            list.add(Item);
            System.out.println("Item Added");
    }

    //Display list and total number of items.
         public void displayItem(){
             System.out.println( list.size()+ " items. ");
                for (ShoppingItem x : list) {
                    System.out.println(x.toString());
                }

                 }

 }

import java.util.Scanner;
public class Application {

    public static void main( String [] args) {
        Scanner input = new Scanner(System.in);
        ShoppingList myList = new ShoppingList();
        int userOpt = 0;
        while (userOpt != 3) {
            System.out.println("");
            System.out.println("----- Shopping List------");
            System.out.println("(1) Add an item to the list. ");
            System.out.println("(2) Display list and total number of items. ");
            System.out.println("(3) Exit. ");
            userOpt = input.nextInt();

            if (userOpt == 1) {
            myList.addItem();

            }

            if (userOpt == 2) {
            myList.displayItem();
            }
        }
    }
}


texts: Setting QProgressBar values based on selection

texts:
I have a function which writes a report based on technologies selected by the user via QCheckBoxes. Depending on the number of technologies chosen, the QProgressBar will go through set values until the function reaches completion.

For example:

1 tech: 0 -> 99 -> 100
2 tech: 0 -> 50 -> 99 -> 100
3 tech: 0 -> 33 -> 66 -> 99 -> 100
4 tech: 0 -> 25 -> 50 -> 75 -> 99 -> 100

Regardless of the number of technologies chosen, once the last one has been processed, the progressbar would be set to 99 to do some textual clean up before reaching 100.

At the moment, I have two such technologies (PV and wind turbine) where I manually set the progress values.

How could I achieve the above in a more systematic fashion?

My current code:

def report(self):
    # Define progress bar
    progressMessageBar = iface.messageBar().createMessage(str('Generating report...'))
    progress = QProgressBar()
    progress.setMaximum(100)
    progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
    progressMessageBar.layout().addWidget(progress)
    iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO)
    progress.setValue(0)
    sleep(5)

    # Define Report text browser
    display_report = self.report_dockwidget.report_textBrowser
    # Technology checkboxes
    pv_checkBox = self.pv_generation_dockwidget.returnResults_Checkbox
    wind_checkBox = self.wind_generation_dockwidget.returnResults_Checkbox

    # For PV
    if pv_checkBox.isChecked():
        # Do some processing
        progress.setValue(50)
        if not wind_checkBox.isChecked():
            progress.setValue(99)
        sleep(5)

    # For Wind
    if wind_checkBox.isChecked():
        # Do some processing
        if not pv_checkBox.isChecked():
            progress.setValue(50)
        else:
            progress.setValue(99)
        sleep(5)

    # Do some cleanup
    progressMessageBar.setText('Complete')
    progress.setValue(100)
    sleep(1)

    # Show report
    self.report_dockwidget.show()


texts: Implementation of a new algorithm for sklearn

texts:
In the Python library, sklearn is implemented the algorithm for SparsePCA.

I have written the code for a another version of this algorithm that is much faster in some situations.  I have not enough experience with Python and sklearn in order to write code that could be loaded in the sklearn repositories.

It would be nice if you can help me to write this code in order to make it 100% compatible with the sklearn standards. If you have experience with machine learning would be nice if you help me to consider bad situations that I may have not considered in order to make the algorithm more robust.

import numpy as np
import sklearn as sk
import pandas as pd
from sklearn.decomposition import SparsePCA, PCA

import random

class IterativeSPCA():

    def __init__(self, Npc=None, alpha=1, max_iter=5000, tol=1e-8):
        self.Npc = Npc #number of components
        self.alpha = alpha  # penalty value
        self.max_iter = max_iter # max number of iteration
        self.tol = tol # accepted tollerance error

    def spca_iterate(self, u_old, v_old):
        # this is the equivalent of the nipals algorithm but designed in order to
        # obtain a sparse loading
        v_new = np.zeros(shape=v_old.shape)
        u_new = np.zeros(shape=u_old.shape)

        for iteration in range(self.max_iter): #repeat the iteration non more than max iter
            y = np.dot(self.X.T, u_old).squeeze()
            v_new = (np.sign(y)*np.maximum(np.abs(y)-self.alpha, 0)).squeeze()
            norm_v = np.linalg.norm(v_new)**2
            if norm_v == 0: #if norm v is 0 it means that no components have been selected. So you should reduce the penalty lambda

                break

            x_times_v = np.dot(self.X, v_new)
            x_times_v.shape = (self.m, 1)
            u_new = x_times_v/np.linalg.norm(x_times_v)

            if np.linalg.norm(v_new)==0:#check again if the norm is 0
                break
            if np.linalg.norm(v_new - v_old)<self.tol or np.linalg.norm(-v_new - v_old) < self.tol:#check if there is convergence
                break
            u_old = u_new
            v_old = v_new

        if iteration == self.max_iter-1:
            print("No Convergence. Error!!!")

        norm_v = np.linalg.norm(v_new)
        v_new.shape = (self.n, 1)
        v_final = sk.preprocessing.normalize(v_new, axis=0)
        u_final = u_new * norm_v
        return v_final, u_final

    def fit(self, X):

        self.m, self.n = X.shape
        self.components_ = np.zeros(shape=(self.n,self.Npc))
        self.sT = np.zeros(shape=(self.m,self.Npc))
        self.X = X

        for i in range(self.Npc):

            pca = PCA(n_components=1).fit(self.X)
            v = pca.components_
            v = sk.preprocessing.normalize(v)
            u = self.X.dot(v.T)
            s = np.linalg.norm(u)

            u_old = u
            v_old = v*s

            v_final, u_final = self.spca_iterate(u_old=u_old, v_old=v_old)
            self.sT[:, i] = u_final.squeeze()
            self.components_[:, i] = v_final.squeeze()
            u_final.shape = (self.m, 1)
            self.X = self.X-np.dot(u_final, v_final.T)
        return self.components_, self.sT

print("start")
X = np.random.random((100, 20)) #generate a random matrix
X = sk.preprocessing.scale(X)   # scale the data
alpha = 1 # set the penalty
nPCs = 2 # set the number of components

import time

start_time = time.time()
a = IterativeSPCA(Npc=nPCs, alpha=alpha)
sP, sT = a.fit(X)
time1 = time.time()

spca = SparsePCA(n_components=nPCs, alpha=alpha, ridge_alpha=0)
spca.fit(X)
time2 = time.time()

import pandas as pd
df = pd.DataFrame(columns=['it_spc1','spc1'])
df['it_spc1'] = a.components_[:,0]
df['spc1'] = spca.components_.T[:,0]
df['it_spc2'] = a.components_[:,1]
df['spc2'] = spca.components_.T[:,1]
print("time iterative SPCA=", time1-start_time, "time SparsePCA=", time2-time1)
print("finish!")


texts: Unbounded Sieve of Eratosthenes in Swift

texts:
I've spent a while teaching myself Swift, and decided to take on the challenge of writing an unbounded Sieve of Eratosthenes to challenge myself. This is actually the first time I've written an unbounded sieve, as well as the first large Swift program I've written, so all comments are appreciated!

This was written using Swift 3 in Xcode 8 beta 3, so it should work on Swift 3.0 Preview 2 from swift.org, but I have not tested it.

public struct PrimeSequence: Sequence {
    private let stop: StoppingPoint

    /// Construct a sequence of primes up to a max.
    ///
    /// - note: This constructor is eager.
    ///
    /// - complexity: `O(log n)`
    ///
    public init(max: Int) {
        self.stop = .precompute([1] + sieveOfEratosthenes(n: max))
    }

    public init(terms: Int? = nil) {
        self.stop = .terms(terms)
    }

    public func makeIterator() -> AnyIterator<Int> {
        switch (stop) {
        case .precompute(let primes):
            return AnyIterator(primes.makeIterator())
        case .terms(let terms):
            var sieve = UnboundedSieve()
            var term = 0
            return AnyIterator {
                term += 1
                if let terms = terms, term > terms {
                    return nil
                }
                if term == 1 {
                    return 1
                } else {
                    return sieve.next()
                }
            }
        }
    }

    private enum StoppingPoint {
        case precompute([Int])
        case terms(Int?)
    }
}

///
/// Lazy, Unbounded, Sieve of Erathosthenes.
///
/// See https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
///
private struct UnboundedSieve: IteratorProtocol {

    var sieve: PriorityQueue<PrimeCounter>
    var counter = 2

    init() {
        sieve = PriorityQueue { $0.composite < $1.composite }
    }

    private struct PrimeCounter {
        let prime: Int
        var composite: Int
        func next() -> PrimeCounter {
            return PrimeCounter(prime: prime, composite: composite + prime)
        }
    }

    mutating func next() -> Int? {
        while let catcher = sieve.peek(), catcher.composite == counter {
            while let catcher = sieve.peek(), catcher.composite == counter {
                sieve.replaceTop(with: catcher.next())
            }
            counter += 1
        }
        defer {
            sieve.enqueue(PrimeCounter(prime: counter, composite: counter + counter))
            counter += 1
        }
        return counter
    }
}

///
/// Mutating Sieve of Erathosthenes.
///
/// Source: https://developer.apple.com/videos/play/wwdc2015/414/ @ 8:15
///
/// I would use the more "swifty" version @ 10:00, but this is the "true" sieve.
///
/// Complexity: `O(n log log n)`
///
private func sieveOfEratosthenes(n: Int) -> [Int] {
    var numbers = [Int](2..<n)
    for i in 0..<n-2 {
        let prime = numbers[i]
        guard prime > 0 else { continue }
        for multiple in stride(from: 2 * prime-2, to: n-2, by: prime) {
            numbers[multiple] = 0
        }
    }
    return numbers.filter { $0 > 0 }
}

I'm using a heap-based PriorityQueue, whose implementation doesn't matter, but here's the protocol pseudocode:

protocol PriorityQueue<T> {
    init(sort: (T, T) -> Bool)
    enqueue(_ element: T)
    dequeue() -> T?
    peek() -> T?
    replaceTop(with value: T)
}

For the purposes of this review, you can assume that it is accurate (but you can see it here if you want).


texts: Applying a formula to 2D numpy arrays row-wise

texts:
The user has two 2D input arrays A and B, and a given matrix S. He wants to apply a
complicated formula to these arrays row-wise to get C. Something like: $$C_i = f(S, A_i, B_i)$$
where f is some complicated function, implemented by the user. That is, the user wants to supply his complicated formula in terms of the row vectors, and whatever additional data is necessary for that formula. The implementation of the formula must be a function.

For the sake of this example only, the complicated formula will be
the dot product, and the "additional data" for the formula will be the
identity matrix. The real application is a lot more complicated.

My question is: How can I express the line

 C = np.fromiter(map(partial(users_formula, S), A, B), dtype=np.float64)

in a cleaner way in Numpy? Speed or memory consumption is not a major concern, but code readability is. I suspect that there is a better way to do it in Numpy.

from __future__ import print_function
from functools import partial
import numpy as np

def main():
    # Some dummy data just for testing purposes
    A = np.array([[-0.486978,  0.810468,  0.325568],
                  [-0.640856,  0.640856,  0.422618],
                  [-0.698328,  0.628777,  0.34202 ],
                  [-0.607665,  0.651641,  0.45399 ]])
    B = np.array([[ 0.075083,  0.41022 , -0.908891],
                  [-0.025583,  0.532392, -0.846111],
                  [ 0.014998,  0.490579, -0.871268],
                  [-0.231477,  0.401497, -0.886125]])
    S = np.identity(3)
    #---------------------------------------------------------------
    # The problematic line is below. What is the proper way to
    # express this in Numpy?
    C = np.fromiter(map(partial(users_formula, S), A, B), dtype=np.float64)
    assert np.allclose(C, 0.0, atol=1.0e-6), C
    print('Done!')

def users_formula(S, a, b):
    # a == A_i, b == B_i
    # In the real application, the user gives his complicated
    # formula here. The matrix S stays the same, the A_i
    # and B_i are the row vectors of A and B, respectively.
    # We have no control over the implementation of the formula,
    # but it must be a function.
    return np.dot(a, np.dot(S, b))

if __name__ == '__main__':
    main()


texts:
I was wondering why the following implementation of a Suffix Tree is 2000 times slower than using a similar data structure in C++ (I tested it using python3, pypy3 and pypy2). I know the bottleneck is the traverse method, do you spot chance of optimisation in the following code? Thanks!

from sys import stdin, stdout, stderr, setrecursionlimit
setrecursionlimit(100000)

def read():
    return stdin.readline().rstrip()

def readint():
    return int(read())

def make_node(_pos, _len):
    global s, n, sz, to, link, fpos, slen, pos, node
    fpos[sz] = _pos
    slen[sz] = _len
    sz += 1
    return sz-1

def go_edge():
    global s, n, sz, to, link, fpos, slen, pos, node
    while (pos > slen[to[node].get(s[n - pos], 0)]):
        node = to[node].get(s[n - pos], 0)
        pos -= slen[node]

def add_letter(c):
    global s, n, sz, to, link, fpos, slen, pos, node
    s[n] = c
    n += 1
    pos += 1
    last = 0
    while(pos > 0):
        go_edge()
        edge = s[n - pos]
        v = to[node].get(edge, 0)
        t = s[fpos[v] + pos - 1]
        if (v == 0):
            to[node][edge] = make_node(n - pos, inf)
            link[last] = node
            last = 0
        elif (t == c):
            link[last] = node
            return
        else:
            u = make_node(fpos[v], pos - 1)
            to[u][c] = make_node(n - 1, inf)
            to[u][t] = v
            fpos[v] += pos - 1
            slen[v] -= pos - 1
            to[node][edge] = u
            link[last] = u
            last = u
        if(node == 0):
            pos -= 1
        else:
            node = link[node]

def init_tree(st):
    global slen, ans, inf, maxn, s, to, fpos, slen, link, node, pos, sz, n

    inf = int(1e9)
    maxn = len(st)*2+1 #int(1e6+1)
    s = [0]*maxn
    to = [{} for i in range(maxn)]
    fpos, slen, link = [0]*maxn, [0]*maxn, [0]*maxn

    node, pos = 0, 0
    sz = 1
    n = 0

    slen[0] = inf
    ans = 0
    for c in st:
        add_letter(ord(c))

text = "TTTTTTTTTT" + 1777*"A" + "$"
query = 1750*"A"

def traverse_edge(st, idx, start, end):
    global len_text, len_st
    k = start
    while k <= end and k < len_text and idx < len_st:
        if text[k] != st[idx]:
            return -1
        k += 1
        idx += 1
    if idx == len_st:
        return idx
    return 0

def edgelen(v, init, e):
    if(v == 0):
        return 0
    return e-init+1

def dfs(node, leafs, off):
    if not node:
        return
    k, tree = node
    if not isinstance(tree, int): # it is a node pointing to other nodes
        for kk, value in tree.items():
            if slen[value] > 190000000:
                leafs.append(fpos[value]-off)
            else:
                dfs((kk, to[value]), leafs, off+slen[value])

def traverse(v, st, idx, depth=0):
    global len_st
    result = cache.get((v, st), -2)
    if result != -2:
        return result
    r = -1
    init = fpos[v]
    end = fpos[v]+slen[v]
    e = end-1
    if v != 0:
        r = traverse_edge(st, idx, init, e)
        if r != 0:
            if r == -1:
                cache[(v, st)] = []
                return []
            depth += r
            # Here is when we found a match
            leafs = []
            dfs((v, to[v]), leafs, depth)
            #return reversed(leafs)
            return leafs
    idx = idx + edgelen(v, init, e)
    if idx > len_st:
        cache[(v, st)] = []
        return []
    k = ord(st[idx])
    children = to[v]
    if k in children:
        vv = children.get(k, 0)
        matches = traverse(vv, st, idx, depth)
        cache[(v, st)] = matches
        return matches
    return []

def main():
    global text, len_st, len_text, cache
    init_tree(text)
    len_text = len(text)
    len_st = len(query)
    r = []
    #cache = {}
    for runs in range(1000):
        cache = {}
        matches = traverse(0, query, 0)
        r.append("\n".join(str(m) for m in matches))
    stdout.write("\n".join(r)+"\n")

main()


texts:
I am trying to implement A* search on a grid in MATLAB. I am currently using a priority queue class I found here, but it's a bit slow. I tried to write this simple priority queue class in MATLAB:

classdef PQ2 < handle

    properties
        nElements
        indx;
        priorityList;
        valueList;
    end

    methods
        function thePQueue = PQ2()
            thePQueue.nElements = 0;
            thePQueue.priorityList = NaN*ones(500,1);
            thePQueue.valueList{500} = [];

            thePQueue.indx = 1;
            thePQueue.nElements = 0;
        end

        function push(thePQueue, value, priority)
            thePQueue.priorityList(thePQueue.indx) = priority;
            thePQueue.valueList{thePQueue.indx} = value;
            thePQueue.indx = thePQueue.indx + 1;
            thePQueue.nElements = thePQueue.nElements + 1;
        end

        function minPriorityElement = pop(thePQueue)
            if ~thePQueue.isEmpty
                thePQueue.nElements = thePQueue.nElements - 1;
                [~, minPriorityIndx] = min(thePQueue.priorityList);
                minPriorityElement = thePQueue.valueList{minPriorityIndx};

                thePQueue.priorityList(minPriorityIndx) = NaN;
            else
                disp('Queue is empty');
            end
        end

        function flagIsEmpty = isEmpty(thePQueue)
        flagIsEmpty = (thePQueue.nElements == 0);
        end
    end
end

The above code is at least 3 times faster than the one I've mentioned above. I'm getting exactly the same output from these 2 classes, and therefore I believe that the code is correct, but I'm not 100% certain. How can I check it? Is there any other way I could implement the same idea and get a faster result?


texts:
I put together a function to sort out values that I am getting from a curl request for different 'devices', it works as is, I am only wondering if there is an easier way to to this.

function convert($deviceName, $namesArray, $devicesArray) {
    $result = array();
    foreach ($devicesArray as $d) {
        $result [] = [
            'Device Type' => $deviceName,
            'Device' => $d[0],
            $namesArray[0] => $d[1],
            $namesArray[1] => $d[2],
            $namesArray[2] => $d[3],
            $namesArray[3] => $d[4],
            $namesArray[4] => $d[5],
            $namesArray[5] => $d[6],
            $namesArray[6] => $d[7],
            $namesArray[7] => $d[8],
            $namesArray[8] => $d[9],
            $namesArray[9] => $d[10]
        ];
    }
    return $result;
}

it takes in the following:

$namesArray = [ Operating System, Physical Size, Physical Size, Width, Height, Device-width, Px Per Inch, Px Density, Aspect Ratio, Popularity];

$devicesArray =
Array
(

    [0] => Array
            (
            [0] => iPhone 4 (4, 4S)
            [1] => iOS
            [2] => 3.5
            [3] => 8.9
            [4] => 640
            [5] => 960
            [6] => 320
            [7] => 326
            [8] => 200% XHDPI
            [9] => 2 : 3
            [10] => 8.8
            )

    [1] => Array
            (
            [0] => iPhone 5 (5c, 5s)
            [1] => iOS
            [2] => 4.0
            [3] => 10.0
            [4] => 640
            [5] => 1136
            [6] => 320
            [7] => 326
            [8] => 200% XHDPI
            [9] => 40 : 71
            [10] => 7.9
            )
)

 and $deviceName field which can be 'Phone', 'Tablet' or 'Monitor'.

This gives the output

[0] => Array
        (
            [Device Type] => Phone
            [Device] => iPhone 4 (4, 4S)
            [Operating System] => iOS
            [Physical Size] => 8.9
            [Width] => 640
            [Height] => 960
            [Device-width] => 320
            [Px Per Inch] => 326
            [Px Density] => 200% XHDPI
            [Aspect Ratio] => 2 : 3
            [Popularity] => 8.8
        )

    [1] => Array
        (
            [Device Type] => Phone
            [Device] => iPhone 5 (5c, 5s)
            [Operating System] => iOS
            [Physical Size] => 10.0
            [Width] => 640
            [Height] => 1136
            [Device-width] => 320
            [Px Per Inch] => 326
            [Px Density] => 200% XHDPI
            [Aspect Ratio] => 40 : 71
            [Popularity] => 7.9
        )


texts:
After learning Javascript for quite some time, I began learning ReactJS and... I am confused with the proper design patterns.

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const Search = ({persons, filter}) =>
{
    const [name, setName] = useState(void 0);

    function search(event){
        event.preventDefault();
        filter(event.target.value.toLowerCase());
    }

    return (

Search

            <form onSubmit={search}>
                <input onChange={(event) => search(event)}/>
                <button type="submit">Search</button>
            </form>

    )
}

const Persons = ({persons}) =>
{
    function renderPersons(){
        const elements = [];

        persons.forEach(person => {
            if(person.show){
                elements.push(
{person.name} -- his/her telephone number: {person.phone}
);
            }
        });

        return elements;
    }

    return(

            {renderPersons()}

    )
}

const App = () =>
{
    const [ persons, setPersons ] = useState([
        { name: 'Arto Hellas', phone: '040-123456', show: true },
        { name: 'Ada Lovelace', phone: '39-44-5323523', show: true },
        { name: 'Dan Abramov', phone: '12-43-234345', show: true },
        { name: 'Mary Poppendieck', phone: '39-23-6423122', show:true }
    ]);

    const [ formInfo, setNewFormInfo ] = useState({name: '', phone: ''});

    function addPerson(event){
        event.preventDefault();

        let able = true;

        persons.forEach(person => { // checks if the person's name is already added
            if(person.name == formInfo.name)
                able = false;
        });

        if(able)
            setPersons(persons.concat({name:formInfo.name, phone:formInfo.phone, show:true}));
        else
            alert(`${formInfo.name} is already added to the list!`);
     }

    function filter(nameToFilter){
        if(nameToFilter === ''){ // if the search form is empty, then show everyone
            setPersons((prev) => prev.map(person => ({...person, show:true})));
        }
        else{
            const filtered = [];
            persons.forEach(person => {
                if(!person.name.toLowerCase().includes(nameToFilter))
                    filtered.push({...person, show:false});
                else
                    filtered.push({...person});
            });
            setPersons(filtered);
        }
    }

    return (

            <Search persons={persons} filter={filter} />

Phonebook

            <form onSubmit={addPerson}>

                    name: <input onChange={(event) => setNewFormInfo({name: event.target.value, phone: formInfo.phone})}/>

                    number: <input onChange={(event) => setNewFormInfo({name: formInfo.name, phone: event.target.value})}/>

                    <button type="submit">add</button>

            </form>

Persons

            <Persons persons={persons} />

    )
}

ReactDOM.render(<App />, document.getElementById("root"))

It works, but I have a feeling the code really is poorly designed; the course I am taking doesn't focus on details and motivates you to self-learn a lot.

I do have a specific question, though. Can I make persons a class? I just feel like in larger applications, each person would have methods and more variables; can I hold classes inside of React states instead of dicts?


texts:
I need to implement a Ring Buffer/FIFO for data coming from a TCP socket.

It must support the following operations:

Append a the recv()'ed chunk of bytes.
Allow me to peek at the beginning of the buffer, since i get differently-sized packets, and I must decode a small fixed-size header to know how many bytes to process.
Remove a chunk of bytes from the beginning of the buffer for processing.

I guess my needs are pretty standard for a TCP-based streaming protocol, but surprisingly I have never found a "best practice" method for doing this.

There are similar questions on SO already, most suggest to use collections.deque, which is fine but has some shortcomings that must be worked around for my needs:

It doesn't easily allow peeking.
It doesn't allow removal of chunks of bytes.

Mixing various suggestions I came up with the following implementation, which seems working but I wonder: can I do any better, performance-wise? Removing a single byte at a time in get() doesn't look optimal at all.

import collections
import itertools

class RingBuffer (object):
    """Ring buffer"""
    def __init__ (self, size = 4096):
            self._buf = collections.deque (maxlen = size)

    def put (self, data):
            """Adds data to the end of the buffer"""
            self._buf.extend (data)

    def get (self, size):
            """Retrieves data from the beginning of the buffer"""
            data = str ()
            for i in xrange (size):
                    data += self._buf.popleft ()
            return data

    def peek (self, size):
            """\"Peeks\" at the beginning of the buffer (i.e.: retrieves data without removing them from the buffer)"""
            return str (bytearray (itertools.islice (self._buf, size)))

    def len (self):
            """Returns the length of the buffer"""
            return len (self._buf)

If you are wondering why I am returning a string from peek(), that is because I need to process its return value with struct.unpack_from().


texts:
I have a segment of code:

/*functions return 4 if all digits are the same, 5 if digits are decreasing, 6 if digits are increasing, 7 if number's digits are bouncy.*/
        int variable = 0;
        cout << number << endl;
        variable = sameDigitsTest(number);
        if (variable == 0)
            variable = decreasingTest(number);
        if (variable == 0)
            variable = increasingTest(number);
        if (variable == 0)
            variable = bouncyTest(number);
        /*variable will not be zero any more, hence I do not test for the value zero*/
        if (variable == 4 || variable == 5 || variable == 6){
            cout << "The number is not bouncy." << endl;
            nonBouncyCounter++;
        }
        if (variable == 7){
            cout << "The number is bouncy." << endl;
            bouncyCounter++;
        }

How can I eliminate all of the if statements to make my code more compact? In fact I was thinking of including a function that includes the functions xTest, and then returning that value and then keeping the two if statements at the end.


texts:
I am trying to find the longest Collatz Sequence:

  Which starting number, ≤ N, produces the longest chain? If many possible such numbers are there print the maximum one.  (1 ≤ N ≤ 5×106)

I tried optimizing the code to include memoization still getting Time Limit Exceeded, for these solutions. Wanted some help to understand where the method is consuming time.

Implementation Using HashMap As Memoized Cache:

object CollatzSeq {
  private final val mapOfCollatzSequence =
    scala.collection.mutable.HashMap[BigInt, BigInt]()
      .withDefaultValue(0)

  def longestCollatzSeq(n: BigInt): BigInt = {
    def longestCollatzSeqHelper(n: BigInt, count: BigInt = 0): BigInt = {
      val mapValueOfN = mapOfCollatzSequence(n)
      n match {
        case n if n == 1 => count
        case _ if mapValueOfN != 0 =>
          count + mapValueOfN
        case n if n % 2 == 0 =>
          val updateForEven = longestCollatzSeqHelper(n/2, count + 1)
          mapOfCollatzSequence.update(n, updateForEven - count)
          updateForEven
        case n if n % 2 != 0 =>
          val c = longestCollatzSeqHelper(3 * n + 1 , count + 1)
          mapOfCollatzSequence.update(n, c - count)
          c
      }
    }
    longestCollatzSeqHelper(n)
  }
}

Implementation Using Array As Memoized Cache:

object CollatzSeq {

  // Using Array As Performance Is Better Than Map
  private final val collatzSeq = Array.fill[BigInt](5* 1000 * 1000)(0)
  def longestCollatzSeq(n: BigInt): BigInt = {
    def longestCollatzSeqHelper(n: BigInt, count: BigInt = 0): BigInt = {
      val countOfN = collatzSeq((n - 1).toInt)
      n match {
        case n if n == 1 => count
        case _ if countOfN != 0 =>
          count + countOfN
        case n if n % 2 == 0 =>
          val updateForEven = longestCollatzSeqHelper(n/2, count + 1)
          collatzSeq.update((n-1).toInt, updateForEven - count)
          updateForEven
        case n if n % 2 != 0 =>
          val updateForOdd = longestCollatzSeqHelper(3 * n + 1 , count + 1)
          collatzSeq.update((n-1).toInt, updateForOdd - count)
          updateForOdd
      }
    }
    longestCollatzSeqHelper(n)
  }
}

Performance Reference


texts:
I have been playing with JavaScript for some time now and made a simple canvas animation. I tried to make my code clean but I would like to hear your opinions about it.

GitHub

'use strict';

var Ball = function (options = {}) {
 var self = {};

 var x = options.x || 0;
 var y = options.y || 0;
 var width = options.width || 20;
 var height = options.height || 20;
 var color = options.color || '#aaaaaa';
 var verticalSpeed = options.verticalSpeed || 1;
 var horizontalSpeed = options.horizontalSpeed || 1;

 self.move = function () {
  x += horizontalSpeed;
  y += verticalSpeed;
 };

 self.verticalBounce = function () {
  verticalSpeed = -verticalSpeed;
 };

 self.horizontalBounce = function () {
  horizontalSpeed = -horizontalSpeed;
 };

 self.getX = function () {
  return x;
 };

 self.getY = function () {
  return y;
 };

 self.getWidth = function () {
  return width;
 };

 self.getHeight = function () {
  return height;
 };

 self.getColor = function () {
  return color;
 };

 self.getVerticalSpeed = function () {
  return verticalSpeed;
 };

 self.getHorizontalSpeed = function () {
  return horizontalSpeed;
 };

 return Object.seal(self);
};

var Board = function (options = {}) {
 var self = {};

 var objects = [];
 var canvas = options.canvas || document.getElementsByTagName('canvas')[0];
 var ctx = canvas.getContext('2d');

 var moveObjects = function () {
  objects.forEach(function (object) {
   object.move();
  });
 };

 var detectCollisions = function () {

  var wallCollision = function (object) {
   if (object.getX() <= 0 || (object.getX() + object.getWidth()) > canvas.width) object.horizontalBounce();
   if (object.getY() <= 0 || (object.getY() + object.getHeight()) > canvas.height) object.verticalBounce();
  };

  var areColliding = function (objectA, objectB) {
   return (
    objectA.getX() < objectB.getX() + objectB.getWidth() &&
    objectA.getX() + objectA.getWidth() > objectB.getX() &&
    objectA.getY() < objectB.getY() + objectB.getHeight() &&
    objectA.getHeight() + objectA.getY() > objectB.getY()
   );
  }

  objects.forEach(function (currentObject, index, objects) {
   wallCollision(currentObject);
   for (var i = index + 1; i < objects.length; i++) {
    var nextObject = objects[i];
    if (areColliding(currentObject, nextObject)) {
     if (Math.sign(currentObject.getHorizontalSpeed()) !== Math.sign(nextObject.getHorizontalSpeed())) {
      currentObject.horizontalBounce();
      nextObject.horizontalBounce();
     }
     if (Math.sign(currentObject.getVerticalSpeed()) !== Math.sign(nextObject.getVerticalSpeed())) {
      currentObject.verticalBounce();
      nextObject.verticalBounce();
     }
    }
   }
  });
 };

 var draw = function () {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  objects.forEach(function (object) {
   ctx.fillStyle = object.getColor();
   ctx.fillRect(object.getX(), object.getY(), object.getWidth(), object.getHeight());
  });
 };

 self.frame = function () {
  moveObjects();
  draw();
  detectCollisions();
 };

 self.addObject = function (object) {
  objects.push(object);
 };

 return Object.seal(self);
};

var ball1 = Ball();
var ball2 = Ball({horizontalSpeed: -1, x: 638, y: 123, color: '#ff0000', width: 25, height: 60, verticalSpeed: 2, horizontalSpeed: 2});
var ball3 = Ball({verticalSpeed: -1, x: 235, y: 453, color: '#00ff00', width: 75, height: 50});
var ball4 = Ball({horizontalSpeed: 1, x: 300, y: 300, color: '#0000ff', width: 50, height: 30});
var board = Board();

board.addObject(ball1);
board.addObject(ball2);
board.addObject(ball3);
board.addObject(ball4);

setInterval(board.frame, 1000/60);
body {
 background: #000;
 text-align: center;
}

canvas {
 background: #434343;
 border: 5px solid #323232;
}
<!doctype html>
<html>
<head>
 <link rel="stylesheet" href="css/main.css">
</head>
<body>
 <canvas width="800" height="600"></canvas>
</body>
</html>


texts: MD5 shuffling with a defined pattern of numbers

texts:
I've created a MD5 shuffler with a defined number pattern.  Does this make sense?  Will this make storing passwords more secure?  Is it efficient?

    <?php
echo "
";
$md5 = "e2fc714c4727ee9395f324cd2e7f331f";
echo "Old hash: " . $md5 . "
";
$hash = str_split($md5, 1);
$shuffle = explode(",", "24,29,21,23,2,30,10,22,6,28,26,11,8,19,9,20,16,3,0,14,18,15,12,25,5,4,31,1,7,27,13,17");
$newhash = "";
for ($i = 0; $i < 32; $i++) {
$s = $shuffle[$i];
$newhash .= $hash[$s];
}
echo "New Hash: " . $newhash . "
";
$newhash = str_split($newhash, 1);
$reverse = "";
for ($i = 0; $i < 32; $i++) {
$s = $shuffle[$i];
$reverse[$s]= $newhash[$i];
}
ksort($reverse);
$reversehash = "";
foreach ($reverse as $value) {
$reversehash .= $value;
}
echo"Reversed hash: " . $reversehash . "
";
echo "
";
?>


texts: Finding distance between vectors of matrices

texts:
So here is the problem:

Given 2D numpy arrays 'a' and 'b' of sizes  n×m  and  k×m
respectively and one natural number 'p'. You need to find the
distance(Euclidean) of the rows of the matrices 'a' and 'b'. Fill the
results in the  k×n  matrix. Calculate the distance with the following
formula
$$
D(x, y) = \left( \sum _{i=1} ^{m}
\left| x_i - y_i \right|^p
\right) ^{1/p}
; x,y \in R^m
$$
(try to prove that this is a distance). Extra points for writing
without a loop.

And here is my solution:
import numpy as np

def dist_mat(a, b, p):
    result = []
    print(result)
    for vector in b:
        matrix = a - vector
        print(matrix)
        result.append(list(((matrix ** p).sum(axis=1))**(1/p)))
    return np.array(result)

a = np.array([[1, 1],
              [0, 1],
              [1, 3],
              [4, 5]])
b = np.array([[1, 1],
              [-1, 0]])
p = 2
print(dist_mat(a, b, p))

I'm not sure about using Python list and then converting it into np.array, is there a better way?


texts: Namespacing jQuery/jQueryUi into markup that I don't control

texts:
I have a project that I've been trying to get just right for the past three months and it's still not quite there yet.

I'm injecting some jQuery and jQueryUI code into pages that I have no control over and I need to be able to "sandbox" my code away from anything that may or may not be there at DOM-ready, or at anytime there after...

I think I've got it, but I know there's most likely some edge cases and race conditions that I'm missing. Please fork this and tell me what I've missed.  I'm tired of spinning my wheels on this issue.

Markup:

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />

Loading multiple versions of jQuery!

Some other html

JavaScript:

;(function($, jQuery){

  var $h2 = $('
').append('Namespaced $: ' + $.fn.jquery + ' | $.ui: ' + $.ui.version);
  document.write($h2[0].outerHTML);

  var $jh2 = $('
').append('Namespaced jQuery: ' + jQuery.fn.jquery + ' | jQuery.ui: ' + jQuery.ui.version);
  document.write($jh2[0].outerHTML);

  //Verify that jQueryUi works on OUR version of jQuery:
  $(document).ready(function(){
    console.log($('h2.namespaced').draggable());
  });

})(myJQuery, myJQuery);


texts: Range Minimum Query Implementation in Scala

texts:
I would like to heat some feedback on this. I'm coming from a Java background and this is my first program in Scala. I solved Range Minimum Query problem.

object Solution {

  def main(args: Array[String]){
    val readInfo = readLine.split(" ");
    val numberofElements = Integer.parseInt(readInfo(0))
    val numberOfQuery = Integer.parseInt(readInfo(1))
    val storeElemets: Array[Int] =readLine.split(" ").map(_.toInt);
    val j =0;
    for(j<-0 until numberOfQuery){
      val z = readLine.split(" ")
      val from = Integer.parseInt(z(0))
      val to = Integer.parseInt(z(1))+1
      val i=from
      val getNumber = (from until to).map{i => storeElemets(i)}
      println(getNumber.min);
    }
  }
}

I would like to know, What are the best practices and is there any better way to implement this solution ?


texts:
I've written this code to get input from a file and count the repetition of number of that file and give output to another file. How can I make this code better?

#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

int main()
{
    ofstream outputFile("outPutData.txt");
    ifstream theFile ("inputData.txt");
    int MaxRange= 50;

    int myint[100]={0};

    int mycompare[90]={0};

    int mycount[90] = {0};

    int i = 0, j = 0, k = 0, sum = 0;

    for(j=0;j <= MaxRange;j++){
        mycompare[j] = j;
    }

    do
    {
        theFile>>myint[i];

        for(j=0;j<=MaxRange;j++)
            for(k=0;k<=MaxRange;k++)
            {

                j = k;
                if(myint[i] == mycompare[j])
                    mycount[k] = mycount[k]+1;
            }
        i++;

    }
    while((myint[i-1] >=0) && (myint[i-1] <= MaxRange));

    cout<< "The Number\t\t Frequency"<<endl;
    cout<<"------\t\t------"<<endl;

    for(k=0; k <=MaxRange ;k++)
    {

        if(mycount[k] != 0)
        {
            outputFile<<k<<"  "<<mycount[k]<<endl;
            cout<< k<<"\t\t"<<mycount[k]<<endl;

            sum = sum + mycount[k];
        }
    }

    cout<<"Total input from file  = "<<sum<<endl;

    return 0;
}

If I have the series of number in my input file like this:

9
9
9
6
6
5
3
7
9
1
2

It gives the output:

The Number  Frequency
---------   --------
1             1
2             1
3             1
5             1
6             2
7             1
9             4


texts: Is this a proper way to check a viewstate of type int?

texts:
In page load I'm saving a query string int value in a viewstate. Then I save it to my DB. Here is the code I use to retrieve viewstate value and validating it:

protected int CurrentCom
{
    get
    {
        if (ViewState["CurrentCom"] == null)
            return 0;
        else
        {
            int temp;
            if (int.TryParse(ViewState["CurrentCom"].ToString(), out temp))
                return temp;
            else return 0;
        }

    }
    set { ViewState["CurrentCom"] = value; }
}

Is there a better way to make this shorter?


texts:
I'm building an iOS app that uses web services extensively. I've built classes that handle the requests. However since there are a lot of web service request. I need to find out how to detect which web service to run, based on the action - registration, login, image upload, etc.

This is just a small snippet of a very large method I came up with:

- (BOOL) wsExecution:(int) wsID wsParameters: (NSDictionary*) parameters
{

    switch (wsID)
    {
        case WEB_SERVICE_ID
        {

            ClassWS* ws = [[ClassWS alloc] initWithURL:WEB_SERVICE_ID Url:WEB_SERVICE_URL];

            break;
        }
        case AAWEB_SERVICE_ID
        {

            ClassWS* ws = [[ClassWS alloc] initWithURL:AAWEB_SERVICE_ID Url:AAWEB_SERVICE_URL];

            break;
        }

The web service IDs are defined in a file called constants. I then map a URL to an ID in the method above. There are another 30 switch cases in this method. The Web Service IDs are just ints that have no relevance to the actual web service. It was just a way to check which service, based on a switch statement.

It makes it hard to read and I think it can be done better. Is there a way to do with and remove the notion of a web service ID completely?

To be a little more clear on where I am going with this:

Here is another example of the switch case (I have counted 200 cases):

switch (wsID)
    {
        case RUN_ORDER_WS_ID:
        {
            NSDictionary* postData = [NSDictionary dictionaryWithObject:[parameters objectForKey:@"OrderResponse"] forKey:@"OrderResponse"];

            NSMutableDictionary* newParams = [NSMutableDictionary dictionaryWithDictionary:parameters];

            OrderWS* ws = [[OrderWS alloc] initWithURL:RUN_ORDER_WS_ID Url:RUN_ORDER_WS_ID_WS_URL];
            self.placeClassifiedResponseWS = ws;
            ws.delegate = self;
            [newParams removeObjectForKey:@"OrderResponse"];
            [ws fetch:newParams PostDataValuesAndKeys:postData];
            [ws release];

            break;
        }
        case GET_LIST_OF_USERS_ID:
        {
            NSDictionary* postData = [NSDictionary dictionaryWithObject:[parameters objectForKey:@"userList"] forKey:@"userList"];

            NSMutableDictionary* newParams = [NSMutableDictionary dictionaryWithDictionary:parameters];

            UsersWS* ws = [[UsersWS alloc] initWithURL:GET_LIST_OF_USERS_ID Url:GET_LIST_OF_USERS_URL];
            self.userListWS = ws;
            ws.delegate = self;
            [newParams removeObjectForKey:@"userList"];
            [ws fetch:newParams PostDataValuesAndKeys:postData];
            [ws release];

            break;
        }
        case GET_USER_REVIEW_FROM_ITEMS_WS_ID:
        {
            NSString* itemId = [parameters objectForKey:@"itemId"];
            NSMutableDictionary* newParams = [NSMutableDictionary dictionaryWithDictionary:parameters];
            NSString* newURL = [NSString stringWithFormat:GET_USER_REVIEW_FROM_ITEMS_WS_URL, itemId];

            DataStoreWS = [[DataStoreWS alloc] initForComponents: [NSArray arrayWithObjects:REVIEW_COMPONENT, nil] WebserviceID: wsID Url:newURL];
            self.reviewOfUserWS = ws;
            ws.delegate = self;
            [newParams removeObjectForKey:@"itemId"];
            [ws fetch:newParams];
            [ws release];

            break;
        }


texts: Finding out which user has made the most progress

texts:
I have some code to accomplish the objective of finding out which user has made the most progress. Progress is measured in integer values, the higher the better. SubmittedAnswers consist of among others a int UserId and a int Progress.

The answers variable consist of a list of SubmittedAnswers as described above. To find out which user has made the most progress of this list I have the following algorithm:

/// <summary>
/// Method used to find out which user had made the most progress in a given time range.
/// </summary>
/// <param name="timeRange"></param>
/// <returns></returns>
public async Task<User> MostProgressAsync(ITimeRange timeRange)
{
    IList<SubmittedAnswer> answers = await GetAnswersInRange(timeRange);

    IEnumerable<IGrouping<int, SubmittedAnswer>> answersOfUsers = answers.GroupBy(a => a.UserId);

    int maxProgress = int.MinValue;
    var maxProgressUserId = 0;
    foreach (IGrouping<int, SubmittedAnswer> answersOfUser in answersOfUsers)
    {
        int progress = answersOfUser.Sum(a => a.Progress);
        if (progress > maxProgress)
        {
            maxProgress = progress;
            maxProgressUserId = answersOfUser.Key;
        }
    }

    return new User { UserId = maxProgressUserId };
}

SubmittedAnswers and User looks as follows:

public class SubmittedAnswer
{
    public ObjectId Id { get; set; }
    public int SubmittedAnswerId { get; set; }
    public BsonDateTime SubmitDateTime { get; set; }
    public bool Correct { get; set; }
    public int Progress { get; set; }
}

public class User
{
    public int UserId { get; set; }
}

Is this a proper way to accomplish this objective? Can it be improved?

Personally I would like to solve the issue a bit more functional, without declaring the variables above a foreach loop.


texts:
I have 2 validation groups, VG1 and VG2.  I have a button BtnInsert that saves data into Datasource. Its Validation Group is VG2. Now, I want to validate both VG1 and VG2 when a user clicks the BtnInsert.

protected void BtnInsert_click(object sender,EventArgs e)
{
    // validate VG1
    Page.Validate("VG1");
    // Page.Validate("VG2") is not required as BtnInsert is of that group
    if(Page.IsValid)
    {
       // call insert function
    }
}

Is this code right, and by clicking BtnInsert, both groups are validated?


texts:
I have 3 different functions I have tried in my programs. I want a function which continues to loop until an integer is entered. Which would be the best to  use? Or is there a better one?

def valid_int(question):
    """Creates a loop until an integer is entered"""
    py_version = find_version()
    if py_version == 3:
        response = input(question)
        while not response.isdigit():
            print("\nInvalid input! Input must be an integer")
            response = input(question)
        return int(response)
    else:
        response = raw_input(question)
        while not response.isdigit():
            print("\nInvalid input! Input must be an integer")
            response = raw_input(question)
        return int(response)

def valid_int(question):
    """Creates a loop until an integer is entered"""
    py_version = find_version()
    if py_version == 3:
        while True:
            response = input(question)
            try:
                return int(response)
            except ValueError:
                print("\nInvalid input! Input must be an integer")
    else:
        while True:
            response = raw_input(question)
            try:
                return int(response)
            except ValueError:
                print("\nInvalid input! Input must be an integer")

def valid_int(question):
    """Creates a loop until an integer is entered"""
    py_version = find_version()
    if py_version == 3:
        while True:
            response = input("Length of password: ")
            if response.isdigit()
                return int(response)
            print("\nInvalid input! Input must be an integer")
    else:
        while True:
            response = raw_input("Length of password: ")
            if response.isdigit()
                return int(response)
            print("\nInvalid input! Input must be an integer")


texts: Number of ways to make change for an amount

texts:
Task

Write a program that, given the amount to make change for and a list of coins prints out how many different ways you can make change from the coins to STDOUT.

My approach

The number to make change for is N. Take one coin C and sum the number of ways to make N - C with the other coins. Add the number of ways to make N - 2C with the other coins, etc, for all N - XC > 0 where X is the number of C coins used. Do that recursively. Memoize it so it's effectively dynamic programming.

Code

(ns hackerrank.core
  (:require [clojure.string :as string]))

(defn get-ways
  [n coins]
  (if (= n 0)
    1
    (if (= (count coins) 0)
      0
      (let [[coin & other-coins] coins]
        (reduce
          #(+ %1 (get-ways (- n (* coin %2)) other-coins))
          (if (= (mod n coin) 0) 1 0)
          (range 0 (/ n coin)))))))

(def get-ways-memoized
  (with-redefs [get-ways (memoize get-ways)] get-ways))

(let
  [n (Integer/parseInt (nth (string/split (read-line) #"\s+") 0))
   coins-line (read-line)
   coins (if (= "" coins-line)
           []
           (map #(Integer/parseInt %) (string/split coins-line #" ")))]
  (println (get-ways-memoized n coins)))

Questions

Any Clojure style / best practices, I'm mostly doing this to learn Clojure.
Any ideas why this wouldn't pass the timing tests on HackerRank. I've checked that the memoized function runs faster than the non-memoized one and AFAIK apart from the large stack resulting from no tail call optimization it should be equivalent to an iterative approach with a matrix storing the results.
Is there a way to do this manually, bottom-up rather than using memoize? Pseudo-code or a hint would be great as I'd like to try to implement it myself. Intuitively it feels like there can't be a bottom-up approach because I don't know in advance which sub-problems need to be solved.


texts: Implementation of Conway's Game Of Life on Android

texts:
I ended up using 2x 2D arrays with a one element border around everything to simplify the kernel logic.

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import java.util.Random;

public class WorldSimulation {

    long generation = 0;

    int[][]  next = null;
    int[][] current = null;

    float cellWidth;
    float cellHeight;

    int width;
    int height;

    public WorldSimulation(int width, int height, float w, float h)
    {
        this.width = width;
        this.height = height;

        next = new int[width+2][height+2];
        current = new int[width+2][height+2];

        cellWidth = (w / this.width);
        cellHeight = (h / this.height);
    }

    public void timeStep(Canvas canvas, Paint paint)
    {
        generation ++;

        for (int i = 0; i < next.length; i++) {
            System.arraycopy(next[i], 0, current[i], 0, next[0].length);
        }

        for(int i = 1; i < this.width+1; i++)
        {
            for(int j = 1; j < this.height+1; j++)
            {
                float left = (i * cellWidth);
                float top = (j * cellHeight);
                float right = (left + cellWidth);
                float bottom = (top + cellHeight);

                int status = current[i][j];

                int neighbours = livingNeighbours(i, j);

                if(status == 255) {
                    paint.setColor(Color.rgb(0, 255, 0));

                    canvas.drawRect(left-cellWidth,top-cellHeight,right,bottom,paint);

                    if (neighbours < 2) {
                        next[i][j]=0;
                    }
                    else if(neighbours >3)
                    {
                        next[i][j]=0;
                    }
                }
                else if(status!=255)
                {
                    paint.setColor(Color.rgb(0, status--, 0));
                    canvas.drawRect(left-cellWidth,top-cellHeight,right,bottom,paint);

                    if(neighbours == 3)
                    {
                        next[i][j] =  255;
                    }
                }
            }
        }
    }

    public int livingNeighbours(int i, int j) {
        int alive = 0 ;

        for(int kernelRow = i -1; kernelRow <= i+1; kernelRow ++)
        {
            for(int kernelCol = j -1; kernelCol <= j+1; kernelCol ++)
            {
                if(current[kernelRow][kernelCol]== 255 && !(kernelRow == i && kernelCol == j))
                {
                    alive ++;
                }
            }
        }
        return alive;
    }

    public void setCell(int i, int j, boolean alive)
    {
        next[i][j] =  255;
    }

}

The full implementation can be found here: https://github.com/jacasey/life/ and I've put a version up on the Google Play Store as well.

The whole thing clocks in at around 12 KB which I think is pretty cool when you compare it to the monters apps on the playstore today.

I was thinking of re-implementing this with a 1D array and indexing calculations but I don't think this would really add to much re: size or performance wise.

https://play.google.com/store/apps/details?id=com.jcasey.life