texts: Producing the intersection of several sequences

texts:
Based on this SO answer I have created a method that produce the set intersection of several sequences:

private static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<IEnumerable<TSource>> source)
{
    using (IEnumerator<IEnumerable<TSource>> sourceIterator = source.GetEnumerator())
    {
        //if there is no first element return an empty list
        if (!sourceIterator.MoveNext())
        {
            yield break;
        }

        IEnumerable<TSource> firstSequence = sourceIterator.Current;
        if (sourceIterator.MoveNext())
        {
            //create a hashset of the first sequence
            HashSet<TSource> hashSet = new HashSet<TSource>(firstSequence);

            //intersect the other sequences
            do
            {
                hashSet.IntersectWith(sourceIterator.Current);
            }
            while (sourceIterator.MoveNext());
            foreach (TSource element in hashSet)
            {
                yield return element;
            }
        }
        else
        {
            //if there is only one sequence, return it without any intersection
            foreach (TSource element in firstSequence)
            {
                yield return element;
            }
        }
    }
}

I'm particularly annoyed that the method is lot of times slower than the following implementation, when there is only one sequence:

public static IEnumerable<TSource>
          Intersect<TSource>(this IEnumerable<IEnumerable<TSource>> source)
{
    return source.Aggregate((x, y) => x.Intersect(y));
}

I already put a special test and code path when there is only one element, but it does not seems to be enough. Beside this problem, is there any obvious way to optimize the method?


texts: Counting the number of increasing sub-sequences

texts:
The problem is to find the number of increasing sub-sequence of a string with only digit characters.
Answer may be very large, so output it modulo 10^9+7.

I have been able to get a O(n) solution using segment trees. However , the the code is quite inefficient owing to loops with constant but large runtime. How can I make the code more efficient ?

The link to the exact problem statement is http://www.spoj.com/problems/LARSUBP/

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

typedef struct Tree_node
{
    int M[10][10] ;
    // M[i][j] = Number of sub-sequences starting with i and ending with j in the interval low to high in which it is called .
} TN ;

//Declaration of global variables

char number[50000] ;//Stores the input string
TN Tree[100000] ;//The array Tree[] is used to store the nodes of the segment tree
long long int convert ; //Other variables
int k1 , k2, i , j;

void Build_Tree( int node , int low , int high) ;

int main()
{
    // t is the number of test cases
    // N is the length of input string
    int t , N , counter ;

    //Stores the number of increasing sub-sequences
    long long int answer ;

    //No of test cases
    scanf("%d",&t) ;

    for(counter=0;counter<t;counter++)
    {
        scanf("%s",number) ;
        N = strlen(number) ;

        // Calling the build tree function
       Build_Tree(1,0,N-1) ;

        // Calculation of increasing sub-sequences using the Tree .
        answer = 0 ;
       for(i=0;i<10;i++)
       {
           for(j=i;j<10;j++)
           {
              answer = answer + Tree[1].M[i][j] ;
              answer= answer % 1000000007 ;
           }
       }
       answer = answer %1000000007 ;
       printf("%lld\n",answer) ;

    }
    return 0 ;
}

void Build_Tree( int node , int low , int high)
{

 // node stores the index of the Tree-node to be evaluated
 // low and high define the interval which we are considering

    int mid ;

    // Initialization of M[][]
    for(i=0;i<10;i++)
    {
        for(j=0;j<10;j++)
        {
            Tree[node].M[i][j] =0 ;

        }
    }

    if(low==high)
    {
        // Base case
        int temp = number[low]- '0' ;
        Tree[node].M[temp][temp] = 1 ;
    }
    else
    {
        mid = (low+high)/2 ;
        Build_Tree(2*node , low , mid) ; // Building the subtree of left child
        Build_Tree(2*node+1 , mid+1 , high) ; // Building the subtree of right child

    // Combining the information
    // No. of increasing sub-sequences starting with i and ending withj from low to highequal to sum of
    // 1.increasing sub sequences starting with i and ending with j from low to mid
    // 2.increasing sub sequences starting with i and ending with j mid+1 to high
    //3. all increasing sub-sequences starting with i and ending with k1 from low to mid multiplied by increasing sub sequences starting with k2 and ending with j from mid+1 to high where k1 < k2 .

        for(i=0;i<10;i++)
        {
            for(j=i;j<10;j++)
            {
                convert = Tree[2*node].M[i][j] + Tree[2*node+1].M[i][j] ;
                convert = convert % 1000000007 ;
                Tree[node].M[i][j] = convert ;

                if(i==j)
                {
                    continue ;
                }
                else
                {

                    for(k1=i;k1<j;k1++)
                    {
                        for(k2=k1+1;k2<=j;k2++)
                        {
                            convert = Tree[node].M[i][j] + Tree[2*node].M[i][k1] * Tree[2*node+1].M[k2][j] ;
                            convert = convert % 1000000007 ;
                            Tree[node].M[i][j] = convert ;

                        }
                    }
                }

            }
        }

    }

}


texts:
How can I eliminate repetition from this code?

std::vector<std::wstring> vec;
bool                      descending;
if (descending)
{
    std::sort(vec.begin(),
              vec.end(),
              std::greater<std::wstring>());
}
else
{
    std::sort(vec.begin(),
              vec.end(),
              std::less<std::wstring>());
}

I tried

std::sort(vec.begin(),
          vec.end(),
          descending
             ? std::greater<std::wstring>()
             : std::less<std::wstring>());

but it fails because greater and less do not evaluate to the same type.

Another question: is it possible to automatically retrieve the required type, std::wstring, from the object vec?


texts: Rearrange characters of a string into a palindrome, if possible

texts:
I have written Python code which works absolutely fine but I am looking for other ways to do this:

import itertools
def permutation(word):
   for i in range(len(word)+1):
      perms=list(itertools.permutations(word))
      for i in perms:
         j=(''.join(i))
         j=j.casefold()
         k=reversed(j)
         if list(j)==list(k):
            print("P")
            print(j)
word='Aabbccdd'
permutation(word)


texts:
I want to find the highest number in a time series, in the most efficient way.
To avoid iterating through all the look back periods, I'm only iterating in case the current high number has just been discarded. I'm avoiding enqueue dequeue for the same performance reasons.

What would be a faster algorithm?

class Program
{
    static Random r = new Random();
    static int LookBackPeriods = 5; //(small to facilitate visual functional test). eventually could be 100 1000, but not more than 5000.
    static double High=0;
    static int HighLocation = 0;
    static int CurrentLocation = 0;
    static double[] arr = new double[LookBackPeriods];

    static void Main(string[] args)
    {
        //functional test - generate 100 numbers and check them in as you go:
        for (int i = 0; i < 100; i++)
            CheckInCandidate(r.Next(10)); //in final application these will be real numbers
        Console.ReadLine();
    }

    /// <summary>
    /// A full iteration on all numbers (run only when the current high is overwritten)
    /// </summary>
    static void ReFindHighest()
    {
        High = arr[0];
        HighLocation =0
        for (int i = 1; i < LookBackPeriods; i++)
            if (arr[i] > High)
            {
                High = arr[i];
                HighLocation = i;
            }
    }
    /// <summary>
    /// minimized check that should run most of the time a new number arrives
    /// </summary>
    static void CheckInCandidate(double currentNum)
    {
        arr[CurrentLocation] = currentNum;
        if (currentNum >= High)
        {
            HighLocation = CurrentLocation;
            High = currentNum;
        }
        else if (CurrentLocation == HighLocation)
            ReFindHighest();

        CurrentLocation++;
        //if (CurrentLocation == HistoryLength) CurrentLocation=0; //is this faster??
        CurrentLocation = CurrentLocation % LookBackPeriods; //is this faster??
        Console.WriteLine("Current:" + currentNum + "\tHighest of " + LookBackPeriods + "last is " + High); //for validation purposes only.
    }
}


texts:
I'm a beginner. This is my implementation of binary search algorithm in Python. Please review my code and give your valuable inputs for further improvements on overall coding style, rare cases etc.

def binary_search(arr,value):
    left = 0
    right = len(arr) - 1
    while(left <= right):
        mid = (left + right) // 2
        print(mid)
        if arr[mid] is value:
            return mid
        elif value < arr[mid]:
            right = mid - 1
        elif value > arr[mid]:
            left = mid + 1

    return -1

def print_binary_search(arr,value):
    pos = binary_search(arr,value)
    if pos is -1:
        print("Element not found")
    else:
        print("Element found in the positon " +str(pos))

def test1():
    arr = [2,5,8,9,11,15,17,19,22,26,29,33,56]
    value = 56
    print_binary_search(arr,value)

def test2():
    arr = [2,5,8,9,11,15,17,19,22,26,29,33,56]
    value = 59
    print_binary_search(arr,value)

test1()
test2()


texts:
Any problems with this D wrapper around libcomcom_run_command() C function from C library libcomcom?

Does it work as expected? Is it idiomatic? Is it the right way to do this?

module libcomcom_wrapper;

import std.string;
import std.algorithm.iteration : map;
import std.array : array;
import std.exception : ErrnoException;
import libcomcom;

string runCommand(string file, string[] argv, string[] envp, string input, int timeout = -1) {
    const(char*) output;
    size_t output_len;
    const char*[] childArgv = map!(s => s.toStringz)(argv).array;
    const char*[] childEnvp = map!(s => s.toStringz)(envp).array;
    immutable int res = libcomcom_run_command(input.ptr, input.length,
                                              &output, &output_len,
                                              file.toStringz, childArgv.ptr,
                                              childEnvp.ptr,
                                              timeout);
    if (res != 0) {
        throw new ErrnoException("Run command"); // TODO: Localization
    }
    import core.stdc.stdlib : free;
    scope(exit) free(cast(void*) output);
    return output[0..output_len].idup;
}

The code was taken here.


texts:
I have written this code for fun. I'd like to hear your suggestions about how to make it more compact and pythonic.

from random import shuffle

class Pool(object):
    """
    Simple object that allows to sort
    """

    def __init__(self):
        """
        During initalization the final grid containing
        ordered balls is created
        1 is placeholder for Solid balls
        0 is placeholder for Striped balls
        """
        self.grid = [[1],[0,0],[1,0,1],[0,1,0,0],[1,0,1,0,1]]

    def create_ball_set(self):
        """
        This function returns a list containing
        a shuffled pool balls set
        """
        balls = []
        [balls.append([number]) for number in range(1, 16)]
        for ball in balls:
            if ball[0] < 9:
                ball.append("Solid")
            else:
                ball.append("Striped")
        shuffle(balls)
        return balls

    def sort_ball_set(self, unsorted_balls):
        """
        This function returns a
        list of sorted balls from a list of
        shuffled balls
        """
        # Ball 1 always goes in 1st place
        self.grid[0][0] = unsorted_balls.pop(unsorted_balls.index([1, 'Solid']))
        # Ball 8 always goes in the 2nd row, in the middle
        self.grid[2][1] = unsorted_balls.pop(unsorted_balls.index([8, 'Solid']))
        # Creating an empty list for solid balls
        unsorted_solid_balls = []
        # Same thing but for striped balls
        unsorted_striped_balls = []

        # Now it is time to divide solid balls from striped ones
        for ball in unsorted_balls:
            if ball[1] == 'Solid':
                unsorted_solid_balls.append(ball)
            elif ball[1] == 'Striped':
                unsorted_striped_balls.append(ball)

        # Once the balls are divided it is time to put them in the grid
        for grid_row_index, grid_row in enumerate(self.grid):
            for grid_col_index, grid_col_value in enumerate(grid_row):
                # In their corresponding placeholder spot
                if grid_col_value == 1:
                    # 1 is for solid balls
                    self.grid[grid_row_index][grid_col_index] = unsorted_solid_balls.pop()
                elif grid_col_value == 0:
                    # 0 is for striped balls
                    self.grid[grid_row_index][grid_col_index] = unsorted_striped_balls.pop()
        return self.grid

pool_table = Pool()
print "Getting new set of balls from the pool table:"
unsorted_balls = pool_table.create_ball_set()
print unsorted_balls
print "Sorted balls:"
sorted_balls = pool_table.sort_ball_set(unsorted_balls)
# Pretty printing sorted balls
for row in sorted_balls:
    print row


texts:
I want to create variable paging on Node.js with MongoDB. I use MongoJS on client side create a request:

api\logs?&limit=val1&page=val2&sort=val3&order=val4&field1=val5&field2=val6

where

limit, page - paging sort
order, sort - sorting (sort - field. "title","age" & etc)
field1, filed2 ... - option for filter

are all parameters optionally.

What are the disadvantages of the method of processing the request and retrieving data? The planned volume of the collection of up to 100,000 records, fields, indexes are created.

var listSort = ['time','request'];
var defSort = listSort[0];
var listOrder = ['-1','1'];
var defOrder = listOrder[0];

router.get('/', function(req, res){
   var limit = (req.query.limit === undefined) ? 25 : req.query.limit;
   var page = (req.query.page === undefined) ? 1 : req.query.page;

   var sort =  listSort.indexOf(req.query.sort) == -1 ? defSort :  req.query.sort;
   var order = listOrder.indexOf(req.query.order) == -1 ? defOrder : req.query.order;
   var querySort = {};
   querySort[sort] = parseInt(order);

   var timeBegin = isNaN(Number(req.query.timeBegin)) ? undefined : Number(req.query.timeBegin);
   var timeEnd = isNaN(Number(req.query.timeEnd))  ? undefined : Number(req.query.timeEnd);
   var request = req.query.request;
   var queryFind = {};

   if(timeBegin || timeEnd){
       queryFind['time']={};
       if(timeBegin)
           queryFind['time']['$gte']=timeBegin;
       if(timeEnd)
           queryFind['time']['$lte']=timeEnd;
   }

   if(request){
       queryFind['request']=  new RegExp(request, 'i');
   }

   Log.find(queryFind).sort(querySort)
   .limit(limit).skip(limit*(page-1), function(err, logItems) {
       if (!err) res.json(logItems);
       else res.send({error: err});
   })});

limit - the number of entries per page
page - he current page number
listSort - he list consists of a list of fields available for sorting
defSort - sort by default
listOrder - the list of sort order
defOrder - default order

Filter for 'time'. Start and end. Perhaps no one of significance. Filter 'request'. This text field, search for possible inclusion content.


texts:
This C code is to print a triangle of stars.

#include <stdio.h>
int main(){
    for(int i=0;i<3;i++) {
        for(int j=0;j<i*2+1;j++){
            printf("*");
        }
        printf("\n");
    }
}

which works well though, I'd like to know if there is a better way to do the job, as it's said 2 layers of loop is inefficient, compared to vectorization.


texts:
To find the days off for our custom accounting software there is this method used to find when is Easter in any given year.

private static DateTime Easter(int year) {
    int a = year%19;
    int b = year/100;
    int c = (b - (b/4) - ((8*b + 13)/25) + (19*a) + 15)%30;
    int d = c - (c/28)*(1 - (c/28)*(29/(c + 1))*((21 - a)/11));
    int e = d - ((year + (year/4) + d + 2 - b + (b/4))%7);
    int month = 3 + ((e + 40)/44);
    int day = e + 28 - (31*(month/4));
    return new DateTime(year, month , day);
}


texts: Validator for mathematical expressions in infix notation

texts:
The function belows validates if a mathematical expression, say 12 + 2 * (9 - 3) / 4, does not have operators that are next to each other. It returns false if an operator is next to another operator. Otherwise, it returns true. For example, if the input expression is 2++1, it will return false. The function also recursively evaluates expressions that are inside pairs of parentheses.

private boolean validateOperators(String expression)
{
    if (!validateEndCharacters(expression)) {
        return false;
    }

    Stack s = new Stack(15); // Stack is a user-defined class.
    char[] operators = { '+', '-', '*', '/' };
    char prevOperator = '\0';
    String subexpression = "";
    boolean addSubexpression = false;
    boolean isValid = false;

    for (char c : expression.toCharArray()) {
        if (addSubexpression) {
            if (c == '(') {
                s.push("(");
            } else if (c == ')') {
                s.pop();
                if (s.isEmpty()) {
                    // We found the end of the expression inside the parentheses.
                    isValid &= this.validateOperators(subexpression);
                    subexpression = "";
                    prevOperator = '\0';
                    addSubexpression = false;
                }
            }

            subexpression += Character.toString(c);
        } else {
            if (c == '(') {
                addSubexpression = true;
                s.push("(");
            } else if (this.isIn(c, operators) && prevOperator == '\0') {
                prevOperator = c;
            } else if (this.isIn(c, operators) && prevOperator == '\0') {
                isValid &= false;
                break;
            } else if (Character.isDigit(c)) {
                prevOperator = '\0';
            }
        }
    }

    if (!s.isEmpty()) {
        return false;
    }

    return isValid;
}

private boolean validateEndCharacters(String expression)
{
    char[] operators = { '+', '-', '*', '/' };
    if (this.isIn(expression.charAt(0), operators) ||
       this.isIn(expression.charAt(expression.length() - 1), operators)) {
        return false;
    }

    return true;
}

How else can I improve the functions?


texts: Mini JavaScript thread pool with maximum number of concurrently running tasks

texts:
I wrote this mini thread pool in JavaScript that takes a maximum number of concurrently running tasks and runs them in the order it was given. I appreciate any feedback or review. Thank you.
class TaskPool {
  constructor(poolSize) {
    this.poolSize = poolSize;
    this.queue = [];
    this.runningTasks = 0;
    this.scheduled = null;
    this.id = 0;
  }

  backgroundRunner() {
    if (this.queue.length) {
      if (this.runningTasks < this.poolSize) {
        const index = 0;
        const [[task, id]] = this.queue.splice(index, 1);
        this.runningTasks++;
        task(id).finally(() => {
          this.runningTasks--;
          this.backgroundRunner();
        });
      } else {
        console.log('queue is full');
        if (!this.scheduled) {
          console.log('scheduled for later');
          this.scheduled = setTimeout(() => {
            this.backgroundRunner();
            this.scheduled = false;
          }, 1000);
        }
      }
    }
  }

  run(task) {
    this.queue.push([task, ++this.id]);
    this.backgroundRunner();
  }
}

Tests:
function task(id) {
  //create an ID
  return new Promise((resolve, _) => {
    console.log('running task #', id);
    setTimeout(() => {
      console.log('done running task #', id);
      resolve();
    }, 400);
  });
}

const pool = new TaskPool(3);
for (let i = 0; i < 10; i++) {
  pool.run(task);
}

jsfiddle


texts:
This is from Leetcode

My solution is based on Python 3. It was faster than 90% of solutions on Leetcode, but used too much memory. Please what makes this memory hungry? How can I make this more efficient?

def trap(height, bound=None):
    storage = 0
    temp_storage = 0
    left_bound = None
    max_left_bound = 0

    for elevation in height:
        if bound and elevation == bound:
            storage += temp_storage
            return storage

        max_left_bound = max(elevation, max_left_bound)

        if not left_bound:
            left_bound = elevation
            continue

        block_capacity = left_bound - elevation
        if block_capacity > 0:
            temp_storage += block_capacity
            continue
        storage += temp_storage
        temp_storage, left_bound = 0, elevation

    if not temp_storage:
        return storage

    height.reverse()

    r_capacity = trap(height, max_left_bound)

    storage += r_capacity

    return storage


texts: Batch processing large text files for sentiment analysis

texts:
I have written this script in Python 2.7 and I was wondering where I could improve it or efficient. This is my first script so I don't now much. The script takes a text file from a folder removes blank spaces with list comprehension and then breaks it into smaller 20 elements and saves it each 20 elements as a definition into a dictionary with iterative numbered keys. Each key is then used to fetch the definition from the dictionary and sends each through the API one by one saving the output into another dictionary. The result dictionary is then converted to text and saved into a text file.

import glob
import os
import json
import paralleldots

api_key = "iyuDsKbgZSsCxVj6Moe37MzdqCUuvkpf33t6qS3X3cH"
paralleldots.set_api_key(api_key)

output = input(r"C:\Users\User\Desktop\trial")
txt_files = os.path.join("D:\\english\\stou\\check", '*.txt')

dic = {}                                #dictionary for storing list elements
res = {}                                #results dictionary for api output

def for_high (list_e):                  #defining a function for taking list elements and putting them into dic
    no_keys = list_e / 20
    dic = {
        1: l[1:21]
    }
    i = 1
    start_key_value = 21
    while i <= no_keys:
        i += 1
        end_key_value = start_key_value + 20
        dic.update({i: ''.join(l[start_key_value:end_key_value])})
        start_key_value += 20
    for x in dic:                       #creating a for loop for getting and saving the output and creating a new file
        output = paralleldots.emotion(dic.get(x))
        res.update({x: output})
        with open(os.path.join("C:\\Users\\User\\Desktop\\trial", filename), 'w') as text_file:
            text_file.write(json.dumps(res))

for txt_file in glob.glob(txt_files):     # for loop for going through all the text files in the input directory
    with open(txt_file, "r") as input_file:
        filename = os.path.splitext(os.path.basename(txt_file))[0] + '.txt'
        l = [l for l in input_file.readlines() if l.strip()]
        list_e = int(len(l))            #no. of list elements variable

    if list_e > 20:                     #checking if list has more than 20 elements
        if list_e % 2 != 0:             #checking if list has an odd no. of elements
            list_e += 1
            for_high(list_e)

        else:
            for_high(list_e)
    else:
        in_txt = paralleldots.emotion(l)
        filename = os.path.splitext(os.path.basename(txt_file))[0] + '.txt'
        with open(os.path.join("C:\\Users\\User\\Desktop\\trial", filename), 'w') as text_file:
            text_file.write(str(in_txt))


texts: Check if vector of strings has matching brackets

texts:
For an online screen, I had a question that would take in a vector of strings, and return a vector of strings indicating whether the input string was a valid combination of []{}(), where valid means the braces are matching and not interleaved. There are no empty string inputs.

For example, [(())] is valid, but ), {, and {[}] are invalid.

Note that input is only brackets, output is YES or NO, depending on whether or not the input is only matching brackets.

Also note using namespace std is required by the online software (hackerrank).

/*
 * Increments each value in vec by the delta.
 */
void increment(vector<int> &vec, int delta){
    transform(vec.begin(), vec.end(), vec.begin(), [delta](int x){return x+delta;});
}

/*
 * Checks if a bracket has been closed, and if it has, checks that it
 * was expected to be closed.  Returns true if there is an invalid close.
 * Note that vectors are in sorted order, since we only add indices when
 * a new bracket is opened.
 */
bool check(vector<int> &vec, bool expected){
    if(vec.empty()){ //if there are no open brackets, check if we expected one
        if (expected){
            return true;
        }
    }
    else if(vec.back() == 0){ //if the there is a bracket that was closed, check if we expected that
        vec.pop_back();
        if (!expected){
            return true;
        }
    }
    return false;
}

/*
 * Complete the function below.
 */
vector<string> braces(vector<string> values) {
    vector<pair<char, char>> bracket_types;
    bracket_types.push_back(pair<char, char>('{','}'));
    bracket_types.push_back(pair<char, char>('(',')'));
    bracket_types.push_back(pair<char, char>('[',']'));
    vector<string> results;
    for(auto const &str: values){
        /* Map of vectors containing integers indicating the number of opening brackets
         * seen since each bracket was first seen, minus the number of closing.
         * When an index is zero, that means that bracket should be closed, so we
         * check it using the check method.
         */
        map<char, vector<int> > counts;

        for(auto const &c : str){ //iterate over the string of brackets
            int incr;
            for(auto const &type : bracket_types){  //find which bracket we are using
                if (type.first == c){  //if it's an opening bracket, add a new open bracket to the vector
                    incr = 1;
                    counts[c].push_back(0);
                    break;
                }
                if (type.second == c){  //if it's a closing bracket, set incr to decrement each value
                    incr = -1;
                    break;
                }
            }
            for(auto &cnt : counts){  //for all vectors, update values, and check if we have an invalid close.
                increment(cnt.second, incr);
                if (incr < 0 && check(cnt.second, cnt.first==c)){  //if we closed a bracket, could be invalid, check
                    cnt.second.push_back(0);  //add a bracket to a vector, so that we will have the right return
                    break;
                }
            }
        }
        //Return false if there are unclosed brackets.
        results.push_back("YES");
        for(auto const &cnt : counts){
            if (!cnt.second.empty()){
                results.back() = "NO";
            }
        }
    }
    return results;
}


texts: Measuring performance of code using StopWatch

texts:
I have created a StopWatch class to measure the performance of any code. I use this StopWatch code in any of my multithreading projects as well.

public static class StopWatch {

    public static ConcurrentHashMap<Long, Long> histogram = new ConcurrentHashMap<Long, Long>();

    /**
     * Creates an instance of the timer and starts it running.
     */
    public static StopWatch getInstance() {
        return new StopWatch();
    }

    private long end = -1;
    private long interval = -1;
    private final long start;

    private StopWatch() {
        start = interval = currentTime();
    }

    /**
     * Returns in milliseconds the amount of time that has elapsed since the timer was created. If the
     * stop method has been invoked, then this returns instead the elapsed time between the creation of
     * the timer and the moment when stop was invoked.
     *
     * @return duration it took
     */
    public long getDuration() {
        long result = 0;

        final long startTime = start;
        final long endTime = isTimerRunning() ? currentTime() : end;

        result = nanoToMilliseconds(endTime - startTime);

        boolean done = false;
        while (!done) {
            Long oldValue = histogram.putIfAbsent(result, 1L);
            if (oldValue != null) {
                done = histogram.replace(result, oldValue, oldValue + 1);
            } else {
                done = true;
            }
        }

        return result;
    }

    /**
     * Returns in milliseconds the amount of time that has elapsed since the last invocation of this same method. If
     * this method has not previously been invoked, then it is the amount of time that has elapsed since the timer
     * was created. Note that once the stop method has been invoked this will just
     * return zero.
     *
     * @return interval period
     */
    public long getInterval() {
        long result = 0;

        final long startTime = interval;
        final long endTime;

        if (isTimerRunning()) {
            endTime = interval = currentTime();
        } else {
            endTime = end;
        }

        result = nanoToMilliseconds(endTime - startTime);

        return result;
    }

    /**
     * Stops the timer from advancing. This has an impact on the values returned by both the
     * getDuration and the getInterval methods.
     */
    public void stop() {
        if (isTimerRunning()) {
            end = currentTime();
        }
    }

    /**
     * What is the current time in nanoseconds?
     *
     * @return returns back the current time in nanoseconds
     */
    private long currentTime() {
        return System.nanoTime();
    }

    /**
     * This is used to check whether the timer is alive or not
     *
     * @return checks whether the timer is running or not
     */
    private boolean isTimerRunning() {
        return (end <= 0);
    }

    /**
     * This is used to convert NanoSeconds to Milliseconds
     *
     * @param nanoseconds
     * @return milliseconds value of nanoseconds
     */
    private long nanoToMilliseconds(final long nanoseconds) {
        return nanoseconds / 1000000L;
    }
}

I wanted to review this piece of code. Any suggestions or improvements I can make here?


texts: Link two databases through the java application

texts:
I have a java application that migrates data from one database to another.
I have to do update data in my database with data from another database. Another database provided by the customer.

Now it is this way:

I make a request from java application to my database(oracle) to get the address and driver of database, user, password from which I want to get the data.

oracleConn = DriverManager.getConnection(...); //connect to my DB

PreparedStatement prStServerP = this.oracleConn.prepareStatement("SELECT adress, driver, user, password from connections where svr_id = ?"); //settings to connect to the remote DB

Then I establish a connection with the remote database.

Connection dbConn = this.getDbConnection(svrId);

From my database I get "selects" for the remote Database.

oraclePrSt = this.oracleConn.prepareStatement("SELECT slq_select FROM SELECTS where svr_id...")

Also from my database I choose the table which will put the data from the remote database.

I Doing "selects" in a remote database and put the data:

Statement dbPrSt = dbConn.createStatement();
ResultSet dbRs = dbPrSt.executeQuery(oracleRs.getString(3)); //here selects that I got from my database
ResultSetMetaData dbRsMd = dbRs.getMetaData();

After all of this I record the results from a remote database into a file and using sqlLoader writes data in my database.

Please, tell me is there any options to make it easier or better?


texts:
In essence, what I'm looking to do is split a string into one-word and two-word segments, and train classifiers against them. First it lowercasifies the string, then strips all non-alphanumeric characters.

Then, it splits the strings into a list of one-word entries. Afterward, it creates a new *[]string which it fills with all sequential two-word entries.

In particular, I'm concerned about the way I'm creating the two-word *[]string slice, and the way I'm using pointers. The first is an efficiency issue, and the second is a, well, I suppose memory-efficiency issue.

const (
    Spam     bayesian.Class = "Spam"
    Spamlike bayesian.Class = "Spamlike"
    NotSpam  bayesian.Class = "NotSpam"
)

type SpamFilter struct {
    singleWordClassifier *bayesian.Classifier
    doubleWordClassifier *bayesian.Classifier
}

func CreateNewSpamFilter() *SpamFilter {
    v1 := bayesian.NewClassifier(Spam, Spamlike, NotSpam)
    v2 := bayesian.NewClassifier(Spam, Spamlike, NotSpam)
    tmp := SpamFilter{v1, v2}
    return &tmp
}

func LoadSpamFilterFromFile(fileName1 string, fileName2 string) *SpamFilter {
    tmp1, err1 := bayesian.NewClassifierFromFile(fileName1)
    tmp2, err2 := bayesian.NewClassifierFromFile(fileName2)
    switch {
    case err1 != nil:
        panic(err1)
    case err2 != nil:
        panic(err2)
    }
    return &SpamFilter{tmp1, tmp2}
}

func splitStringToSingleWords(input string) *[]string {
    reg, err := regexp.Compile("[^A-Za-z0-9 ]+")
    if err != nil {
        panic(err)
    }

    tmp := reg.ReplaceAllString(input, "")
    split := strings.Fields(tmp)
    return &split
}

func SplitStringToWords(input string) (*[]string, *[]string) {
    splitSingle := splitStringToSingleWords(strings.ToLower(input))
    var splitDouble = make([]string, len(*splitSingle)-1)

    for i := 0; i < len(*splitSingle)-1; i++ {
        splitDouble[i] = (*splitSingle)[i] + " " + (*splitSingle)[i+1]
    }

    return splitSingle, &splitDouble
}

func (filter *SpamFilter) TrainStringsInSpamFilter(trainType bayesian.Class, singleWords *[]string, doubleWords *[]string) *SpamFilter {
    (*filter).singleWordClassifier.Learn(*singleWords, trainType)
    (*filter).doubleWordClassifier.Learn(*doubleWords, trainType)
    return filter
}

func (filter *SpamFilter) TestStringThroughSpamFilter(testString string) (*[]float64, *[]float64) {
    splitSingle, splitDouble := SplitStringToWords(testString)
    p1, _, _ := (*filter).singleWordClassifier.ProbScores(*splitSingle)
    p2, _, _ := (*filter).doubleWordClassifier.ProbScores(*splitDouble)
    return &p1, &p2
}

How does this look, generally-speaking? What should I have done differently?

Also, copied here:

How is my use of pointers (is it, well, correct)?
Am I segmenting the strings in the most efficient possible way? I intend to use this on a rather large dataset.
Will this be threadsafe/goroutine-friendly for large datasets?


texts: Reduce array of objects into object of arrays

texts:
I have an array of objects where each object has two keys: key (k) and value (v). I need to make an object that would take values of k and collect corresponding values of v as a value of this key, an array of them.

So, for example, from an array

[{
  k: 'a',
  v: 0
}, {
  k: 'a',
  v: 1
}, {
  k: 'b',
  v: 2
}]

I need an object

{
  a: [0, 1],
  b: [2]
}

It's easy to use outer-scope variables but what I want to do is to perform it in functional manner.

Right now, I have this piece of (ES6) code:

rows.reduce((result, item) => ({
  ...result,
  [item.k]: [
    ...(result[item.k] || []),
    item.v
  ]}),
{});

It works nice but the question is if it is possible to optimize it in terms of SLOC. For one, I don't like the ...(result[item.k] || []) piece but if I leave it as simple as ...result[item.k] then I get an error because, when it's undefined, babel fails to perform a method call of it, since undefined doesn't have any methods.

Did I maybe take a wrong path and there's a more elegant solution that reducing the array?

I would appreciate any suggestions, please throw any ideas at me.


texts:
Learn You a Haskell shows the intersperse function:

ghci> intersperse '.' "MONKEY"
"M.O.N.K.E.Y"
ghci> intersperse 0 [1,2,3,4,5,6]
[1,0,2,0,3,0,4,0,5,0,6]

Note that the interspersed element only appears inside of the elements.

  list elem ... item ... list elem ..... item .. list elem

Originally, I tried to write this function in terms of a fold.

intersperse' :: [a] -> a -> [a]
intersperse' ys i = foldl (\acc x -> acc ++ [x] ++ [i]) [] ys

But, my approach failed since interspersed item was getting appended to the last element. Also, the lambda appended (++) to the acc each time, which isn't good.

So I decided to use pattern matching:

is' :: [a] -> a -> [a]
is' [] _ = []
is' (x:xs) i
  | null xs = [x]
  | otherwise = x : (i : (is' xs i))

Could the fold approach have worked? If so, how? Also, how's my is' implementation?


texts: Code improvement suggestions for cost calculation

texts:
I have to calculate costs based on country code and city(optional). There is also a condition that countries in Asia have separate pricing logic depending on both country and city and they are stored in a different table (for segregating regional price variances). For the rest, it's only dependent on country code. Let's assume we must have separate tables Asia & the rest.

Please suggest some improvements in the below code.

def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]:
    cost = None

    # check if the country is in Asia
    if models.OperatorCostAsia.objects.filter(country=country_code).exists():
        cost = models.OperatorCostAsia.objects.filter(country=country_code, city__icontains=city).first()

        if cost is None:
            cost = models.OperatorCostAsia.objects.filter(country=country_code).first()
    else:
        cost = models.OperatorCost.objects.filter(country=country_code).first()

    return cost

I have two different tables to calculate the prices. The pricing table for Asia has three columns: Country code, city name and the price itself. The pricing table for rest of the countries just has country code and price columns.
I get a mandatory country code and an optional city name as parameters from the frontend. First I check these params against the Asia pricing table. if the selected country happens to be Asian, I query against country code and city name (if there is one). If the city param is empty, i just pick the first match against the country.

If the country is not an Asian country, I simply query the second (Rest of the world) table to find the pricing against the country code.


texts: Have I prepared this prepared statement well?

texts:
This is a prepared statement (I think).  Have I done this well?

function wyswietl($rekord, $tabela) {
    $lacz = lacz_bd();

    if (!$zap_preparowane = $lacz->prepare("SELECT {$rekord} FROM {$tabela} where email = ?"))                 {echo "Prepare nieudane: (" . $zap_preparowane->errno . ") " . $zap_preparowane->error;}
    if (!$zap_preparowane->bind_param("s",$_SESSION['prawid_uzyt']))                                           {echo "BindPar nieudane: (" . $zap_preparowane->errno . ") " . $zap_preparowane->error;}
    if (!$zap_preparowane->execute())                                                                          {echo "Execute nieudane: (" . $zap_preparowane->errno . ") " . $zap_preparowane->error;}
    if (!$zap_preparowane->store_result())                                                                     {echo "StoreRe nieudane: (" . $zap_preparowane->errno . ") " . $zap_preparowane->error;}
    if (!$zap_preparowane->bind_result($binded_result))                                                        {echo "BindRes nieudane: (" . $zap_preparowane->errno . ") " . $zap_preparowane->error;}
        while ($zap_preparowane->fetch()) {
             echo $binded_result;     //htmlspecialchars? printf("%s ?
        }
    $zap_preparowane->free_result();
    $zap_preparowane->close();

    $lacz->close();
}


texts: Average across direction-specific average speeds and probabilities

texts:
I have a wind rose with 72 evenly-spaced directions, spanning 360°, each describing a direction-specific average wind speed and associated probability. We must condense this information to 36 evenly-spaced direction bins. "probability" is the normalized frequency of occurrences. The probabilities should sum to one. If 5° has a 0.1 probability. that means that the wind came from that direction 10% of the time.

I average across the midpoints of each bin, which results in undesirably shifting the wind rose so that the center is at 2.5 degrees. Is there a more elegant way to do this in theory or implementation?

import pandas as pd
import numpy as np
import wget

# Load data!
url = 'https://raw.githubusercontent.com/scls19fr/windrose/master/samples/amalia_directionally_averaged_speeds.txt'
wget.download(url, 'amalia_directionally_averaged_speeds.txt')
dat = pd.read_csv('./amalia_directionally_averaged_speeds.txt',
                  sep=r'\s+', header=None, skiprows=[0])
dat.columns = ['direction', 'average_speed', 'probability']

# two steps
#   1. average frequency across speeds
#   2. compute average speed weighted by frequencies
#     (the scheme is to average across both midpoints. this
#      shift the centers by 2.5 degrees and bin by 10)
directions, speeds, frequencies = [], [], []
for i in range(dat.shape[0] / 2):
    directions.append(dat.direction[i * 2] + 2.5)
    frequencies.append(np.mean(dat.probability[[i * 2, i * 2 + 1]].values))
    speeds.append((dat.direction[i * 2] * dat.average_speed[i*2] +
                  dat.direction[i*2 + 1] * dat.average_speed[i * 2 + 1]) /
                  (dat.direction[i * 2] + dat.direction[i * 2+1]))

# save data
done = pd.DataFrame({'direction': directions,
                    'speed': speeds, 'probability': frequencies})
done.to_csv('wind_rose.csv')


texts: Pythonic way to do strategy design pattern,avoid use switch base on string compare

texts:
Here are two functions, which are quite similar. The type of dtIndex is pandas DatetimeIndex and the only difference is the i.dayofyear part. There are days of week, month of year, week of month, week of year I still need to implement.

def extract_day_of_year(dtIndex):
    dayofyear_arr = []
    for i in dtIndex:
        dayofyear_arr.append(i.dayofyear)
    return dayofyear_arr

def extract_day_of_month(dtIndex):
    dayofmonth_arr = []
    for i in dtIndex:
        dayofmonth_arr.append(i.dayofmonth)
    return dayofmonth_arr

Is there a "Pythonic" way than switch according to an additional str parameter?


texts: Design of class hierarchy for a object formatter API forces derivatives to know too much

texts:
While learning object oriented design I'm judging my own design critically. This framework should be able to print objects in either XML, or JSON, I've stubbed in a basic implementation to avoid getting into details of XML and JSON parser APIs for now.

So I made the Formatter be the base class. But with my current design, all derivatives of this base class would need to know that they have to call: getFormattedValue() to get output. Also I don't feel comfortable with all of those if else statements in the Formatter constructor. The clients would need to know to pass in either an "XML" or "JSON" in all derivatives of this class. How can I improve this design to conform to all object oriented design principles?

public class Formatter {

    private String output;

    public Formatter(Object object, String formatType){
        if(formatType.equals("xml")){
            output = getXMLFormat(object);
        } else if(formatType.equals("json")) {
            output = getJSONFormat(object);
        }
    }

    private String getXMLFormat(Object object){

        return "<title>"+object.toString()+"<title>"; // simplified
    }

    private String getJSONFormat(Object object){
        return "{"+object.toString()+"}"; // simplified
    }

   protected  String getFormattedValue(){
        return output;
    }
}

The derivative class:

public class ItemFormatter extends Formatter {

    public ItemFormatter(Employee item, String formatOutput) {
        super(item, formatOutput);
    }

    public void printItem(){
        System.out.println(getFormattedValue());
    }
}


texts:
Is this code good enough, or is it stinky?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DotNetLegends
{
    public class LogParser
    {
        /// <summary>
        /// Returns a populated Game objects that has a list of players and other information.
        /// </summary>
        /// <param name="pathToLog">Path to the .log file.</param>
        /// <returns>A Game object.</returns>
        public Game Parse(string pathToLog)
        {
            Game game = new Game();

            //On actual deployment of this code, I will use the pathToLog parameter.
            StreamReader reader = new StreamReader(@"D:\Games\Riot Games\League of Legends\air\logs\LolClient.20110121.213758.log");
            var content = reader.ReadToEnd();

            game.Id = GetGameID(content);
            game.Length = GetGameLength(content);
            game.Map = GetGameMap(content);
            game.MaximumPlayers = GetGameMaximumPlayers(content);
            game.Date = GetGameDate(content);

            return game;
        }

        internal string GetGameID(string content)
        {
            var location = content.IndexOf("gameId");
            var gameID = content.Substring(location + 8, 10);
            gameID = gameID.Trim();
            return gameID;
        }

        internal string GetGameLength(string content)
        {
            var location = content.IndexOf("gameLength");
            var gamelength = content.Substring(location + 13, 6);
            gamelength = gamelength.Trim();
            var time = Convert.ToInt32(gamelength) / 60;
            return time.ToString();
        }

        internal string GetGameMap(string content)
        {
            var location = content.IndexOf("mapId");
            var gameMap = content.Substring(location + 8, 1);
            switch (gameMap)
            {
                case "2":
                    return "Summoner's Rift";
                default:
                    return "nul";
            }
        }

        internal string GetGameMaximumPlayers(string content)
        {
            var location = content.IndexOf("maxNumPlayers");
            var maxPlayers = content.Substring(location + 16, 2);
            maxPlayers = maxPlayers.Trim();
            return maxPlayers;
        }

        internal string GetGameDate(string content)
        {
            var location = content.IndexOf("creationTime");
            var creationDate = content.Substring(location + 14, 34);
            creationDate = creationDate.Trim();
            return creationDate;
        }
    }
}


texts:
Using GetEnumerator extensions added in C# 9 I was able to do the following:
    public static class Extensions
    {
        public static IEnumerator<int> GetEnumerator(this Range range)
        {
            var start = range.Start.Value;
            var end = range.End.Value;

            var current = start;
            while (current <= end)
            {
                yield return current++;
            }
        }
    }

Which enables me to do this neat thing:
foreach (var i in 1..5)
{
     Console.WriteLine(i);
}

What I want to know is what are potential problems or side effects. Apart from a little performance loss, what downsides can you see if I would write like this in the future instead of using a for loop?


texts: Lazy man's IEnumerable extension verification method

texts:
I often find myself doing this (or similar) with Lists and other collection types:

if (someList != null && someList.Count > 0)
    //take some action on the list

so I got lazy and wrote the following extension methods to do it for me:

    public static bool IsNullOrEmpty(this IEnumerable self)
    {
        //Convert to collection here because IEnumerable doesn't have a count property
        ICollection c = self as ICollection;
        return c == null || c.Count < 1;
    }

    public static bool IsNotNullOrEmpty(this IEnumerable self)
    {
        return !self.IsNullOrEmpty();
    }

    public static bool IsNotNullAndContains<T>(this IEnumerable<T> self, T item)
    {
        return self.IsNotNullOrEmpty() && self.Contains(item);
    }

Other than being lazy is there anything wrong with this or should I have just stuck with the manual check every time?

Edit:

Based on the answer from Jeroen Vannevel:

I originally had the first extension method (IsNullOrEmpty) defined as such:

public static bool IsNullOrEmpty<T>(this IEnumerable<T> self)
{
    return self == null || self.Count < 1;
}

which eliminated the need for the cast to ICollection, as IEnumerable<T> implements the count property. I removed the type parameter though because I wasn't actually using it for anything. Should I have just kept it like that to prevent the cast and a potential type cast exception?


texts: Find the first non-recurring character in string

texts:
I wrote a solution to first-unique-character-in-a-string:

  Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

If there is better way for me to build the dictionary seems? and find the first key when value is 1 and index is lowest?

def firstUniqChar(string) -> int:
    seems = dict()
    index = len(string)
    c = ''
    for i, char in string:
        if char not in seems:
            seems.setdefault(char, (i,1))
        else:
            seems[char] = (seems[char][0], seems[char][1] + 1)

    for k, value in seems.items():
        if value[1] == 1 and value[0] < index:
            index = value[0]
            c = k
    return  index if c else -1


texts:
I have the following method that has been shortened for the sake of this review. The actual method has many more tasks. Essentially what I am trying to do is to create many tasks, fire them off, wait until they are all finished, and handle any exceptions generated. Does this look correct?

public static void RefreshCoaterCaches()
{
    try
    {
        CicApplication.CoaterDataLock.EnterWriteLock();

        List<Task> alarmTasks = new List<Task>();

        alarmTasks.Add(Task.Factory.StartNew(() =>
        {
            using (DistributorBackpressure44Logic logic = new DistributorBackpressure44Logic())
                logic.RefreshDistributorBackpressure44Cache();
        }));

        alarmTasks.Add(Task.Factory.StartNew(() =>
        {
            using (DeltaPressureLogic logic = new DeltaPressureLogic())
                logic.RefreshDeltaPressureCache();
        }));

        Task.WaitAll(alarmTasks.ToArray());
    }
    catch (System.AggregateException exception)
    {
        CicServerLogic.HandleUnexpectedAggregateException(exception.Flatten(), string.Empty);
    }
    catch (System.Exception exception)
    {
        CicServerLogic.HandleUnexpectedException(exception);
    }
    finally
    {
        CicApplication.CoaterDataLock.ExitWriteLock();
    }
}

I then have this method to handle any AggregateException thrown:

internal static void HandleUnexpectedAggregateException(AggregateException aggregateException)
{
    try
    {
        foreach (Exception exception in aggregateException.InnerExceptions)
        {
         ...
         ...
         Do some stuff with the current exception, like logging etc.
         ...
        }
    }
    catch (Exception)
    {
    }
}


texts: Optimize this jQuery tab controller further

texts:
How do I optimize this code further?  Goal is to edit "js-tab" in one place.  This is what I tried to follow.

Full code here.

var ToggleTab = {

init: function() {
    this.tab = $(".js-tab");
    this.bindEvents();
},

bindEvents: function() {
    this.tab.on("click", this.toggleTab);
    //this.tab.on("click", $.proxy(this.toggleTab, this));
},

toggleTab: function(e) {
    var showTab = $(this).data("tab-content");
    e.preventDefault();

    $(".js-tab").each(function() {
        if ($(this).data("tab-content") === showTab) {
           $(".js-tab-" + showTab).removeClass("hide");
        } else {
            $(".js-tab-" + $(this).data("tab-content")).addClass("hide");
        }
    });
}

};

$(function() {

    ToggleTab.init();

});


texts: Putting called delegate into AsyncState parameter - Pros/cons?

texts:
I have the following interface:

public interface ILogger
{
    void Log(string message, string title, StatusType type, DateTime timestamp);
    IAsyncResult LogAsync(string message, string title, StatusType type, DateTime timestamp, AsyncCallback callback);
    void EndLogAsync(IAsyncResult result);
}

Implemented as a file-based logger...

...

    public FileInfo LogFileInfo { get; internal set; }

    public void Log(string message, string title, StatusType type, DateTime timestamp)
    {
        lock (syncObj)
        {
            CheckLogFileSize(); //rotates LogFileInfo through numbered log files

            using (var stream = LogFileInfo.AppendText())
            {
                stream.WriteLine(GetFormattedString(message, title, type, timestamp));
                stream.Flush();
            }
        }
    }

    public IAsyncResult LogAsync(string message, string title, StatusType type, DateTime timestamp, AsyncCallback callback)
    {
        var action = new Action<string, string, StatusType, DateTime>(Log);
        return action.BeginInvoke(message, title, type, timestamp, callback, action);
    }

    public void EndLogAsync(IAsyncResult result)
    {
        ((Action)result.AsyncState).EndInvoke(result);
    }

Notice the AsyncState parameter of BeginInvoke; I pass the delegate to its own invocation, so that I can reference it again on the flip side to end the invocation using the same delegate reference I called BeginInvoke on.

The questions:

Is it even necessary to keep the actual invoked delegate reference around, or can I simply new up another reference to that method in the EndLogAsync method?
Is this an acceptable use of the AsyncState, given that I have no other use for it?


texts: Euler problem 3: largest prime factor of the number

texts:
I have been trying to learn Python and just solved Euler Problem 3:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

I am looking for any feedback on improving efficiency and the code itself.

My code:

from itertools import count, islice

def is_prime(number):
    for n in islice(count(2), int(number**0.5 -1)):
        if number % n == 0:
            return False
    return True

def find_factors(number):
    lst = []
    for n in islice(count(2), int(number/2-1)):
        if number % n == 0:
            if is_prime(n):
                lst.append(n)
    return lst

print(find_factors(13195).pop())

I used islice instead of xrange because of int limits, which I learned about from another question at StackOverflow.com

In code above, I have created two separate functions, one to find a prime and the other to find factors.

The program works this way,

It takes an input number
Find all the factors of that number from 2->number/2
If it finds a factor, it checks if its a prime, and append it to a list.
Eventually I print the last element of list since list in python are ordered.


texts:
Project Euler problem 27

I decided to try simple brute force, and it worked surprisingly quickly.  How can this be optimized?

"""Considering quadratics of the form:
n^2 + an + b, where |a| < 1000 and |b| < 1000
Find the product of the coefficients, a and b,
for the quadratic expression that produces
the maximum number of primes for
consecutive values of n,
starting with n = 0."""

from timeit import default_timer as timer
import math
start = timer()

def longestPrimeQuadratic(alim, blim):

    def isPrime(k): # checks if a number is prime
        if k < 2: return False
        elif k == 2: return True
        elif k % 2 == 0: return False
        else:
            for x in range(3, int(math.sqrt(k)+1), 2):
                if k % x == 0: return False

        return True

    longest = [0, 0, 0] # length, a, b
    for a in range((alim * -1) + 1, alim):
        for b in range(2, blim):
            if isPrime(b):
                count = 0
                n = 0
                while isPrime((n**2) + (a*n) + b):
                    count += 1
                    n += 1

                if count > longest[0]:
                    longest = [count, a, b]

    return longest

ans = longestPrimeQuadratic(1000, 1000)

elapsed_time = (timer() - start) * 100 # s --> ms

print "Found %d and %d in %r ms." % (ans[1], ans[2], elapsed_time)


texts:
I am beginning the cycle of creating my role based access control into my framework. I now want to log the user into my application and my _user table looks like this:
CREATE TABLE `_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `hash` varchar(255) NOT NULL,
  `session` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

I create my user like so in my model, where bin2hex() is my IV / salt.
Database::getInstance()->Prepare( 'INSERT INTO _users (username, hash, session) VALUES (?, ?, ?)' )
                       ->execute( array(
                           'Test',
                           password_hash( 'Test', PASSWORD_BCRYPT ),
                           md5( time() . bin2hex( random_bytes( 32 ) ) )
                       ) );

To then log into the user, I use a method. The method I use in the request is POST because my application has built in CRSF tokens. If the CRSF token is passed, then a xauth_protected aliased class is instanced which ensures that X-Auth header exists and is of md5(session_id()) to ensure that no cross-site-origin requests can be made.
public function login( Request $request )
{
    $this->middleware( 'json_response', $request );
    $this->middleware( 'xauth_protected', $request );

    if( !$request->has( 'username' ) || !$request->has( 'password') )
    {
        echo json_encode( array(
            'status' => FALSE,
            'reason' => 'Please fill in the required fields...',
        ) );
        return;
    }

    $stmt = Database::getInstance()->Prepare( 'SELECT id, hash, session FROM _users WHERE username = ? LIMIT 1' );
    $stmt->execute( array( $request->username ) );
    $row  = (object) $stmt->fetch();

    if( isset( $row->id ) )
    {
        if( password_verify( $request->password, $row->hash ) )
        {
            // $_SESSION['oath'] = $row->session
            // This is used to find the user that is logged in, if it is set
            $request->setSession( 'oauth', $row->session );

            echo json_encode( array(
                'status' => TRUE,
            ) );

            return;
        }

        echo json_encode( array(
            'status' => FALSE,
            'reason' => 'Invalid credentials...',
        ) );

        return;
    }

    echo json_encode( array(
            'status' => FALSE,
            'reason' => 'Sorry, that username was not found in our records...',
        ) );
}

To then test this method, I can use:
const formData = new FormData();

formData.append( 'crsf_token', sessionStorage.getItem( 'token' ) ); // CRSF token is set elsewhere
formData.append( 'username', document.getElementById( 'username' ).value ); // Example input field
formData.append( 'password', document.getElementById( 'password' ).value ); // Example input field

fetch( App.__viewFactory.homepage.login, { // This is a prestored route that looks like /oauth/login
    method: 'POST',
    headers: {
        'X-Auth': sessionStorage.getItem( 'session' ) // md5( session_id() ) which is set elsewhere
    },
    body: formData
} )
.then( response => response.json() )
.then( data     => {
    if( data.result ) {
        window.location.href = App.__viewFactory.dashboard.view; // prestored route to the dashboard
        return;
    }

    document.getElementById( 'login-error' ).innerHTML = data.reason;
} )
.catch(error => {
    document.getElementById( 'login-error' ).innerHTML = 'Oh no! Something went wrong.';
});

I have incorporated CRSF protected, custom headers using the session_id() to prevent cross-origin requests (since my framework rewrites all requests to my index page, this then turns on CORS). Is everything I am doing on the database side as secure? Is there something I could be doing better?


texts: Number of prime numbers in a given range

texts:
I've written a method that should return the numbers of prime numbers in a given range:

public static int numberOfPrim(int up){                 // Returns amount of primnumbers from 0 to up
    if(up<=0){
        return 0;
    }
    int primAmount = 0;
    for(int i = 1; i<=up ; i++){
        if(checkIfPrim(i) == true){
           primAmount++;
        }
    }
    return primAmount;
}

public static boolean checkIfPrim(int number){         // If number is prim -> return true
    if (number < 2){
        return false;
    }
    boolean prim = true;
    if(number == 2){
        return prim;
    }
    boolean[] con = new boolean[number];
    for(int i = 2; i < number; i++){
        if(number %i == 0) {
            con[i] = true;
        }
    }
    for(int j = 0; j < number; j++){
        if(con[j] == true){
            prim = false;
        }
    }
    return prim;
}

The code is working like I want it to. For example, numberOfPrim(10) should return 4 (2, 3, 5, 7). I'm just asking if there are any locations where I can improve my code, like shorten it or if there are any other possibilities to write such a method.


texts:
I just finished writing a basic binary conversion class in Ruby. I'm curious to see if anyone has suggestions for improvements. In particular, I'm looking for the cleanest, shortest, most succinct code possible, while staying away from hacky shortcut stuff.

In creating this I wanted to use a minimum of functions that come with Ruby by default, as that would sort of defeat the purpose of this as a practice program. For instance, the entire thing could have been summed up with a quick line like this.

"101".to_i(2) ##> 5

But I wanted to do most of the math by hand, so to speak.

There is one place in the get_bits method I did use a string, and I'm not too happy about it. However it was the only way I could think of to get the bits into an array. If there's another way to do so without splitting a string, I'd be glad to hear it.

Here's the class.

class Converter
  def initialize binary_number
    @binary = binary_number
    @bits = get_bits
    @total = 0
    self
  end

  def to_base_ten
    validate_binary
    @bits.reverse.each_with_index do |bit, power|
      append_to_total bit_value(bit, power)
    end
    get_total
  end

  private
  def get_bits
    @binary.to_s.split('').map do |bit|
      bit.to_i
    end
  end

  def validate_binary
    @bits.each do |bit|
      raise "Invalid binary!" unless bit == 0 || bit == 1
    end
  end

  def bit_value bit, power
    is_set?(bit) ? two_to_power_of(power) : 0
  end

  def two_to_power_of power
    total = 1
    power.times do
      total = total * 2
    end
    total
  end

  def is_set? bit
    bit == 1
  end

  def append_to_total amount
    @total = @total + amount
  end

  def get_total
    @total
  end
end

I also used RSpec to test it as best I could, but I won't post the specs here, just because they're long and not directly related to the class itself. If you want to inspect those too, they can be found on GitHub.

So there ya have it. Any thoughts are greatly appreciated. Clean code forever!


texts: Scanning a directory for plugins and loading them

texts:
I'm working on a simple dictionary tool, with a base class that can be extended by plugins to represent different dictionaries. The plugins are organized in the filesystem like this:

plugins/
├── dict1
│   ├── ...
│   └── dict1.py
└── dict2
    ├── ...
    └── dict2.py

Each plugin defines a class named Dictionary, which happens to extend a BaseDictionary, in case that's relevant.

I implemented discovering and loading the plugins like this:

import os
from imp import find_module, load_module

BASE_DIR = os.path.dirname(__file__)
PLUGINS_PATH = os.path.join(BASE_DIR, 'plugins')

def discover_dictionaries():
    import plugins
    for plugin_name in os.listdir(PLUGINS_PATH):
        plugin_path = os.path.join(PLUGINS_PATH, plugin_name, plugin_name + '.py')
        if os.path.isfile(plugin_path):
            try:
                fp, pathname, description = find_module(plugin_name, plugins.__path__)
                m1 = load_module(plugin_name, fp, pathname, description)
                fp, pathname, description = find_module(plugin_name, m1.__path__)
                m2 = load_module(plugin_name, fp, pathname, description)
                class_ = getattr(m2, 'Dictionary')
                yield plugin_name, class_()
            except ImportError:
                print('Error: could not import Dictionary from {0}'.format(plugin_path))

This works, but it's kind of ugly, and probably I'm doing it all wrong. How to do this the "right way," or at least better?

If you want to play with the code to see if your refactoring ideas work, clone the project from GitHub, and run this as a sanity check:

# should output: dummy
python -c 'import util; print util.discover_dictionaries().next()[0]'


texts: Python static / instance method or function?

texts:
background:
I have a model called FileInfo, which represents a sftp file / windows dfs file.

class FileInfo(object):
    def __init__(self, server_info, folder_path, file_name):
        self.server_info = server_info
        self.folder_path = folder_path
        self.file_name = file_name

    def get_file_full_path(self):
        return os.path.join(self.folder_path, self.file_name)

FileInfo has a ServerInfo to hold the server connection info: e.g. sftp connection details.

class ServerInfo(object):
    pass

class WindowsServerInfo(ServerInfo):
    pass

class SFTPServerInfo(ServerInfo):
    pass

this is how I print out the full path:

if __name__ == '__main__':
    sftp_server_info = SFTPServerInfo()
    win_server_info = WindowsServerInfo()

    print FileInfo(win_server_info, r'\\dfs\domain\tmp', 'test.txt').get_file_full_path()
    print FileInfo(sftp_server_info, r'/tmp', 'test.txt').get_file_full_path()

the application is running in Windows and Linux, so the output of the above code will be different -- depends on the hosting OS result on Linux:

\\dfs\domain\tmp/test.txt
/tmp/test.txt

result on Windows:

\\\\dfs\\domain\\tmp\\test.txt
/tmp\\test.txt

I want to have a consistent output, such as:

\\dfs\domain\tmp\test.txt
/tmp/test.txt

so I start to refactor the code:

v1. if...else...

class FileInfo(object):
    def get_file_full_path(self):
        if isinstance(self.server_info, SFTPServerInfo):
             return r'%s/%s' % (self.folder_path, self.file_name)
        elif isinstance(self.server_info, WindowsServerInfo):
            return r'%s\%s' % (self.folder_path, self.file_name)
        else
            raise exception

it works, but if...else means it'll be a big method if I want to support more server types. so I'm going to create a dict to handle it.

v2. a dict contains ServerInfo type and function mapping

class FileInfo(object):
    def get_file_full_path(self):
       return get_full_path_functions[type(self.server_info)](self.folder_path, self.file_name)

def get_full_path_windows(folder_path, file_name):
    return r'%s\%s' % (folder_path, file_name)

def get_full_path_sftp(folder_path, file_name):
    return r'%s/%s' % (folder_path, file_name)

get_full_path_functions = {
    WindowsServerInfo: get_full_path_windows,
    SFTPServerInfo: get_full_path_sftp
}

it works fine, but I think it may be a good idea to move these methods into ServerInfo

v3. instance method

class FileInfo(object):
    def get_file_full_path(self):
        return self.server_info.get_full_path(self.folder_path, self.file_name)

class WindowsServerInfo(ServerInfo):
    def get_full_path(self, folder_path, file_name):
        return r'%s\%s' % (folder_path, file_name)

class SFTPServerInfo(ServerInfo):
    def get_full_path(self, folder_path, file_name):
        return r'%s/%s' % (folder_path, file_name)

however, get_full_path methods are not using self, and this method should not belongs to any instance of ServerInfo

v4. static method

class FileInfo(object):
    def get_file_full_path(self):
        return type(self.server_info).get_full_path(self.folder_path, self.file_name)

class WindowsServerInfo(ServerInfo):
    @staticmethod
    def get_full_path(folder_path, file_name):
        return r'%s\%s' % (folder_path, file_name)

class SFTPServerInfo(ServerInfo):
    @staticmethod
    def get_full_path(folder_path, file_name):
        return r'%s/%s' % (folder_path, file_name)

All these 4 versions are working as expected, please help to review them and let me know:

from the OOP perspective, which one is the best? is there a better way to desing it?
from Python perspective, which one is the most
pythonic way?


texts:
I am a Java developer, and I recently gave Kotlin a try.
To begin, I did a little exercise I often do when I start a new language, to verify I got the very basics: the more or less game.
The code I submit there is working fine, but of course I suspect it may be too much like Java, and I would like you to point to me how I can make my code more Kotlin.

package fr.caro

import java.util.*

fun main(args: Array<String>) {
    val min = 0
    val max = 100
    var nbAttempts = 0
    val random = SplittableRandom()
    val reader = Scanner(System.`in`)
    val goal = random.nextInt(min, max)
    var userGuess: Int

    computerSays("I chose a number between $min and $max")
    do {
        nbAttempts++
        computerSays("What's your guess?")
        userGuess = reader.nextInt()
        if (userGuess > goal) computerSays("less !")
        else if (userGuess < goal) computerSays("more !")
    } while(userGuess != goal)

    computerSays("Congratulation ! You found in $nbAttempts attemps.")
}

fun computerSays(text: String) {
    println("Computer : " + text)
}

PS: I wonder if putting the min and max values in a Pair object would be a good idea?


texts: Java 8 use streams for a "group by" feature

texts:
I am writing a Java function that checks if the items of a list are unique (depending of an id member).

I have a Java 7 implementation that works, but it is not using streams, filter and joins. I think the code can be improved.

Case 1: empty list => OK

Case 2: all ids are different => OK

+---------+-------+
| baf18c4 | Item1 |
| c5e4623 | Item2 |
| bf1932f | Item3 |
+---------+-------+

No message expected.

Case 3: one id is duplicate (3 times each) => message expected

+---------+-------+
| baf18c4 | Item1 |
| c5e4623 | Item2 |
| baf18c4 | Item3 |
| baf18c4 | Item4 |
+---------+-------+

Expected message:

  Some of the items are sharing the same code: 'baf18c4' used by {Item1, Item3, Item4}

Case 4: two ids is duplicate (2 times each) => message expected

+---------+-------+
| baf18c4 | Item1 |
| c5e4623 | Item2 |
| baf18c4 | Item3 |
| bf1932f | Item4 |
| c5e4623 | Item5 |
+---------+-------+

  Some of the items are sharing the same code: 'baf18c4' used by {Item1, Item3}, 'c5e4623' used by {Item2, Item5}

Code

package tmp;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.junit.Test;

public class Snippet {
  private static String verifyItems(List<Item> items) {
    Map<String, List<Item>> map = new HashMap<>();
    for (Item item : items) {
      String key = item.getCode();
      List<Item> list;
      if (map.containsKey(key)) {
        list = map.get(key);
      }
      else {
        list = new ArrayList<>();
        map.put(key, list);
      }
      list.add(item);
    }
    boolean isFirst = true;
    StringBuilder sb = new StringBuilder();
    for (Entry<String, List<Item>> e : map.entrySet()) {
      if (e.getValue().size() > 1) {
        if (isFirst) {
          sb.append("Some of the items are sharing the same code: ");
        }
        else {
          sb.append(", ");
        }
        isFirst = false;
        sb.append("'" + e.getKey() + "' used by ");
        sb.append(e.getValue().stream().map(i -> i.getDescription())
            .collect(Collectors.joining(", ", "{", "}")));
      }
    }
    return sb.toString();
  }

  @Test
  public void testEmpty() throws Exception {
    assertEquals("", verifyItems(Collections.emptyList()));
  }

  @Test
  public void testOk() throws Exception {
    List<Item> items = Arrays.asList(
        new Item("baf18c4", "Item1"),
        new Item("c5e4623", "Item2"),
        new Item("bf1932f", "Item3"));
    assertEquals("", verifyItems(items));
  }

  @Test
  public void testDuplicate() throws Exception {
    List<Item> items = Arrays.asList(
        new Item("baf18c4", "Item1"),
        new Item("c5e4623", "Item2"),
        new Item("baf18c4", "Item3"),
        new Item("baf18c4", "Item4"));
    assertEquals("Some of the items are sharing the same code: 'baf18c4' used by {Item1, Item3, Item4}", verifyItems(items));
  }

  @Test
  public void testDuplicate2() throws Exception {
    List<Item> items = Arrays.asList(
        new Item("baf18c4", "Item1"),
        new Item("c5e4623", "Item2"),
        new Item("baf18c4", "Item3"),
        new Item("bf1932f", "Item4"),
        new Item("c5e4623", "Item5"));
    assertEquals("Some of the items are sharing the same code: 'baf18c4' used by {Item1, Item3}, 'c5e4623' used by {Item2, Item5}", verifyItems(items));
  }

  public static class Item {
    private String code;
    private String description;

    public Item(String code, String description) {
      super();
      this.code = code;
      this.description = description;
    }

    public String getCode() {
      return code;
    }

    public String getDescription() {
      return description;
    }
  }
}


texts: Where should I put menu items in MVC with PHP - Model or Controller?

texts:
This is my first attempt with MVC and I almost get it, but a small thing bothers me.

I have this controller in CodeIgniter:

<?php
class Page extends CI_Controller {

    public function index($page = "home")
    {
            $data['page'] = $page;
            list($data['title']) = array_keys($this->_menu(), $page);
            $data['menuItems'] = $this->_menu();

            $this->load->view('templates/header', $data);
            $this->load->view('templates/menu', $data);
            $this->load->view('pages/'.$page, $data);
            $this->load->view('templates/footer', $data);
    }

    private function _menu()
    {
        static $menuItems = array(
                           "Home page" => "home",
                           "Our history" => "history",
                           "About us" => "about",
                           "Contact page" => "contact"
                       );

        return $menuItems;
    }
}

And here is the menu view:

<?php
$menu = "";
foreach ($menuItems as $menuName => $view) {
    $menu .= '
';
        $menu .= '';
    } else {
        $menu .= '>';
    }
    $menu .= $menuName . '
' .PHP_EOL ;
}

echo $menu;

Where do the menu items belong in MVC logic?  Is it ok to store things like the menu in the Controller or do I have to make a new Model for it like this?

class Menu extends CI_Model {

    public function __construct()
    {
        parent::__construct();
    }

    public function get_menu_items()
    {
        static $menuItems = array(
                           "Home page" => "home",
                           "Our history" => "history",
                           "About us" => "about",
                           "Contact page" => "contact"
                       );

        return $menuItems;
    }
}

Then load it from Controller:

public function index($page = "home")
{
    ...
    $this->load->model('Menu');
    $data['menuItems'] = $this->Menu->get_menu_items();

    $this->load->view(...);
    $this->load->view(...);
    $this->load->view(...);
}


texts:
I wrote a program to convert float to it's binary IEEE754 representation in C.
Any improvements to this is appreciated
#include <stdio.h>
#include <stdlib.h>
void binary(float num) {
    int n = *(int *) &num; //Evil bit hack from Quake3 Q_sqrt function
    int size = sizeof(n) * 8;
    char *s = malloc(1 + size); //A string which can hold 32 characters
    s[size] = '\0';
    int index = size - 1;
    while(index >= 0) {
        if (n & 1)
            *(s + index) = '1';
        else
            *(s + index) = '0';
        n >>= 1;
        index--;
    }
    printf("%s\n", s);
    free(s);
}

int main(void) {
    float num;
    scanf("%f", &num);
    binary(num);
}


texts:
I wrote the following code to deal with possible network problems.

def getPage(browser: Browser, page: String): Document =
    {
      var attempts = 5
      while (attempts > 0) {
        try {
          return browser.get(page)
        } catch {
          case ste: java.net.SocketTimeoutException if attempts == 1 => throw ste
          case ste: java.net.SocketTimeoutException => attempts -= 1
        }
      }
      return null
    }

I am new to scala and would appreciate if there is a better, "scala-way" of implementing similar

Document and Browser are classes from Scalascraper lib which is a wrapper around JSoup lib.


texts:
I'm currently building a Node/Express app using Passport for user authentication and Sequelize for database queries. It's a 'To-do list' app which currently has 3 models: User, List and Task. My back-end database calls are done using an API. My front-end uses AJAX to retrieve the data.

This is my first time using Passport for authentication, so I was wondering if there are any security problems in my current code. I am specifically concerned about Users being able to retrieve info about other Users by modifying the requests to my API.

Here is an example of an API call to create a List:

// Create list
router.post('/lists', isLoggedIn, (req, res) => {
    models.List.build( { name: req.body.name, userId: req.user.id } ).save()
    .then(list => {
        res.send(list);
    })
    .catch(err => {
        res.send(err);
    });
});

// ... other API calls

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.redirect('/');
}

And the front-end function that calls it:

// Create list and open it
function addList(name) {
    if (!name.length) return;
    $.ajax({
           type: "POST",
           url: '/api/lists',
           data: { name: name },
           success: function(data)
           {
               window.location = "/lists/"+data.id;
           }
         });
}

I am 99% sure that this is a secure implementation, since it seems like any data sent in the POST request is contained within req.body, whereas req.user is generated by Express/Passport on the server side. However there is still the 1% of me that thinks it might be possible to modify req.user in the POST request and be able to get information about other Users.

Are my worries for nothing, or is there a better way to implement this?


texts: Implementing "day wise task management" system using Django and AngularJS

texts:
I have a Task model in Django which looks like the following:

class Task(TimeStampedModel):
    project = models.ForeignKey(Project, related_name='tasks')
    date = models.DateField(_('date'))
    task = models.TextField(_('what\'s the task?'))
    status = models.CharField(
        _('what\'s the status'), default=constants.TASK_STATUS_EMPTY,
        max_length=40, choices=constants.TASK_STATUS_CHOICES)
    status_note = models.TextField(_('write a note about status'), blank=True)

    created_by = models.ForeignKey(User, related_name='created_tasks')
    modified_by = models.ForeignKey(User, related_name='modified_tasks')

    class Meta:
        ordering = ('-created', '-modified')

    def __unicode__(self):
        return self.task

Here is a screenshot of the final implementation:

I have exposed this Task model using django-tastypie as a RESTful api.

On client side, I have used AngularJS for editing/adding tasks.

I need to group tasks by project and date for rendering them properly. I have used _.groupBy method of lodash.js for this.

I wanted to know if there is a better approach to implement same interface.


texts: A toy example of the concurrent stack via atomic variables and CAS pattern

texts:
I've written a toy example of the concurrent stack which has only three functions push(), peek(), and length(). I've used atomic variables for synchronization. Is there anything incorrect in terms of synchronization? Could you please review this code?
#include <iostream>
#include <thread>
#include <atomic>
#include <vector>

template <typename T>
struct Node {
    Node<T>* next{};
    T val{};
    Node(const T& v) : val(v) {};
};

template <typename T>
class Stack {
    std::atomic<Node<T>*> top{};
    std::atomic<size_t> size{};
    public:
    void push(const T& data) {
        Node<T>* node = new Node<T>(data);
        size_t length = size.load(std::memory_order_relaxed);
        node->next = top.load(std::memory_order_relaxed);
        while(!std::atomic_compare_exchange_weak_explicit(&top, &node->next, node, std::memory_order_release, std::memory_order_relaxed));
        while(!std::atomic_compare_exchange_weak_explicit(&size, &length, size + 1, std::memory_order_release, std::memory_order_relaxed));
    }
    Node<T>* peek() {
        return top.load();
    }
    size_t length() const {
        return size;
    }
};

template <typename T>
class Runner {
    int cnt{};
    Stack<T>* ss{};
    public:
        Runner(const int n, Stack<T>* s) : cnt(n), ss(s) {}
        void operator()() {
            for(int i = 0; i < cnt; ++i) {
                size_t size = ss->length();
                if(size >= cnt) {
                    return;
                }
                ss->push(i);
            }
        }
        Stack<T>* get_stack() const {
            return ss;
        }
};

int main() {
    std::vector<std::thread> threads{};
    Stack<int>* s = new Stack<int>();
    int n = 10;
    Runner<int> r(n, s);
    for(int i = 0; i < 3; ++i) {
        threads.push_back(std::move(std::thread(r)));
    }
    for(int i = 0; i < 3; ++i) {
        threads[i].join();
    }
    Stack<int>* top = r.get_stack();
    Node<int>* head = top->peek();
    while(head) {
        std::cout << head->val << ", ";
        head = head->next;
    }
    size_t size = top->length();
    return 0;
}


texts: Solution of class design issue of generic of restricted type

texts:
I am developing a statistics library in .net. I have developed a Set<T> data structure. Now, I want to derive a data structure named DescriptiveStatisticalSet<T>, and I want this set to be able to operate only on integer and double types.
Problem:

I want to implement a generic type that is able to work with integer
and double data types only.
Say, I have the following interfaces and classes:
public interface IIntegerDataType
{
    int Data { get; set; }
    int Add(int other);
}

public interface IDoubleDataType
{
    double Data { get; set; }
    double Add(double other);
}
public class IntegerDataType : IIntegerDataType
{
    public int Data { get; set; }

    public int Add(int other)
    {
        return Data + other;
    }
}
public class DoubleDataType : IDoubleDataType
{
    public double Data { get; set; }

    public double Add(double other)
    {
        return Data + other;
    }
}

Is it possible to create a generic type DataType<T> so that both
(and only) IntegerDataType and DoubleDataType could be accessed
through that generic type?

Solution:
I have devised the following solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTypeNamespace
{
    public interface IDataType
    {
        object Add(object other);
        void SetVal(object other);
    }
    public interface IDataType<T> where T : IDataType, new()
    {
        T Add(T other);
    }
    class IntegerDataType : IDataType
    {
        public int Data { get; set; }

        public object Add(object other)
        {
            int o = ((IntegerDataType)other).Data;
            return Data + o;
        }
        public void SetVal(object other)
        {
            Data = (int)other;
        }
    }

    class DoubleDataType : IDataType
    {
        public double Data { get; set; }

        public object Add(object other)
        {
            double o = ((DoubleDataType)other).Data;
            return Data + o;
        }

        public void SetVal(object other)
        {
            Data = (double)other;
        }
    }

    public class DataType<T> : IDataType<T> where T : IDataType, new()//https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint
    {
        IDataType _item;
        public DataType(IDataType item)
        {
            _item = item;
        }

        public T Add(T other)
        {
            object o = _item.Add(other);

            T t = new T();

            t.SetVal(o);

            return t;
        }
    }

    public class MainClass
    {
        public static void Main(string[] args)
        {
            //IntegerDataType item1 = new IntegerDataType();
            //item1.Data = 10;

            //IntegerDataType item2 = new IntegerDataType();
            //item2.Data = 20;

            //DataType<IntegerDataType> l1 = new DataType<IntegerDataType>(item1);
            //IntegerDataType sum1 = l1.Add(item2);

            DoubleDataType item3 = new DoubleDataType();
            item3.Data = 10.5;

            DoubleDataType item4 = new DoubleDataType();
            item4.Data = 20.5;

            DataType<DoubleDataType> l2 = new DataType<DoubleDataType>(item3);
            DoubleDataType sum2 = l2.Add(item4);
        }
    }
}

Can someone review this? Or, maybe help me to improve?


texts:
I am trying to write up all the linked list basic operations (push, pop, add_at_end, pop_from_end, add_at_index, pop_from_index). This is not a school assignment, even though it may look like one. I have written the code. I have tested it myself quite a bit, although I am no C guru. I would like it if you could tell me if there are any suggestions / corrections you have for the code in terms of efficiency, memory handling, readability, clarity etc.

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

typedef struct node {
    int data;
    struct node * next;
} node_t;

void print_list(node_t * head);
void push(node_t ** head, int data);
int pop(node_t ** head);
int add_at_end(node_t ** head, int data);
int remove_last(node_t * head);
int add_at_index(node_t ** head, int n, int data);
int remove_by_index(node_t ** head, int n);

int main()
{
    node_t * head = NULL;

    head = malloc(sizeof(node_t));
    if (head == NULL) {
      return 1;
    }
    head->data = 1;
    head->next = NULL;
    print_list(head);
    return 0;
}

void push(node_t ** head, int data) {
    node_t * new_node;
    new_node = malloc(sizeof(node_t));
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
}

void print_list(node_t * head) {
    node_t * current = head;

    while (current != NULL) {
        printf("%d\n", current->data);
        current = current->next;
    }
}

int add_at_end(node_t ** head, int data) {
    node_t * new_node = malloc(sizeof(node_t));
    new_node->data = data;
    new_node->next=NULL;
    if(*head==NULL){
        *head = new_node;
        return 1;
    }
    node_t * current = *head;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = new_node;
    return 1;
}

int add_at_index(node_t ** head, int n, int data) {
    node_t * current = *head;
    node_t * temp_node = NULL;
    if(n == 0 || *head==NULL){
        push(head, data);
        return 1;
    }
    while(n>1 && current->next!=NULL){
        current = current->next;
        n--;
    }
    if(n>1){
        return -1;
    }

    temp_node = malloc(sizeof(node_t));
    temp_node->data = data;
    temp_node->next = current->next;
    current->next = temp_node;
    return 1;
}

int remove_by_index(node_t ** head, int n) {
    node_t * current = *head;
    node_t * curr_head = NULL;
    if(n == 0||*head==NULL){
        pop(head);
        return 1;
    }
    while(n>0 && current->next!=NULL){
        curr_head = current;
        current = current->next;
        n--;
    }
    if(n>0){
        return -1;
    }
    curr_head->next = current->next;
    free(current);
    return 1;
}

int pop(node_t ** head) {
    int retval = -1;
    if (*head == NULL) {
        return -1;
    }
    if ((*head)->next == NULL) {
        printf("here");
        retval = (*head)->data;
        free(*head);
        *head = NULL;
        return retval;
    }
    node_t * next_node = NULL;
    next_node = (*head)->next;
    retval = (*head)->data;
    free(*head);
    *head = next_node;
    return retval;
}

int remove_last(node_t * head) {
    int retval = 0;
    if (head->next == NULL) {
        head->data;
        free(head);
        head = NULL;
        return retval;
    }

    node_t * current = head;

    while (current->next->next != NULL) {
        current = current->next;
    }
    retval = current->next->data;
    free(current->next);
    current->next = NULL;
    return retval;
}


texts: Unwanted return values in lambda functions?

texts:
From a previous question, I got the idea of moving boilerplate code structures into a helper function and passing in a lambda function to it.

I then applied the idea to a data access class (code below).  I'm not sure how to handle the result of my ProcessDatabaseCall helper function; it seems irrelevant to my pattern of use-cases.  In this example I'm returning an IEnumerable; in other cases I'm returning int, School, etc.

    public IEnumerable<School> SchoolsList(string searchChars)
    {
        DataSet ds = new DataSet();
        List<School> schools = new List<School>();
        bool cool = ProcessDatabaseCall("dbo.usp_esrvs_API_SchoolList", cmd => {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@SearchValue", searchChars));

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);

            return true;
        });

        //Foreach row in the data set add a json array object
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            schools.Add(new School((int) row["esrvs_Account_ID"], row["SchoolName"].ToString()));
        }
        return schools;
    }

    private bool ProcessDatabaseCall(string procedureName, Func<SqlCommand,bool> processor)
    {
        using (SqlConnection Mackin1Conn = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(procedureName, Mackin1Conn))
            {
                return processor(cmd);
            }
        }
    }

The function used to look like this:

public IEnumerable<School> SchoolsList(string searchChars)
    {
        DataSet ds = new DataSet();
        List<School> schools = new List<School>();
        using (SqlConnection Mackin1Conn = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand("dbo.usp_esrvs_API_SchoolList", Mackin1Conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@SearchValue", searchChars));
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
        }
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            schools.Add(new School((int) row["esrvs_Account_ID"], row["SchoolName"].ToString()));
        }
        return schools;
    }


texts:
I have a WPF application where I have a function for generating an overlaying info grid.

I have written some code for queueing the messages(IpopupMessage) so that each displays a certain amount of time

public interface IPopupMessage
{
    string Description { get; set; }
    TimeSpan Duration { get; set; }
    SolidColorBrush MessageColor { get; set; }
    string Title { get; set; }
}

This is the code for displaying and hiding the UI-element

private readonly Queue<IPopupMessage> PopupMessageQueue = new Queue<IPopupMessage>();

public void DisplayPopupmessage(IPopupMessage obj)
{
    this.PopupMessage = obj;
    if (obj.Duration > TimeSpan.Zero) this.HideErrorMessageAfter(obj.Duration);
}

protected async void HideErrorMessageAfter(TimeSpan delayTime)
{
    await Task.Delay(delayTime);
    if (this.PopupMessageIsVisible) this.PopupMessageIsVisible = false;
}

private void CancelPopupMessage()
{
    this.PopupMessageIsVisible = false;
}

private async void UpdatePopupMessage(IPopupMessage obj)
{
    //Adding the message to the queue
    this.PopupMessageQueue.Enqueue(obj);
    //never ending loop
    while (true)
        //PopupMessageIsVisible is a boolean with binding to the UI element
        if ((this.PopupMessageQueue.Count > 0) && (this.PopupMessageIsVisible == false))
        {
            this.PopupMessageIsVisible = true;
            this.DisplayPopupmessage(this.PopupMessageQueue.Dequeue());
        }
        else
        {
            await Task.Delay(TimeSpan.FromSeconds(1));
        }
}

Is there a cleaner more efficient way for this? I have tried some variants with single thread TPL actionblock, but the timer in HideErrorMessageAfter would set PopupMessageIsVisible false and cut the next message short.

I also tried creating a continuous Queue where every queued item would get consumed automatically, but I could not get it to work.

Do you have any tips for making this code more efficient?


texts: Testing whether pages can be fetched from two ports

texts:
I have an endpoint in my API which does a port test on 4455 and 4456 once a client GET's it. This is accomplished by requesting two web pages. The result will respond to the client with a JSON object:

{
    "4455": 200,
    "4456": 200
}

I have the following code

app.get(networkPfix + "/portcheck", (req, res) => {
        http.get('http://foo.com:4455/', (res, error) => {
            let status_code1 = res.status_code;
            http.get('http://foo.com:4456/', (res, error) => {
                let status_code2 = res.status_code;
                res.status(200).send({"4455": status_code1, "4456": status_code2});
            }).on("error", (err) => {
                let status_code2 = 0;
                res.status(200).send({"4455": status_code1, "4456": status_code2});
            });
            }).on("error", (err) => {
                let status_code1 = 0;
                http.get('http://foo.com:4456', (res, error) => {
                    let status_code2 = res.status_code;
                    res.status(200).send({"4455": status_code1, "4456": status_code2});
                }).on("error", (err) => {
                    let status_code2 = 0;
                    res.status(200).send({"4455": status_code1, "4456": status_code2});
                });
        });
    })

I'm quite new to Node, but surely there must be a neater way to achieve this, perhaps with less nesting?

To explain my code a little:

I need to test two webpages (one on each port)
Both webpages must be tested, even if there are errors
Timeouts would be nice, but I couldn't find a reliable way of stopping the callback
Return the JSON object to the client at the end


texts: jQuery delegate events on dynamic elements with a click away handler

texts:
Just thought I'd share this and see what kind of improvements could be made that I'm not aware of and taking advantage of.

The situation is this: I have a list of items on a page that have a button that opens a menu. I need a click away event as well as close others when a new menu is opened. Also some of the menu actions will replace items in the list which means I have new dynamic menu buttons on the page.

To do this efficiently (as far as I can tell) you need to use event delegation and it ends up looking like this:

$(document).delegate( '.button', 'click', function(e){
    var $button = $(this);
    var $menu = $button.closest('.menu');
    e.stopPropagation();

    // Close others
    $('.button').each(function(){
      $(this).closest('.menu').removeClass('open');
    });

    // Toggle target open/close
    if( $menu.hasClass('open') ){
        $menu.removeClass('open');
    }
    else{
        $menu.addClass('open');
    }
    $(document).on('click', function(e){
        var $target = $(e.target);
        if( !$target.is( $( $menu.find('button') ) ) ){
            if( $menu.hasClass('open') ){
                $menu.removeClass('open');
            }
        }
    });
});

Maybe there's a better way?