texts: Display Thousands/Millions of different background images

texts:
Kindly help me check this code, I want to be able to make it load thousands/millions of different pictures as HTML background without crashing or slowing down the browser.

The images can be created dynamically, or linked to its folder, I was able to do that for up to 1000 images/colors per canvas, and add up many more canvas, but at 30 canvas, which is 30,000 images/colors the browser stops to respond(slowish). Tested only on google chrome, so help me achieve tens of millions random colors/pictures.

FYI: The images must be displayed all at once.

  Rihana Photo Mosaic or picturemosaics this is similar to what i want to achieve, as you can see about 36,000 images without any performance issue, they even boast of more than 5 million pictures. Mine should be easier because my pictures are to be random or in a pattern not necessarily being in a mosaic form. If you have another method or way to achieve it, that would be helpful too.

<html>
<body>
  <script>
  var cInt=0;
  var loopCInt=0;
  while (loopCInt<3){
   var canvasName = document.createElement("canvas");
   canvasName.setAttribute('width', "1000");
   canvasName.setAttribute('height', "1000");
   var canvasIdName="myCanvas"+cInt;
   canvasName.setAttribute('id', canvasIdName);
   document.body.appendChild(canvasName);
    var c = document.getElementById(canvasIdName);
    var ctx = c.getContext("2d");
    var i = 0;
    var right=0;
    var tops=0;
    var goDown=0;
    while (i <= 1000) {
      ctx.beginPath();
      ctx.rect(right, goDown, 30, 30);
      ctx.fillStyle = '#'+Math.random().toString(16).slice(-6);
      ctx.fill();
      i++;
      right=right+30;
      tops++;
      if (tops==30){
        goDown=goDown+30;
        right=0;
        tops=0;
      }
    }

  loopCInt++;
  cInt++;
}
</script>
</body>
</html>


texts: Search key in a rotated sorted array without repetition of elements

texts:
Is there any improvement possible in this implementation?

#include<iostream>

int search( int array[], int N, int key )
{
    int first_index = 0;
    int last_index = N - 1;

    while ( last_index >= first_index )
    {
        int middle_index = last_index + first_index / 2;

        if( array[ middle_index ] == key )
           return middle_index;

        if ( array[ first_index ] < array [ middle_index ] )
        {
            if( key >=  array[ first_index ] && key < array [ middle_index ] )
                last_index = middle_index - 1;
            else
                first_index = middle_index + 1;
        }
        else
        {
            if( key > array [ middle_index ] && key <= array [ last_index ])
                first_index = middle_index + 1;
            else
                last_index = middle_index - 1;
        }
    }
    return -1;
}

int main()
{
    int array[] = { 2, 4, 5, 6, 7, 0, 1 };
    int index = search( array, 7, 0 );

    std::cout<<"index :"<<index;

}


texts: Calculating a factorial with parallel sub-computations using pmap, pvalues and pcalls

texts:
In an attempt to learn more about Clojure's parallel computation functions, I devised the following task: calculate a factorial in parallel using pmap, pcalls and pvalues.

The idea is to split the factorial sequence into sub-computations, reducing the final output of each.

Here is the obvious non-parallel function:

(defn factorial [n] (reduce * (range 1 (inc n))

pmap is fairly straight-forward:

(defn pmap-factorial [n psz]
  (let [parts (partition-all psz (range 1 (inc n)))]
    (reduce * (pmap #(apply * %) parts))))

However, with pvalues I had to resort to macros that return a computation function.

(defmacro pvalues-factorial [n psz]
  (let [exprs (for [p (partition-all psz (range 1 (inc n)))]
                 (cons '* p))]
    `(fn [] (reduce * (pvalues ~@exprs)))))

Similar approach with pcalls:

(defmacro pcalls-factorial [n psz]
  (let [exprs (for [p (partition-all psz (range 1 (inc n)))]
                     `(fn [] (* ~@p)))]
    `(fn [] (reduce * (pcalls ~@exprs)))))

So, I had to use macros for pcalls and pvalues. Does not seem ideal, but it was the only way I could accomplish the above (and perhaps indicates that pmaps is the best practice for this use case).

Questions:

1) How could the code be made more correct / idiomatic?

2) Did I have to resort to macros for pvalues and pcalls, or have I overlooked another way of accomplishing my goal with these functions?


texts: Is my code overdesigned? Does it rely too heavily on interfaces?

texts:
Context:

I am using XNA to create a simple game / learning project.

Problem:

I have three interfaces, each with a different purpose in mind. However, the way I use them, as well as their implementations, makes me feel as if my code is overdesigned and poorly thought out, so I am looking for better approaches, if possible.

IGrid<T> is intended to wrap a 2-dimensional array, exposing only the Size and indexer.
IChunk<T> is intended to be a grid object with a predetermined size.
IMesh<T> is intended to be a grid, but with several methods to manipulate and transform the data.

Interfaces:

public interface IGrid<T>
{
    Point Size { get; }
    T this[int x, int y] { get; set; }
}

public interface IChunk<T> : IGrid<T>
{
}

public interface IMesh<T> : IGrid<T>
{
    IMesh<T> Clone();
    IMesh<T> Flip(bool horizontal, bool vertical);
    IMesh<T> Rotate(bool clockwise);
    IMesh<T> Slice(Rectangle value);
    IMesh<T> Slice(int x, int y, int width, int height);
    IMesh<T> Transpose();
}

The idea is that I would use IGrid to create a "custom array" which could be inherited from. IChunk would hold a finite part of the world, breaking it apart for easier/segmented access, while IMesh would let me define a heightmap (with T:float), for example, and let me merge and manipulate them very easily (for generating terrain and the like).

Classes:

A secondary concern is defining custom operators for my Mesh class, in such a way that they could easily be added, subtracted, multiplied, etc. Now, because operator overloading involves static methods, it can't really be inherited in an elegant way.

I had tried a pattern in which I made an abstract MeshBase class that defined the operators, which called protected and abstract methods as handlers for the operations, but because of the typing involved, simply adding three meshes together involved heavy usage of casting. Needless to say, it was messy and almost unusuable.

My current solution is to do something like the following to have more control over the manipulation:

public class Mesh<T> : Grid<T>, IMesh<T>
{
    public Mesh(int x, int y)
        : base(x, y)
    {
    }

    // Clone(), Flip(), Rotation(), Slice(), Transpose() methods here
}

public class FloatMesh : Mesh<float> // Used as a heightmap!
{
    // Add the values of the two meshes together, creating a new mesh
    public static FloatMesh operator +(FloatMesh a, FloatMesh b) { }

    // Add the value of "b" to every element of "a", creating a new mesh
    public static FloatMesh operator +(FloatMesh a, float b) { }
}

public class Vector2Mesh : Mesh<Vector2> // Possibly used for sampling perlin noise
{
    // Add the values of two meshes together, creating a new mesh
    public static Vector2Mesh operator +(Vector2Mesh a, Vector2Mesh b) { }

    // Apply the XY values of "b" to every element of "a", creating a new mesh
    public static Vector2Mesh operator +(Vector2Mesh a, Vector2 b) { }

    // Apply the value of "b" to each XY value of every element of "a", creating a new mesh
    public static Vector2Mesh operator +(Vector2Mesh a, float b) { }
}

Obviously, I would need to define these operators for every specific type I wanted to use. Nothing is stopping the user from making a Mesh themselves, if they're only interested in Transpose(), etc., but using a more derived class offers the ability to use convenient operators in addition to the transformation methods.

Conclusion:

Anyways, I am interested in whatever feedback you guys can offer. Like I said, I don't know if I made this in a very roundabout way, or if there is an easier/simpler way of accomplishing what I want.


texts:
I have the following wx.Window:

class SketchWindow(wx.Window):

  def __init__(self, parent):
    wx.Window.__init__(self, parent, -1)
    self.SetBackgroundColour('White')
    # Window event binding
    self.Bind(wx.EVT_PAINT, self.OnPaint)
    self.Bind(wx.EVT_IDLE, self.OnIdle)
    # run
    self.Run()

  def OnPaint(self, evt):
    self.DrawEntities(wx.PaintDC(self))

  def DrawEntities(self, dc):
    dc.SetPen(wx.Pen('Black', 1, wx.SOLID))
    dc.SetBrush(wx.Brush('Green', wx.SOLID))
    # draw all
    for e in self.entities:
      x, y = e.location
      dc.DrawCircle(x, y, 4)

  def OnIdle(self, event):
    self.Refresh(False)

  def Run(self):
    # update self.entities ...
    # call this method again later
    wx.CallLater(50, self.Run)

I need to draw on my window a number of circles [0, 2000] every N milliseconds (50 in my example), where at each step these circles may update their location.

The method I wrote works (the circles are anti-aliased too) but it's quite slow.
Is there a way to improve my solution?


texts: Using bucket sort to rank students based on their marks

texts:
Problem:

  n students have marks and names. Rank students based on their marks and print their names.

#include <stdio.h>
#include <assert.h>

struct student
{
    int marks;
    char name[50];
};

struct listnode
{
    struct student * data;
    struct listnode *next;
};

addtofrontoflist(struct listnode *listhead,struct student *node)
{
    //make a block of listnode.
    struct listnode bucketnode;
    bucketnode.data=node;

    struct listnode *tmp;
    tmp=listhead->next;
    listhead->next=&bucketnode;
    bucketnode.next=tmp;
}

bucket_sort(struct student array[],int n)
{
    struct listnode *buckets[n];
    int i,j;
    struct listnode *temp;
    for(i=0;i<n;i++)
    {
            buckets[i]=malloc(sizeof(struct listnode));
            assert(buckets[i]!=NULL);
    }

    for(i=0;i<n;i++)
    {
            addtofrontoflist(buckets[array[i].marks],&array[i]);
    }

    for(i=0;i<n;i++)
    {
            if(buckets[i]==NULL) continue;
            for(temp=buckets[i];temp!=NULL;temp++)
            printf("%d %s\n",temp->data->marks,temp->data->name);
    }
}

main()
{
    struct student array[5]={"1,one","2,two","2,two","4,four","1,one"};
    bucket_sort(array,5);
}


texts:
Recently I started programming with python.
Today I was trying to make a stone, paper, scissor game. After so scratching my head long time, finally I got a working code.

from random import choice

def play_again():
        print "Do you want to play again:- Choose 'yay' or 'nay'"
        user_again = raw_input('->')
        if user_again == 'yay':
            SPCa()
        elif user_again == 'nay':
            print "Ok bye! hope you enjoyed the game. See you soon! :)"
        else:
            print "Please choose correct option."
            play_again()

def SPCa():
    computer_choice = choice( ['stone', 'paper', 'scissor'] )
    computer_choosed =  "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = raw_input('->')

    if user_choice == computer_choice:
        print computer_choosed
        print "So it's a tie"
        play_again()

    elif user_choice == 'stone':
        if computer_choice == 'paper':
            print computer_choosed
            print "So, You loose"
            play_again()
        elif computer_choice == 'scissor':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()

    elif user_choice == 'paper':
        if computer_choice == 'scissor':
            print computer_choosed
            print "So, you loose."
           play_again()
        elif computer_choice == 'stone':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()

   elif user_choice == 'scissor':
        if computer_choice == 'stone':
            print computer_choosed
            print "So, you loose."
            play_again()
        elif computer_choice == 'paper':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()
    else:
         print "please choose correct option"
        SPCa()

def SPC():
    computer_choice = choice( ['stone', 'paper', 'scissor'] )
    computer_choosed =  "Computer choosed %s" % computer_choice
    print "You are playing Stone, Paper, Scissor."
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = raw_input('->')

    if user_choice == computer_choice:
        print computer_choosed
        print "So it's a tie"
        play_again()

   elif user_choice == 'stone':
        if computer_choice == 'paper':
            print computer_choosed
            print "So, You loose"
            play_again()
        elif computer_choice == 'scissor':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()

    elif user_choice == 'paper':
        if computer_choice == 'scissor':
            print computer_choosed
            print "So, you loose."
            play_again()
        elif computer_choice == 'stone':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()

    elif user_choice == 'scissor':
        if computer_choice == 'stone':
            print computer_choosed
            print "So, you loose."
            play_again()
        elif computer_choice == 'paper':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()
    else:
        print "please choose correct option"
        SPCa()
SPC()

But I found my code so repetitive, it has not even a single loop. Please suggest how can I improve my code. What are things that I should learn?


texts:
I wrote a BST in C a while back and may use it at some point.

 search_tree tree_make_empty( search_tree tree )
 {
   if ( tree != NULL )
   {
       tree_make_empty( tree->left );
       tree_make_empty( tree->right );
       free( tree );
   }
   return NULL;
 }

 tree_position tree_find( CHAR_DATA *target, search_tree tree )
 {
     if ( tree == NULL )
       return NULL;

     if ( target < tree->hatedata->target_char )
       return tree_find( target, tree->left );
     else if ( target > tree->hatedata->target_char )
       return tree_find( target, tree->right );
     else
       return tree;
 }

 search_tree tree_insert( HATE_DATA *hatedata, search_tree tree )
 {
     if ( tree == NULL )
     {
       tree = (HATE_NODE * ) malloc( sizeof( HATE_NODE ) );

       if ( tree == NULL )
          bug( "tree_insert: out of space!" );
       else
       {
          tree->hatedata = hatedata;
          tree->left = tree->right = NULL;
       }
     }
     else if ( hatedata->target_char < tree->hatedata->target_char )
       tree->left = tree_insert( hatedata, tree->left );
     else if ( hatedata->target_char > tree->hatedata->target_char )
          tree->right = tree_insert( hatedata, tree->right );

     return tree;
 }

 tree_position tree_find_min( search_tree tree )
 {
    if ( tree == NULL )
       return NULL;
    else if ( tree->left == NULL )
       return tree;
    else
       return tree_find_min( tree->left );
 }

 search_tree tree_delete( HATE_DATA *hatedata, search_tree tree )
 {
    tree_position pos;

    if ( tree == NULL )
       bug( "tree_delete: not found" );
    else if ( hatedata->target_char < tree->hatedata->target_char )
       tree->left = tree_delete( hatedata, tree->left );
    else if ( hatedata->target_char > tree->hatedata->target_char )
         tree->right = tree_delete( hatedata, tree->right );
    else if ( tree->left && tree->right )
    {
       pos = tree_find_min( tree->right );
       tree->hatedata = pos->hatedata;
       tree->right = tree_delete( tree->hatedata, tree->right );
    }
    else
    {
       pos = tree;
       if ( tree->left == NULL )
         tree = tree->right;
       else if ( tree->right == NULL )
         tree = tree->left;
       free( pos );
    }

    return tree;
 }

 HATE_DATA *tree_retrieve( tree_position pos )
 {
    return pos->hatedata;
 }

...

 struct hate_data
 {
    CHAR_DATA *target_char;
    int hate_amount;
 };

 struct hate_node
 {
    HATE_DATA *hatedata;
    search_tree left;
    search_tree right;
 };

...

mob->hatedata = tree_make_empty( NULL );

Example use:

if ( IS_NPC(victim) )
{
     HATE_DATA *hatedata;
   tree_position P;

   if( ( P = tree_find( ch, victim->hatedata )) == NULL || tree_retrieve( P )->target_char != ch )
   {
     int test;
     hatedata = (HATE_DATA * ) malloc( sizeof( HATE_DATA ) );
     hatedata->target_char = ch;
     test = number_range( 1, 50 );
     hatedata->hate_amount = test;
     victim->hatedata = tree_insert( hatedata, victim->hatedata );
     ch_printf( ch, "It should now hate you for %d.\n\r", test );
   }
   else
   {
     hatedata = tree_retrieve(tree_find( ch, victim->hatedata ));
     ch_printf(ch, "You are already hated for %d!\n\r", hatedata->hate_amount );
   }

}

Do you have any suggestions? Does it look okay? Are there any ways to optimize it?


texts:
A friend of mine wanted an array-to-CSV string function for Node.js, so I came up with this. Basically, it can take in a single object, a 2D array or an array of objects.

If the children or parent is an object then the object properties become the headers, if the children are arrays then the first array is the headers.

Each cell is enclosed inside double quotes in the case of commas inside of the cell, and any double quotes inside the cell are escaped. Is there anything else I should be escaping?

exports.objectToCSVString = function (ob) {
    var str = "", row, a, i, o, c, r;
    if(ob instanceof Object && !(ob instanceof Array)){
        ob = [ob];
    }
    if(ob instanceof Array){
        for(r in ob){
            if(ob.hasOwnProperty(r)){
                row = ob[r];
                if(row instanceof Array){
                    a = "";
                    for(i in row){
                        if(row.hasOwnProperty(i)){
                            a += a.length === 0 ? "" : ",";
                            a += "\"" + row[i].toString().replaceAll("\"", "\\\"") + "\"";
                        }
                    }
                    str += str.length === 0 ? a : "\r\n" + a;
                }else if(row instanceof Object){
                    if(o === undefined){
                        o = [];
                        a = "";
                        for(c in row){
                            if(row.hasOwnProperty(c)){
                                o.push(c);
                                a += a.length === 0 ? "" : ",";
                                a += "\"" + c.toString().replaceAll("\"", "\\\"") + "\"";
                            }
                        }
                        str += str.length === 0 ? a : "\r\n" + a;
                    }
                    a = "";
                    for(c in o){
                        if(o.hasOwnProperty(c) && row[o[c]] !== undefined){
                            a += a.length === 0 ? "" : ",";
                            a += "\"" + row[o[c]].toString().replaceAll("\"", "\\\"") + "\"";
                        }
                    }
                    str += str.length === 0 ? a : "\r\n" + a;
                }else{
                    throw "row is not an Array or object";
                }
            }
        }
        return str;
    }
    throw "Object is not an Array";
};

String.prototype.replaceAll = function(a, b){
var t = this, o = [], i;
//get all the occurances of it
for(i = 0; i < t.length; i+=1){
    if(t.substr(i, i - 1 + a.length) == a){
        o.push(i);
    }
}
for(i = 0; i < o.length; i+=1){
    t = t.substr(0, o[i] - 1) + b + t.substr(o[i] + b.length, t.length - 1);
}
return t;
};

Is the concept right? Do I cover everything when it comes to creating a CSV string? Any other comments?

Is there any way I can improve this or improve the performance? It seems to be rather quick when running, but I'm not sure what to base it on either.

Examples

Given I have required the file and it is names csv

csv.objectToCSVString({a:"a1",b:"b1"});

will output:

"a", "b"
"a1", "b1"

csv.objectToCSVString([{a:"a1",b:"b1"},{a:"a2",b:"b2"}]);

will output:

"a","b"
"a1","b1"
"a2","b2"

csv.objectToCSVString([["a", "b"], ["a1", "b1"], ["a2", "b2"]]);

will output:

"a","b"
"a1","b1"
"a2","b2"

csv.objectToCSVString({a:"a\"1\"",b:"b\"1\""});

will output:

"a","b"
"a\"1\"","b\"1\""

NOTE I am working on the replace all function, it doesn't work as it should yet


texts:
I wrote this simple implementation of the sum of primes for the code eval

Challenge Description:
Write a program which determines the sum of the first 1000 prime numbers.

I would like to know of a better - more efficient - way of implementing the solution.
import java.lang.Math;

public class SumOfPrimes {

    public static boolean isPrime(int n) {
        if (n < 2) {
            return false;
        }
        if (n == 2) {
            return true;
        }
        if (n % 2 == 0) {
            return false;
        }
        for (int i = 3; i <= Math.sqrt((double) n); i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        long sum = 0;

        for (int i = 1, count = 0; count < 1000; i++) {
            if (isPrime(i)) {
                sum += i;
                count++;
            }
        }
        System.out.print(sum);
    }

}

As for the primality test I only know of these other:
for (int divisor = 2; divisor < n; divisor++) {
    if (n % divisor == 0) {
        return false;
    }
}
return true;

and
for (int divisor = 2; divisor <= n/2; divisor++) {
    if (n % divisor == 0) {
        return false;
    }
}
return true;


texts:
I'm using Bootstrap. I'm doing my best to work with more semantic markup and getting away from divitis.

Several of these "card" blocks appear on a page, like this.

Original:

Card Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis ipsam eos, nam perspiciatis natus commodi similique totam consectetur praesentium molestiae atque exercitationem ut consequuntur, sed eveniet, magni nostrum sint fuga.

          Learn More

Rewritten:

Card Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente esse necessitatibus neque.

          Learn More

Could I improve the HTML?


texts: Alternate way for comparison call back function?

texts:
I'm doing a programming practice problem and was wondering if someone can suggest a better to create/setup the call back for the comparison function. I have the following classes:

public class myTreeItem<T> {
    private T item;
    private myTreeItem<T> left;
    private myTreeItem<T> right;
    private myTreeItem<T> parent;
}

I have the usual get/set functions. This item go into a tree, whose definition is:

public class myTree<T> {
    myTreeItem<T> root;
    protected comparableCallBack<T> callback; // call back function for comparisons, to be provided by the creator of the tree

    public interface comparableCallBack<T> {
        int onCompare(myTreeItem<T> item1, myTreeItem<T> item2);
    }
}

I omitted all the other functions to help with readability. I am creating the tree in the following way:

    // create a regular tree
    myTree<Integer> tree1 = new myTree<Integer>();
    tree1.setCallback(new comparableCallBack<Integer>() {
        public int onCompare(myTreeItem<Integer> item1,
                myTreeItem<Integer> item2) {
            // Do the actual comparison here.
            if (item1.getItem().intValue() < item2.getItem().intValue())
                return -1;
            else if (item1.getItem().intValue() == item2.getItem().intValue())
                return 0;
            else
                return 1;
            }
    });

Are there any other options/ideas for the call back?


texts:
I have two list of tuples:

 [[1,8],[2,7],[3,14]]
 [[1,5],[2,10],[3,14]]

and a desired sum 20. I need to find two tuples from two list whose second element either add it to the sum i.e 20 or the next lowest sum. In this case if we consider [3,14] and [1,5] the sum is 14+5=19 hence the output should be [3,1]

[1,3000],[2,5000],[3,7000],[4,10000]
[1,2000],[2,3000],[3,4000],[4,5000]]

the sum is 10000. Here we have [2,5000], [4,5000] and [3,7000], [2,3000] so the output should be [2,4] and [3,2]

[[1,2000],[2,4000],[3,6000]]
[[1,2000]]

the sum is 7000. Here since I don't have a combination that sum up to 7000 I consider all the possible combinations 4000(2000+2000), 6000(4000+2000) and 8000(6000+2000) and consider the next lowest number from the desired sum which is 600. For 6000 my output should be [2,4000] and [1,2000] which is [2,1].

import itertools

def optimalUtilization(maximumOperatingTravelDistance,
                       forwardShippingRouteList, returnShippingRouteList):

    result=[]
    t1=[]
    t2=[]
    for miles in forwardShippingRouteList:
        t1.append(miles[1])

    for miles in returnShippingRouteList:
        t2.append(miles[1])

    result.append(t1)
    result.append(t2)
    total_sum=set()

    for element in list(itertools.product(*result)):
        if sum(element)<=maximumOperatingTravelDistance:
            total_sum.add(sum(element))

    total_sum=sorted(total_sum,reverse=True)
    return optimalUtilizationhelper(total_sum[0],
                       forwardShippingRouteList, returnShippingRouteList)

def optimalUtilizationhelper(maximumOperatingTravelDistance,
                       forwardShippingRouteList, returnShippingRouteList):

    dist_dict={}
    for carid,miles in forwardShippingRouteList:
        dist_dict.update({miles:carid})

    result=[]

    for carid,miles in returnShippingRouteList:
        if (maximumOperatingTravelDistance-miles) in dist_dict:
            result.append(list((dist_dict[maximumOperatingTravelDistance-miles],carid)))

    return result

I get the desired result here but the complexity here is \$O(n^2 \log n)\$. What is a better way to do this?


texts: Program slows down significantly based on input

texts:
I've been writing a program to perform a kind of pattern-matching in XML and text files.

When my program reaches this section of the code, the CPU usage gets very high and the performance slows down to a point where the program seems to be frozen.  It actually isn't, but depending on the input (number of text files and their content), it may take several hours to complete the task.

I'm looking for a more efficient way to rewrite this section of the code:

List<string> CandidatesRet = new List<string>();

for (int indexCi = 0; indexCi < Ci.Count - 1; indexCi++)
{
    // generate all sub itemset with length-1

    string[] allItems = Ci[indexCi].Split(new char[] { ' ' });
    for (int i = 0; i < allItems.Length; i++)
    {
        string tempStr = "";
        for (int j = 0; j < allItems.Length; j++)
            if (i != j)
                tempStr += allItems[j] + " ";
        tempStr = tempStr.Trim();
        subItemset.Add(tempStr);
    }

    // THE PROBLEM BEGINS HERE

    foreach (string subitem in subItemset)
    {

        int iFirtS;
        for (int indexCommon = indexCi + 1; indexCommon < Ci.Count; indexCommon++)
            if ((iFirtS = Ci[indexCommon].IndexOf(subitem)) >= 0)
            {
                string[] listTempCi = Ci[indexCommon].Split(new char[] { ' ' });
                foreach (string itemCi in listTempCi)
                    if (!subitem.Contains(itemCi))
                        commonItem.Add(itemCi);
            }
        allCommonItems.Add(commonItem);
    }

    // generate condidate from common item
    foreach (string item in oldItemsetCi)
    {
        bool flagCi = true;
        foreach (List<string> listCommItem in allCommonItems)
            if (!listCommItem.Contains(item))
            {
                flagCi = false;
                break;
            }
        if (flagCi)
            CandidatesRet.Add((Ci[indexCi] + " " + item).Trim());
    }

There are many nested loops and I know this is the problem.  What do you think should be improved?


texts: design to send multiple type http request

texts:
I have to send multiple HTTP requests where their payload will be different, type will be different, headers will be different, URL will be different etc. The code I have right now is
pub async fn make_login_request(
    client: &Client,
    host: &String,
    credentials: &HashMap<String, String>,
) -> Result<(), reqwest::Error> {
    client
        .post(
            &(String::from("https://")
                + &String::from(host)
                + &String::from("/[URL]")),
        )
        .json(&credentials)
        .header(
            CONTENT_TYPE,
            "application/json, text/javascript, */*; q=0.01",
        )
        .send()
        .await?;
    Ok(())
}

This code makes a POST call, for GET call, it will be like
client
    .get(
        &(String::from("https://")
            + &String::from(host)
            + &String::from("/[URL]")),
    )
 ...

But, I will have to create a different function for GET call. Here, I will have to pass hostname, URL, headers, payload. So, what is the best approach I should take to write this code and handle the response?


texts: Roll a die according to the number of sides that the user enters

texts:
I have created a program which rolls a die according to the number of sides that the user enters:

def var():

    import random

    dicesides = int(input("Please enter the amount of sides you want the dice that is being thrown to have. The dice sides available are: 4, 6 and 12: "))
    script(dicesides, random)

def script(dicesides, random):

    if dicesides == 4:
        dice4 = int(random.randrange(1, dicesides))
        print(dicesides, " sided dice, score", dice4)

    elif dicesides == 6:
        dice6 = int(random.randrange(1, dicesides))
        print(dicesides, " sided dice, score", dice6)

    elif dicesides == 12:
        dice12 = int(random.randrange(1, dicesides))
        print(dicesides, " sided dice, score", dice12)

    elif dicesides != 4 or dicesides != 6 or dicesides != 12:
        print("That number is invalid. Please try again.")
        var()

    repeat = str(input("Repeat? Simply put yes or no : "))

    if repeat == "yes":
        var()
    else:
        quit()

var()

Is there a way to shorten this?


texts: How can this LINQ query using SqlFunctions.Datediff and LINQKit's PredicateBuilder be improved

texts:
I have this query built using the above, but it feels like it could be improved to make it more concise:

  private IQueryable<Lead> _queryLeadsByHeat(int? ownerUserId, bool warmLeads)
        {
            var predicate = PredicateBuilder.False<Lead>();

            predicate = predicate.Or(x => x.LeadPool.DecreaseByUnit == (int) DecreaseUnitTime.Day
                                           &&
                                           (
                                               (x.LastHeatValue - SqlFunctions.DateDiff("day", !x.LastContactDate.HasValue
                                                                          ? x.InitialContactDate
                                                                          : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                                (x.LastHeatValue - SqlFunctions.DateDiff("day", !x.LastContactDate.HasValue
                                                                          ? x.InitialContactDate
                                                                          : x.LastContactDate.Value, DateTime.Today)*
                                                x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                            )
                                       );

            predicate = predicate.Or(x => x.LeadPool.DecreaseByUnit == (int)DecreaseUnitTime.Week
                                       &&
                                       (
                                           (x.LastHeatValue - SqlFunctions.DateDiff("week", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                            (x.LastHeatValue - SqlFunctions.DateDiff("week", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) *
                                            x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                        )
                                   );

            predicate = predicate.Or(x => x.LeadPool.DecreaseByUnit == (int)DecreaseUnitTime.Month
                                       &&
                                       (
                                           (x.LastHeatValue - SqlFunctions.DateDiff("month", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                            (x.LastHeatValue - SqlFunctions.DateDiff("month", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) *
                                            x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                        )
                                   );

            var query = _activeLeads(ownerUserId)
                        .AsExpandable().Where(predicate);

            return query;
        }

Any ideas on how to improve this?


texts: Generate filter criteria based on multiple field combinations

texts:
The PrepareConditions method in the FeeTypeQueryService class prepares the conditions based on the searchConditions parameter and returns as an object. searchConditions can only have 3 combinations, such as:

Filter by TenantId, FeeTypeId
Filter by TenantId, FeeTypeName
Filter by TenantId, FeeTypeId, FeeTypeName

Note: The TenantId is mandatory for all the filter criterias.

Question: Is there a better way to write the PrepareConditions method so that it doesn't become complicated with a long list of conditional statements? When I start to have more properties in the FeeTypeSearchModel class, this may get dirty - I think.

Sample code:

FeeTypeQueryService.cs

public sealed class FeeTypeQueryService
{
    private object PrepareConditions(FeeTypeSearchModel searchConditions)
    {
        object conditions = null;

        if (searchConditions.FeeTypeId.HasValue && string.IsNullOrEmpty(searchConditions.FeeTypeName))
        {
            conditions = new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value };
            return conditions;
        }

        if (!searchConditions.FeeTypeId.HasValue && !string.IsNullOrEmpty(searchConditions.FeeTypeName))
        {
            conditions = new { TenantId, searchConditions.FeeTypeName };
            return conditions;
        }

        if (searchConditions.FeeTypeId.HasValue && !string.IsNullOrEmpty(searchConditions.FeeTypeName))
        {
            conditions = new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value, searchConditions.FeeTypeName };
            return conditions;
        }

        conditions = new { TenantId };
        return conditions;
    }
}

FeeTypeSearchModel.cs

public sealed class FeeTypeSearchModel
{
    public int? FeeTypeId { get; set; }
    public string FeeTypeName { get; set; }
}


texts: Small DSL: Converting JSON to MSSQL query

texts:
Scenario

Once upon a time, there was this human (ahem, me, ahem) who tried (and succeeded) to build a small program which would convert JSON to a MSSQL query using Python 3.x.

How does it work?

The user makes a POST request with a JSON (in the code, I've used a JSON file) which looks like this:

{
  "endpoint": "rfc",
  "expression": [
    {
      "field": "first_name",
      "operator": "EQ",
      "value": "Dixie"
    },
    "AND",
    [
      {
        "field": "last_name",
        "operator": "NEQ",
        "value": "Smith"
      },
      "OR",
      {
        "field": "middle_name",
        "operator": "EQ",
        "value": "Sam"
      }
    ]
  ],
  "limit": "2"
}

Now, the key point in this story is the expression which is being translated to a query, using recursion, as follows:

def process(data):
    """
    :param data: JSON Object (dict).
    :return: where clause (str) built from data
    """
    where_clause = ""
    if isinstance(data, list):
        for part in data:
            if part not in LOGICAL_OPERATORS:
                where_clause += " ({}) ".format(process(part))
            else:
                where_clause += process(part)
    elif isinstance(data, dict):
        where_clause += " {} {} '{}'".format(data["field"], COMPARISON_OPERATORS[data["operator"]], data["value"])
    elif isinstance(data, str):
        return data
    return where_clause

The entire code, is as follows:

import json

LOGICAL_OPERATORS = ("AND", "OR")

COMPARISON_OPERATORS = {
    "LT": "<",
    "GT": ">",
    "LTE": "<=",
    "GTE": ">=",
    "EQ": "=",
    "NEQ": "!="
}

def get_data(file):
    """
    :param file: JSON file.
    :return: data as a json object (dict).
    """
    with open(file) as data_file:
        return json.load(data_file)

def process(data):
    """
    :param data: JSON Object (dict).
    :return: where clause (str) built from data
    """
    where_clause = ""
    if isinstance(data, list):
        for part in data:
            if part not in LOGICAL_OPERATORS:
                where_clause += " ({}) ".format(process(part))
            else:
                where_clause += process(part)
    elif isinstance(data, dict):
        where_clause += " {} {} '{}'".format(data["field"], COMPARISON_OPERATORS[data["operator"]], data["value"])
    elif isinstance(data, str):
        return data
    return where_clause

def main():
    expression = get_data("other.json")["expression"]
    where_clause = process(expression)

    return "SELECT * FROM table WHERE {}".format(where_clause)

if __name__ == '__main__':
    print(main())

Questions:

Will the recursive function scale good on a larger expression? Now, that expression can go in depth as long as the memory goes. Should I add a limit to it?
Did I miss something? Maybe an edge case?
Is there an already builtin in out there for this?


texts: Hex boardgame with fast random rollouts (OpenAI gym framework)

texts:
I implemented the boardgame Hex using the OpenAI gym framework with the aim of building a bot/AI player that can learn through self-play and expert iteration (details Note: not my paper; I am merely reproducing it).
The initial agent uses Monte-Carlo tree search (MCTS), and I will compare myself against it to evaluate the strength of different bots. MCTS involves simulating the game with random moves (called a rollout) and this is done A LOT (>1,000 games played per move in the actual game), so this rollout speed matters to me. Indeed, when I profile my code, the bottleneck is said rollout, and, more specifically, the test if the game has ended.
Currently, I check if the game is finished using the following mechanism (I'm sure there is a name for it, but I don't know it):

Pad the board with 1 extra row/column and place stones on the west/east side (player white/blue) or north/south side (player black/red) (cached at the start of the game)
Find all the connected regions for the current player (cached from previous turn)
Place stone on board
check neighborhood of stone and (a) start new region if unconnected, (b) add to the region with lowest region index
if multiple regions are in the neighborhood, merge them with the region that has the lowest index

I assign index 1 to the stones in the north/west (black/white) padding, and can then efficiently test if the game is over by checking the south-east corner. If it has region index 1, it is connected to the opposite side and the game has finished.
The full code of the game is available on GitHub together with a MWE that performs a random rollout. It's not a big repo (maybe 500 lines). The critical function is this one
    def flood_fill(self, position):
        regions = self.regions[self.active_player]

        current_position = (position[0] + 1, position[1] + 1)
        low_x = current_position[1] - 1
        high_x = current_position[1] + 2
        low_y = current_position[0] - 1
        high_y = current_position[0] + 2
        neighbourhood = regions[low_y:high_y, low_x:high_x].copy()
        neighbourhood[0, 0] = 0
        neighbourhood[2, 2] = 0
        adjacent_regions = sorted(set(neighbourhood.flatten().tolist()))
        adjacent_regions.pop(0)

        if len(adjacent_regions) == 0:
            regions[tuple(current_position)] = self.region_counter[self.active_player]
            self.region_counter[self.active_player] += 1
        else:
            new_region_label = adjacent_regions.pop(0)
            regions[tuple(current_position)] = new_region_label
            for label in adjacent_regions:
                regions[regions == label] = new_region_label

with the most expensive line being adjacent_regions = sorted(set(neighbourhood.flatten().tolist())). I'm wondering if this can be implemented in a nicer way, either by using a different algorithm or vectorizing the code more, more intelligent caching, ...
Of course, I'm also happy with any other comment on the code.
Disclaimer: I found a basic hex implementation in an old commit in the OpenAI gym repo, which I used as a base to work off. Most of the code has changed, but some of it (e.g., the render function) I did not write myself.


texts: Calculating T-Test within Large Pandas Dataframes

texts:
The below code runs a t-statistic within a large dataframe (rnadf) based on masked values from another dataframe (cnvdf_maked).  Before, I was putting my results into a dictionary and turning it into a pandas dataframe.  These dataframes became too large for my memory, so I had to switch to writing the results to a file line by line, as below on the last line.

The above code takes a little less than a week to produce one complete file.  I have many dataframes to run this on, as in many pairs of the DFs rnadf and cnvdf.  I have 138 pairs of these DFs pickled in a directory, so I was making my script "parallel" by running each DF pair's ttest caluclation at once in its own screen session -- for a total of 138 screen sessions.  This was a clunky way to do it.  When result files get to be around 2.6Gb, they fail with an OS Error 30.

I've since moved to a new server with about 1Tb of memory, so I'm no longer practically constrained by memory.  I'm open to doing two things to improve optimization: 1) make each calculated ttest faster, and 2) parallelize this process to run on many different dataframes at once without using separate screen sessions.

from scipy import stats
import pandas as pd
import numpy as np
import itertools

# sample dataframes
rnadf = pd.DataFrame(np.random.randint(0,100,size=(100, 26)), columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
cnvdf = pd.DataFrame(np.random.randint(0,1000,size=(100, 25)), columns=list('BCDEFGHIJKLMNOPQRSTUVWXY5'))
cnvdf_mask = cnvdf <= 500

inter = list(set(cnvdf_mask.columns).intersection(rnadf.columns))
cnvdf_mask, rnadf = cnvdf_mask[inter], rnadf[inter]

with open('out_tab.txt', 'w') as f:
    for pr in itertools.product(rnadf.index, cnvdf_mask.index):
        rnaPos = np.array(rnadf.loc[pr[0]][cnvdf_mask.loc[pr[1]]].dropna())
        rnaNeg = np.array(rnadf.loc[pr[0]][~cnvdf_mask.loc[pr[1]]].dropna())
        t, p = stats.ttest_ind(rnaPos, rnaNeg)
        f.write('{}\t{}\t{}\n'.format(t, p, pr))  # changed pr table to tuple of str indices joined by '&'


texts: PHP script for getting post data from Tampermonkey script

texts:
I'm trying to shorten this piece of my code into a loop:

<?php header('Access-Control-Allow-Origin: http://mysite.com'); ?>

<?php

    if(sizeof($_POST))
    {
    file_put_contents;
    } else {
    echo "ERROR! Must be activated from Tampermonkey script!";
    exit();
    }

file_put_contents(
"content.html",
" Updated last: " . $_POST['date'] . "

"  .
//Please add more entries depending on how many accounts you have configured

"Account 1
(" . $_POST['accountname1'] . ")" . "
CREDITS
" . $_POST['credits1'] . "
-
" .
"Account 2
(" . $_POST['accountname2'] . ")" . "
CREDITS
" . $_POST['credits2'] . "
-
" .
"Account 3
(" . $_POST['accountname3'] . ")" . "
CREDITS
" . $_POST['credits3'] . "
-
" .
"Account 4
(" . $_POST['accountname4'] . ")" . "
CREDITS
" . $_POST['credits4'] . "
-
" .
"Account 5
(" . $_POST['accountname5'] . ")" . "
CREDITS
" . $_POST['credits5'] . "
-
" .
"Account 6
(" . $_POST['accountname6'] . ")" . "
CREDITS
" . $_POST['credits6']);

?>

Here's the JavaScript code I'm posting with:

function bprs() {

    {
        var rowCount = $('#accountsTable tr').length;
        var accountsCount = rowCount -1;
        var accounts = [];
        for (var n = 1; n <= accountsCount; n++) {
            accounts[n] = {
                name: $('#accountName' + n).text(),
                credits: $('#credits' + n).text()
            };
        }

        var date = new Date();
        var data = "date=" + date +
            accounts.reduce(function (prev, account, n) {
                return prev + "&accountname" + n + "=" + account.name +
                    "&credits" + n + "=" + account.credits;
            }, '');

        $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
            options.async = true;
        });

        $.ajax({
            url: 'http://mysite.com/submit.php', // point to the php file here
            async:false,
            type: "POST",
            dataType: "json",
            data: data,
            success: function (result) {
                JSON.parse(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr);
            }
        });

Here's the post data my browser gives me:

" array(13) { ["date"]=> string(58) "Sun Dec 27 2015 11:28:53 GMT-0700 (Mountain Standard Time)" ["accountname1"]=> string(28) "*****@gmail.com" ["credits1"]=> string(3) "110" ["accountname2"]=> string(33) "*****@gmail.com" ["credits2"]=> string(3) "109" ["accountname3"]=> string(23) "*****@gmail.com" ["credits3"]=> string(3) "536" ["accountname4"]=> string(32) "*****@outlook.com" ["credits4"]=> string(3) "333" ["accountname5"]=> string(19) "*****@gmail.com" ["credits5"]=> string(3) "188" ["accountname6"]=> string(20) "*****@gmail.com" ["credits6"]=> string(2) "72" } "

What this does is post data from a web page to a PHP script on a server, then the script parses the data into an HTML file.

As it stands right now, the script requires me to add a new entry when I create a new account and add it to the page.

What I'd like is for my PHP page to generate the HTML code based on how many entries are in the post data.


texts: HttpClient wrapper for simple calls with optional cert

texts:
Trying to ensure each controller contains it's own httpclient.  The super user can change which endpoint is called from the site and some of those endpoints do not require a certificate, but some require their own certificate.

Want a safe call to this wrapper class (HttpClientProvider) as a static and in a static constructor for reuse. Any gotchas?

Will the httpclient still execute after not being used for a while?

Here is the Controller Call:

    public class HomeController : Controller
{
    private static readonly HttpClientProvider _clientProvider;

    static HomeController()
    {
        _clientProvider = new HttpClientProvider();
    }

    public ActionResult Index()
    {
        var certPath = HostingEnvironment.MapPath("~/App_Data/cert.pfx");
        var httpClient = _clientProvider.GetHttpClient(certPath);

        var result = httpClient.GetAsync("www.example.com").Result;

        return View();
    }
}

Here is the Provider Class:

 public class HttpClientProvider
{
    private HttpClient _client;
    private WebRequestHandler _clientHandler;

    public HttpClient GetHttpClient()
    {
        SetUpHandler();
        SetUpClient();

        return _client;
    }

    public HttpClient GetHttpClient(string certPath, string password = "")
    {
        SetUpHandler();
        SetUpClient();
        SetUpCertificate(certPath, password);

        return _client;
    }

    public HttpClient GetHttpClient(X509Certificate2 x509Cert)
    {
        SetUpHandler();

        _clientHandler.ClientCertificates.Add(x509Cert);

        SetUpClient();

        return _client;
    }

    private void SetUpHandler()
    {
        if (_clientHandler == null)
        {
            _clientHandler = new WebRequestHandler();
        }
        else
        {
            _clientHandler.ClientCertificates.Clear();
        }
    }

    private void SetUpCertificate(string certPath, string password = "")
    {
        if (certPath != null)
        {
            var absolutePath = HostingEnvironment.MapPath(certPath);

            var cert = absolutePath != null
                ? new X509Certificate2(absolutePath, password, X509KeyStorageFlags.MachineKeySet)
                : new X509Certificate2(certPath, password, X509KeyStorageFlags.MachineKeySet);

            _clientHandler.ClientCertificates.Add(cert);
        }
    }

    private void SetUpClient()
    {
        if (_client == null)
        {
            _client = new HttpClient(_clientHandler);
        }
    }
}


texts:
I am used to procedural PHP.  However, I have a piece of code that needs to be repeated a lot.  I was thinking of trying my hand at creating a class.  All is going well and it is working, but I think it can be done better.  Especially the function where I am creating the HTML.  At the moment, I have a variable $html and I keep adding data to it.  It feels clunky and I wanted to know if anyone knows of a better solution.

I have been spending hours on Google trying to find a better way of doing it.  Has anyone got advice or a link to a good tutorial?

Thank you in advance.  Here is the class.

class clerksection {
    var $header;
    var $post;
    var $meta;

    function __construct($post, $meta, $header) {
        $this->post = $post;
        $this->meta = $meta;
        $this->header = $header;
    }

    //PHP magic methods to get values
    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    //PHP magic methods to set values
    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
        return $this;
    }

    function create_html () {
        $repeat_group = get_post_meta( $this->post, $this->meta, true );
        $uid = spl_object_hash($this);
        $html = '
'. $this->header .'
';
        $html .= '
';
        $i = 1;
        foreach( (array) $repeat_group as $key => $value ) :
            $html .= '
';
            $html .= '
';
            if (!empty($value['image'])) :
            $html .= '';
            endif;
            $html .= '
' . $value['title'] . '
';
            $html .= '
' . $value['name'] . '';
            if (!empty($value['notes'])) :
                $html .= '(more)';
            endif;
            $html .= '
'; //.dark_color .clerk_thin
            if (!empty($value['notes'])) :
                $html .= '
' . $value['notes'] .'
';
            endif;
            if (!empty($value['phone'])) :
            $html .= '
 ' . $value['phone'] . '
';
            endif;
            if (!empty($value['email'])) :
            $html .= '
  ' . $value['email'] . '
';
            endif;
            $html .= '
'; //.pd_btm_20
            $html .= '
'; //.col-lg-4 .pd_left_15
            $i++;
        endforeach;
        $html .= '
'; //.row

        return $html;
    }
}


texts: LeetCode 124: Binary Tree Maximum Path Sum

texts:
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:
Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

Inputs
[1,2,3]
[-10,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7999999,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7]

Outputs
6
42
66
791
8001552

Code
#include <cstdint>
#include <algorithm>

struct Solution {
    int maxPathSum(TreeNode* root) {
        std::int_fast64_t sum = INT_FAST64_MIN;
        depthFirstSearch(root, sum);
        return sum;
    }

private:
    static std::int_fast64_t depthFirstSearch(
        const TreeNode* node,
        std::int_fast64_t& sum
    ) {

        if (!node) {
            return 0;
        }

        const std::int_fast64_t left = std::max(
                                           (std::int_fast64_t) 0,
                                           depthFirstSearch(node->left, sum)
                                       );
        const std::int_fast64_t right = std::max(
                                            (std::int_fast64_t) 0,
                                            depthFirstSearch(node->right, sum)
                                        );
        sum = std::max(sum, left + right + node->val);
        return std::max(left, right) + node->val;
    }
};

References

Problem

Discuss

Solution


texts: Getting all public constants from the main and nested classes

texts:
I wrote this recursive function to get all constants from a class and its subclasses. Can it be simplified?

private static IEnumerable<FieldInfo> GetPublicConstants(Type type)
{
    var subtypes = type.GetNestedTypes(BindingFlags.Public);

    foreach (var subtype in subtypes)
    {
        foreach (var constant in GetPublicConstants(subtype))
        {
            yield return constant;
        }
    }

    var publicStaticFields = type.GetFields(BindingFlags.Public |
         BindingFlags.Static | BindingFlags.FlattenHierarchy)
         .Where(fi => fi.IsLiteral && !fi.IsInitOnly);

    foreach (var fieldInfo in publicStaticFields)
    {
        yield return fieldInfo;
    }
}

For example, it would return 6 constants for the following class:

public static class MyClass
{
    public const string AAA = "";

    public static class A
    {
        public const string Aaaaa = "";

        public static class AB
        {
            public const string ABaaa = "";
        }
    }

    public static class B
    {
        public const string Baaa = "";
        public const string Bbbb = "";
    }

    public static class C
    {
        public const string Caaa = "";
    }
}

What I don't like is the fact I'm having 2 loops where I yield return 1 item because of inability to yield return a list of items.


texts: Checking if there are tags or categories in the database

texts:
The code below is used to check if there are tags or categories in the database. If they exist, they are not added to the database, otherwise they are added.

Is this code efficient and easy to read?

private void CreateTagCategoryBlog(string Tags, string category)
    {
        int lastInsertedId = postRepo.GetAll().LastOrDefault().BlogPostId;
        var allTags = tagRepo.GetAll().Where(e => e.Name.Contains(Tags)).ToList().DefaultIfEmpty();
        var allCategories = catRepo.GetAll().Where(e => e.Name.Contains(category)).ToList().DefaultIfEmpty();

        foreach (var x in GetItems<Tag>(Tags, tagRepo))
        {
            blogTag.Add(new BlogTag
            {
                TagId = x.TagID,
                BlogPostId = lastInsertedId,
                DateAdded = DateTime.Now,
                LastModifiedDate = DateTime.Now,
                IsDeleted = false
            });
        }

        foreach (var x in GetItems<Category>(category, catRepo))
        {
            blogCat.Add(new BlogCategory
            {
                BlogPostId = lastInsertedId,
                CategoryId = x.CategoryId,
                DateAdded = DateTime.Now,
                LastModifiedDate = DateTime.Now,
                IsDeleted = false
            });
        }
    }


texts:
Can I use #define fori(i,n) for(int i=0;i<=n;i++) in Java?

And of course, Java doesn't have precompiler so we cannot do that in java. So I thought we can do that fori method either using stream() or manually defining a method. But I thought instead of just traversing why can't I put the third parameter as lambda expression that operates.

Functional interface:

interface func
{
    int calculate(int a,int b);
}

Method implementation:

 int run(int[] array,int start,int end,func t)
 {
   int result =0;
   for(int i=start;i<=end;i++)
   {
     System.out.println(result);
     result = t.calculate(array[i], result);
    }
    return result;
  }

Usage:

public static void main(String[] args)
{
        int[] array = {1,2,3,4,5,3,5,3,2,2,3,2,23,2};
        System.out.println(run(array, 0, 5, (a,b) -> a + b  ));
}

I would like a review on this code pattern. My major concern is that how much complicated lambda expression I can use here. Also, what is the future scope of this what could be done with this pattern?


texts:
I've completed Advent of Code's Day 9 in Python3, trying to use it to teach myself coroutines. I'm very familiar with generators, but I've pretty much never used coroutines before.

I've ended up with something that works (I got the answers correct for both parts of the challenge), but my use of coroutines feels really fragile in some poorly-defined sense, and I was particularly disappointed that I couldn't make a program in which I used yield from; I thought that this was the kind of thing that yield from was built for.

Overall strategy: input an iterable string containing the expression to parse. Hand that iterable to various generators in turn, depending on what is required; those consume the characters they need and then yield their answers before being destroyed.

A group is as defined in the problem: anything contained in {} in the input. score is the "score" of the input (i.e. the number of groups in the tree or in any subtree). garbage_len is the total length of the garbage objects in the tree or any subtree. I'm not really concerned with how to improve those two methods; I'd like feedback on the idiomatic use of generators/coroutines.

class color:
    RED = '\033[91m'
    END = '\033[0m'

class Garbage:
    def __init__(self):
        self.characters = []

    def __str__(self):
        return '{}{}{}'.format(color.RED, ''.join(str(s) for s in self.characters), color.END)

    def add(self, ch):
        self.characters.append(ch)

    def __len__(self):
        return len(self.characters)

    def __bool__(self):
        return True

class States(enum.Enum):
    Group = 0
    Garbage = 1
    Escaped = 2

class Group:
    def __init__(self):
        self.contents = []

    def __str__(self):
        # A group contains a list of {Garbage or Group}.
        return '{' + ','.join(str(s) for s in self.contents) + '}'

    def score(self, depth=0):
        ans = depth + 1
        for g in self.contents:
            if isinstance(g, Group):
                ans += g.score(depth + 1)
        return ans

    def garbage_len(self):
        ans = 0
        for gr in self.contents:
            if isinstance(gr, Group):
                ans += gr.garbage_len()
            else:
                assert isinstance(gr, Garbage)
                ans += len(gr)
        return ans

def curr_garbage(gen):
    # Coroutine which consumes garbage characters and yields characters.
    # Stops when the current garbage is finished.
    state = States.Garbage
    for ch in gen:
        if state == States.Escaped:
            state = States.Garbage
        elif state == States.Garbage:
            if ch == '!':
                state = States.Escaped
            elif ch == '>':
                return
            else:
                yield ch

def curr_group(gen):
    # Coroutine which consumes characters and yields Groups and Garbages.
    for ch in gen:
        if ch == '{':
            # New group.
            subgroup = Group()
            subgroup_gen = curr_group(gen)
            subgroup.contents = list(sub)
            yield subgroup
        elif ch == ',':
            pass
        elif ch == '}':
            # End of current group
            raise StopIteration
        elif ch == '<':
            # New garbage
            garbage = Garbage()
            garbage_gen = curr_garbage(gen)
            for garbage_char in garbage_gen:
                garbage.add(garbage_char)
            yield garbage
        else:
            raise ValueError("Malformed string, received character {}".format(ch))

if __name__ == '__main__':
    gen = curr_group(iter(line))
    tree = next(gen)
    print(tree.score())
    print(tree.garbage_len())


texts:
I have made a merge sort algorithm but am unsure of the 'Space Usage' of the algorithm.

public class Sorting {

    public static void mergeSort(int[] arr) {
        if (arr.length == 1) {
            return;
        }
        int[] newArrLeft = new int[arr.length / 2];
        int[] newArrRight = new int[arr.length - (arr.length / 2)];
        int currentRight = 0;
        for (int i = 0; i < arr.length; i++) {
            if (i < arr.length / 2) {
                newArrLeft[i] = arr[i];
            } else {
                newArrRight[currentRight++] = arr[i];
            }
        }
        mergeSort(newArrLeft);
        mergeSort(newArrRight);
        merge(newArrLeft, newArrRight, arr);

    }

    private static void merge(int[] arrLeft, int[] arrRight,
            int[] sortedValuesArr) {
        int currentLeft = 0;
        int currentRight = 0;
        int currentSorted = 0;
        while (currentLeft < arrLeft.length && currentRight < arrRight.length) {
            if (arrLeft[currentLeft] < arrRight[currentRight]) {
                sortedValuesArr[currentSorted++] = arrLeft[currentLeft++];
            } else {
                sortedValuesArr[currentSorted++] = arrRight[currentRight++];
            }
        }

        while (currentLeft < arrLeft.length) {
            sortedValuesArr[currentSorted++] = arrLeft[currentLeft++];
        }
        while (currentRight < arrRight.length) {
            sortedValuesArr[currentSorted++] = arrRight[currentRight++];
        }

    }
}

I am specifically inquiring about:

int[] newArrLeft = new int[arr.length / 2];
int[] newArrRight = new int[arr.length - (arr.length / 2)];
int currentRight = 0;
for (int i = 0; i < arr.length; i++) {
    if (i < arr.length / 2) {
        newArrLeft[i] = arr[i];
    } else {
        newArrRight[currentRight++] = arr[i];
    }
}

Is the above code wasting space? Is there a better implementation?


texts: Finding the minimum number of swaps to sort a list

texts:
I can handle large numbers with this code as well but I need to improve my execution time.

def no_swap(a):
  sorted_a=sorted(a)
  rev_a=list(reversed(a))
  b=a[:]
  n=len(a)
  noswap1=0
  noswap2=0
  for i in range(n):
    if a[i]!=sorted_a[i]:
      noswap1=noswap1+1
      j=binarySearch(sorted_a[i],a)
      a=swaplist(i,j,a)

    if rev_a[i]!=sorted_a[i]:
      noswap2=noswap2+1
      j=binarySearch(sorted_a[i],rev_a)
      b=swaplist(i,j,rev_a)

  return min(noswap1,noswap2)

def swaplist(i,j,arr):
  temp=arr[i]
  arr[i]=arr[j]
  arr[j]=temp
  return arr

def binarySearch(item, alist):
  first = 0
  last = len(alist)-1
  found = False
  while first<=last and not found:
    midpoint = (first + last)
    if alist[midpoint] == item:
      found = True
    else:
      if item < alist[midpoint]:
       last = midpoint-1
      else:
        first = midpoint+1

  return midpoint

Any suggestions are appreciated!


texts: Bring phone numbers in consistent format

texts:
I'm using this code to bring my phone numbers in a consistent format.

Desired: +(country code)phone number

Possible patterns:

01721234567 -> change to desired pattern
00491234567 -> change to desired pattern
+4912345678 -> do nothing, already desired pattern

This is what I use:
String number = allContactNumbers.get(i).get(j);
number = number.replaceAll("[^+0-9]", ""); // All weird characters such as /, -, ...

String country_code = getResources().getString(R.string.countrycode_de);

if (number.substring(0, 1).compareTo("0") == 0 && number.substring(1, 2).compareTo("0") != 0) {
    number = "+" + country_code + number.substring(1); // e.g. 0172 12 34 567 -> + (country_code) 172 12 34 567
}

number = number.replaceAll("^[0]{1,4}", "+"); // e.g. 004912345678 -> +4912345678

For some reason I'm not happy with it though. I hope there is somebody to tell me, whether my code is written properly!


texts:
A triangular number is a product of three factors as follows:

$$
\text{Triangular number} = x(x + 1)(x + 2)
$$

Is there a way to make this code faster? As it is the code calculates every triangular number less than or equal to the integer given by the user.

#include <stdio.h>

int main(void) {

    int firstFactor = 0;
    int secondFactor = 1;
    int thirdFactor = 2;

    int userInput;
    int product = 0;

    printf("Enter a integer: ");
    scanf("%d", &userInput);

    if(userInput == 0) {
        printf("User input is a triangular number\n");
        return 0;
    }

    do {
        firstFactor++;
        secondFactor++;
        thirdFactor++;
        product = firstFactor * secondFactor * thirdFactor;
    } while(product < userInput);

    if(product == userInput) {
        printf("User input is a triangular number\n");
    } else {
        printf("User input is not a triangular number\n");
    }
    return 0;
}


texts:
This is my code for this question on hackerrank.
The idea is to find the amount of substrings of a given word that are anagrams of each other.

The code works fine, but it times out with longer strings. I've downloaded the test cases to make sure the result is correct and it is, it just takes too long.
I can do this in C and pass all tests, but I was wondering if there is a faster alternative in Perl.

I also tried using numbers, i.e. multiplying the ord()-97 of the characters in the two substrings, and then doing a single check on the number, to see if they are anagrams of each other.
That is much faster, but only works on small strings because it overflows quickly.

In this specific case, I'm not really that concerned about style, as much as performance. How can this be improved?

use strict;
use warnings;

use Data::Dumper;

sub get_all_substr {
    my ($input_string) = @_;

    my @results;
    push @results, $input_string =~ /(?=(.{$_}))/g for 1 .. length($input_string);

    return \@results;
}

sub is_anagram {
    my ($string_a, $string_b) = @_;

    my $len_a = length($string_a);

    return 0 if (length($string_b) != $len_a);

    my %vec_a;
    my %vec_b;

    foreach my $i (0..$len_a-1) {
        $vec_a{substr($string_a, $i, 1)}++;
        $vec_b{substr($string_b, $i, 1)}++;
    }

    return 0 if (scalar(keys(%vec_a)) != scalar(keys(%vec_b)));

    foreach my $key (keys(%vec_a)) {
        if (!defined($vec_b{$key}) || ($vec_a{$key} != $vec_b{$key})) {
            return 0;
        }
    }

    return 1;
}

my @results;

my $t = <STDIN>;
chomp $t;

while($t--) {
    my $input_string = <STDIN>;
    chomp $input_string;

    my $count = 0;
    my $strings;
    $strings = get_all_substr($input_string);

    my $max_size = scalar(@{$strings})-1;
    foreach my $i (0..$max_size) {
        foreach my $k ($i+1..$max_size) {
            if (is_anagram($strings->[$k], $strings->[$i])) {
                $count++;
            }
        }
    }
    push @results, $count;
}

print join("\n", @results);


texts:
I've written some class which allows me to derive from it to make objects lazy-instantiated. Do you see notational improvements or maybe even cases where this method might not work (multiple inheritance etc.)? What else could I try?

class LazyProxy(object):
    def __init__(self, cls, *params, **kwargs):
        self.__dict__["_cls"]=cls
        self.__dict__["_params"]=params
        self.__dict__["_kwargs"]=kwargs

        self.__dict__["_obj"]=None

    def __getattr__(self, name):
        if self.__dict__["_obj"] is None:
            self.__init_obj()

        return getattr(self.__dict__["_obj"], name)

    def __setattr__(self, name, value):
        if self.__dict__["_obj"] is None:
            self.__init_obj()

        setattr(self.__dict__["_obj"], name, value)

    def __init_obj(self):
        self.__dict__["_obj"]=object.__new__(self.__dict__["_cls"], *self.__dict__["_params"], **self.__dict__["_kwargs"])
        self.__dict__["_obj"].__init__(*self.__dict__["_params"], **self.__dict__["_kwargs"])

class LazyInit(object):
    def __new__(cls, *params, **kwargs):
        return LazyProxy(cls, *params, **kwargs)

class A(LazyInit): # classes meant to be lazy loaded are derived from LazyInit
    def __init__(self, x):
        print("Init A")
        self.x=14+x

a=A(1)
print("Go")
print("15=", a.x)


texts: Building equal number of records list object

texts:
I am trying to get equal number of records in both columns, even if that means that first column doesn't fill page to bottom on the second page. The only way I was able to do this was by using a maxrow count and breaking when it is equal to the max row count.

 public List<DataForExcelExport> GetData()
        {

            var list = new List<DataForExcelExport>();
            int ROWS_PER_PAGE = 41;
            int MaxRow = 0;

            SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommandText, connectionString);
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            bool flgLastPage = false;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                DataRow dr = dataTable.Rows[i];
                var item = new DataForExcelExport();
                SetItemData(dr, item, true);
                if (i + ROWS_PER_PAGE < dataTable.Rows.Count)
                {
                    SetItemData(dataTable.Rows[i + ROWS_PER_PAGE], item, false);
                }
                list.Add(item);
                if (flgLastPage == false)
                {
                    if ((i + 1) % ROWS_PER_PAGE == 0)
                    {
                        i += ROWS_PER_PAGE;

                        int remaining = dataTable.Rows.Count - (i + 1);
                        if (remaining < 2 * ROWS_PER_PAGE)
                        {
                            ROWS_PER_PAGE = remaining / 2 + remaining % 2;
                            flgLastPage = true;

                        }
                    }
                }
                int maxrow = i + ROWS_PER_PAGE;
                if (maxrow == dataTable.Rows.Count)
                {
                    break;

                }
            }
            return list;

        }

expected output: when there are a total of 118 rows

- page 1
_________
  1 | 41
... |...
 38 | 78
 39 | 79
 40 | 80
_________

- page 2
_________
 81 | 99
 82 | 100
... | ...
98  |118
_________


texts: Creating a styled component inside a component function

texts:
In one of my React components, I want to use props when creating a styled-component to determine which tag to use. Specifically I am looking for what's in props.headingLevel to decide which heading level to create. E.g. h1 or h2.

All of the styled-components examples show components being created outside of the React component class or function, however I have only got this working by creating the styled-component inside the function when props is available. I know you can use props inside of the styled-component via the props passed to the styled-component itself within the React function but at this point it's too late.

So my question is twofold. Is it acceptable to create styled-components inside React components functions? And, is there a better way to manage dynamic tags, e.g. creating a styled-component tag based on context or props passed?

Here is my component:

// Modules
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';

// Data
import styleData from '../../../data/styles';

const SupplementaryTitle = styled.span`
    display: block;
    text-align: right;
`

const Title = (props) => {
    const HeadingLevel = props.headingLevel ? props.headingLevel : 'h2';
    const StyledHeading = styled(HeadingLevel)`
        margin: 0;
        font-weight: ${styleData['typography_settings']['title'][props.typographySize]['weight']};
        font-size: ${styleData['typography_settings']['title'][props.typographySize]['size']};
        font-family: ${styleData['typography_settings']['title'][props.typographySize]['font']};
        line-height: ${styleData['typography_settings']['title'][props.typographySize]['line_height']};
    `

    const hasSupplementaryTitle = props.supplementaryTitle;

    if (hasSupplementaryTitle) {
        return (
            <StyledHeading>
                {props.children}
                <SupplementaryTitle>{props.supplementaryTitle}</SupplementaryTitle>
            </StyledHeading>
        )
    }

    return (
        <StyledHeading>{props.children}</StyledHeading>
    )
}

Title.propTypes = {
    children: PropTypes.string.isRequired,
    headingLevel: PropTypes.string,
    typographySize: PropTypes.oneOf([
        'small', 'medium', 'large'
    ]).isRequired,
    supplementaryTitle: PropTypes.string,
}

export default Title;


texts:
I've implemented atoi function as described in leetcode problem string-to-integer-atoi.

I am looking for some feedback on writing this in a more scala native way and being able to include the requirement that:

  If the numerical value is out of the range of representable values,
  INT_MAX (231 − 1) or INT_MIN (−231) is returned.

  object Solution {
    def myAtoi(str: String): Int = {

      val charMap = Map('1'->1, '2'->2, '3'->3, '4'->4, '5'->5, '6'->6, '7'->7, '8'->8, '9'->9, '0'-> 0)

      val keySet = charMap.keySet
      var num = 0
      var firstChar = -1
      var negFlag = false
      var zeroFlag = false

      var cleanStr = str.reverse.dropWhile(c => !charMap.contains(c) || c == '-' || c == ' ').trim

      for((c, i) <- cleanStr.view.zipWithIndex) {
        var summand = c match {
          case c if keySet.contains(c) => {
            if(firstChar == -1) firstChar = i
            charMap(c) * math.pow(10, i - firstChar).toInt
          }
          case '-' if(firstChar != -1) =>  {
            negFlag = true
            0
          }
          case _ => {
            zeroFlag = true
            0
          }
        }
        num += summand
      }
      if(zeroFlag) 0 else if(negFlag) num * -1 else num
    }
  }


texts: ByteBuffer Performance with Java NIO2 AsynchronousChannelGroup.withFixedThreadPool

texts:
I have a socket which will be receiving more than 100 TPS, so I need the reading to be as fast as possible. In this socket, I read the info I need to build a String and check if it matches a regex. I need to read char by char, so I can know where a new message is sent.

But I'm having performance issues. I'm testing it with JMeter and after some time the throughput starts going down. So far, this is the best way I've found to read the elements and classify them (char by char), because the only way I know when a message new message starts/ends is the NULL.

Here is my code:

//Keep reading info from the socket
while (running) {
    try {
        Future<Integer> readFuture = getWorker().read(buffer);
        Integer option = readFuture.get();
        if (option > 0) {
            buffer.flip();
            //Read all the info from the buffer
            while (buffer.hasRemaining()) {
                char buf = (char) buffer.get();
                if (buf == '/') {
                    continue;
                }
                //If the info has one of those char, it's a new message, so I have to manage and keep reading
                if (buf == '\0' || buf == ' ') {
                    trace=sendMessage(trace);
                } else {
                    trace.append(buf);
                }
            }
            buffer.clear();
        } else {
            trace=sendMessage(trace);
            running = false;
            close();
        }
    } catch (Exception e) {
        //Error management
    }
}


texts:
At this point, the user will probably want to know if this system is Long Mode capable, which is indicated by the word CPUID in green. This is determined by attempting to toggle bit 21 in EFLAGS.

5BD  C6460004          mov      [bp], RED       Assume CPUID incapable
5C1  55                push     bp
5C2  89E5              mov      bp, sp
5C4  669C              pushfd                   Preserve original state
5C6  669C              pushfd
5C8  804EFA20          or       [bp-6], 20H
5CC  669D              popfd                    Set flag
5CE  669C              pushfd                   Re-read it
5D0  58                pop      ax
5D1  58                pop      ax              AX = High order bits
5D2  669D              popfd                    Restore original flags
5D4  5D                pop      bp
5D5  0FBAE005          bt       ax, 5           Is bit 21 on
5D9  7328              jnc      603             No if CY=0

Now we'll test if CPU has Extended Function support.

5DB  C6460006          mov      [bp], BROWN
5DF  66B801000080      mov      eax, 0x80000000 Ext Func supported?
5E5  6650              push     eax
5E7  0FA2              cpuid
5E9  6659              pop      ecx
5EB  6639C8            cmp      eax, ecx
5EE  7613              jna      603         AX >= 80000001H

5F0  C646000E          mov      [bp], YELLOW
5F4  B001              mov      al, 1       AX = Read feature bits
5F6  0FA2              cpuid
5F8  660FBAE21D        bt       edx, 29     Long Mode?
5FD  7304              jnc      603

5FF  C6460002          mov      [bp], GREEN

Display CPUID with selected color

603  31C9              xor      cx, cx
605  89CB              mov      bx, cx
607  8A5E00            mov      bl, [bp]        Selected color
60A  BA0706            mov      dx, 607H        Line 7 column 8
60D  E818FF            call     528

Finally, determine state of A20 line and for now only because it works, Fast A20 Gate has been implemented.

610  56                push     si
611  1E                push     ds
612  06                push     es
613  C6460002          mov      [bp], GREEN
617  B90080            mov      cx, 8000H      Retry count

This sets up DS:SI =    560H    Is volatile as not needed anymore
             ES:DI = 100560H

61A  8CCE              mov       si, cs
61C  C1E604            shl       si, 4
61F  81C66000          add       si, 60H       Offset from CS
623  89F7              mov       di, si
625  83C710            add       di, 16
628  31C0              xor       ax, ax
62A  8ED8              mov       ds, ax
62C  48                dec       ax
62D  8EC0              mov       es, ax
62F  57                push      di
630  56                push      si
631  AD                lodsw
632  F7D8              neg       ax
634  AB                stosw
635  3944FE            cmp       [si-2], ax   If equal A20 is off
638  5E                pop       si
639  5F                pop       di
63A  0F858E00          jnz       6cc          Bounce A20 already on

Do Fast A20

63E  C646000E          mov       [bp], YELLOW
642  E492              in        al, 92H
644  0C02              or        al, 2
646  E692              out       92H, al
648  49                dec       cx
649  75E4              jnz       62f        Execute test again

NOTE: There is 125 bytes reserved here for additional methods of
      enabling A20.

6C8  C6460004          mov       [bp], RED   A20 enabling failed

Display "A20" in one of the three colors

6CC  07                pop       es
6CD  1F                pop       ds
6CE  5E                pop       si
6CF  8A5E00            mov       bl, [bp]
6D2  31C9              xor       cx, cx
6D4  B21C              mov       dl, 0x1c
6D6  E84FFE            call      528
6D9  EB25              jmp      700

From here to end of sector is where I2H (6DB) lives and can be viewed at the bottom of this post


texts:
I was doing the following exercise:

Create an algorithm which asks the user a number from 1 to 7, and each number represents a day on the week. For example, 1 represents Sunday, 2 represents Monday and so on. The user will type this number and the program will show them the name of the day on the week and if it's a business day or a weekend.

I tried to do it in a object-oriented way and using Python. Can someone please verify if my code is within the Python and object-oriented "standards"? Because I'm not sure whether it is, and I need a review.
Here's my code:
class DayOnWeek:
    ERROR_MESSAGE = 'Invalid weekday. Try again:'
    NUMBER_NAME_ASSOCIATIONS = {
        1: 'Sunday',
        2: 'Monday',
        3: 'Tuesday',
        4: 'Wednesday',
        5: 'Thursday',
        6: 'Friday',
        7: 'Saturday'
    }

    def __init__(self):
        self._day_number = 0
        self._day_name = None
        self._category = None

    @property
    def day_name(self):
        return self._day_name

    @property
    def category(self):
        return self._category

    @property
    def day_number(self):
        return self._day_number

    @day_number.setter
    def day_number(self, value):
        if 1 <= value <= 7:
            self._day_number = value
            self._day_name = DayOnWeek.NUMBER_NAME_ASSOCIATIONS[self._day_number]
        else:
            raise ValueError(DayOnWeek.ERROR_MESSAGE)

        if 2 <= value <= 6:
            self._category = 'Business day'
        else:
            self._category = 'Weekend'

class DayOnWeekInterface:

    def __init__(self):
        self._day_on_week = DayOnWeek()

    def request_day_number(self):
        while True:
            try:
                day_num = input('Type the number of the day on the week (ex: 1 - Sunday):')
                day_num = int(day_num)
                self._day_on_week.day_number = day_num
                break
            except ValueError:
                print(DayOnWeek.ERROR_MESSAGE)
        self.show_day_on_week()

    def show_day_on_week(self):
        day_num = self._day_on_week.day_number
        day_name = self._day_on_week.day_name
        day_category = self._day_on_week.category
        print(f'The day {day_num} is {day_name.lower()}')
        print(f'{day_name} is a {day_category.lower()}')

DayOnWeekInterface().request_day_number()


texts: Multiplayer Peer-To-Peer position interpolation

texts:
I have coded this movement interpolation for Unity3d using Photon.

OnPhotonSerializeView gets called at the tickrate.

Any kind of criticism/improvement suggestions are welcome. I tried to make the code as plain as possible because I don't see this as something that should be over-engineered because it is rather algorithmic in nature.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerInterpolation : MonoBehaviour {
    Queue<Vector3> positions = new Queue<Vector3>();
    Queue<Quaternion> rotations = new Queue<Quaternion>();
    Queue<int> frameNumbers = new Queue<int>();
    static int amountBuffered = 1;
    static float oneTickTime = 1.0f / Settings.tickRate;

    PhotonView photonView;
    int localSentFrameNumber = 0;
    int lastReceivedFrameNumber = -1;
    int lastFrameNumberMovedTowards = 0;

    int expectedExecuteFrameNumber = 0; //An estimation of what frame number should be executing at this time.
    float expectedExecuteFrameNumberLastExecutedTime = 0;

    Vector3 moveTowards;
    float moveTowardsSpeed = 1.0f;
    bool moveInProgress = false;

    void Start() {
        photonView = gameObject.GetComponent<PhotonView>();
        moveTowards = transform.position;
    }

    void Update() {
        if (photonView.isMine) return;

        transform.position = Vector3.MoveTowards(transform.position, moveTowards, moveTowardsSpeed * Time.deltaTime);
        if (Mathf.Abs(Vector3.Distance(transform.position, moveTowards)) < 0.001f) {
            moveInProgress = false;
        } else {
            moveInProgress = true;
        }

        if (expectedExecuteFrameNumberLastExecutedTime + oneTickTime < Time.realtimeSinceStartup) {
            expectedExecuteFrameNumber++;
            expectedExecuteFrameNumberLastExecutedTime = Time.realtimeSinceStartup;
        }

        if (frameNumbers.Count > 0 && ((frameNumbers.Peek() + amountBuffered <= lastReceivedFrameNumber) || frameNumbers.Peek() <= expectedExecuteFrameNumber - amountBuffered)) {
            if (lastReceivedFrameNumber - frameNumbers.Peek() > amountBuffered) {
                int trimUntil = lastReceivedFrameNumber - amountBuffered;
                while (frameNumbers.Peek() < trimUntil) {
                    positions.Dequeue();
                    rotations.Dequeue();
                    frameNumbers.Dequeue();
                }
            }

            Vector3 position = positions.Dequeue();
            Quaternion rotation = rotations.Dequeue();
            int frameNumber = frameNumbers.Dequeue();

            if (moveInProgress == true) {
                transform.position = moveTowards;
            }

            float distance = Vector3.Distance(transform.position, position);
            moveTowards = position;
            moveTowardsSpeed = distance * (frameNumber - lastFrameNumberMovedTowards) / oneTickTime;

            lastFrameNumberMovedTowards = frameNumber;

            expectedExecuteFrameNumber = frameNumber;
            expectedExecuteFrameNumberLastExecutedTime = Time.realtimeSinceStartup;
        }
    }

    void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) {
        if (stream.isWriting) {
            stream.SendNext(transform.position);
            stream.SendNext(transform.rotation);
            stream.SendNext(localSentFrameNumber++);
        } else {
            positions.Enqueue((Vector3)stream.ReceiveNext());
            rotations.Enqueue((Quaternion)stream.ReceiveNext());
            int frameNumber = (int)stream.ReceiveNext();
            frameNumbers.Enqueue(frameNumber);
            lastReceivedFrameNumber = frameNumber;
        }
    }
}


texts: Finding the second largest element of large input sets

texts:
I have a problem where I need to find the second maximum element of the user inputs. It's an online practice problem and I can't figure out why the server responds back with a Non-Zero Exit Code error when I submit my code. The  program produces right outputs every single time when tested locally. Can someone tell me which part of my code is prone to such errors and how I can deal with this error?

Sample Input:                 Sample Output:

2                             7
1 3 5 7 8 -1                  16
12 23 16 0 2 -1

The first input is the number of test cases. Second and third inputs are the actual user inputs respectively. And user inputs are always terminated with -1.

Here is my code:

class SecondLargest {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int testcase=Integer.parseInt(sc.nextLine());

        while(testcase-->0){
            ArrayList<Long> al=new ArrayList<>();
            long num=0;
            long i=0;
            while((num=(sc.nextLong()))!=-1){
                al.add(num);
                i++;
            }
            Collections.sort(al);
            if(al.size()==0){
                System.err.println("");
            }
            else if(al.size()==1){
                System.out.println(al.get(0));
            }
            else if(al.size()>1){
            System.out.println(al.get((int)(al.size()-2)));
            }
        }
    }
}

Large input sets will be used to test the program.


texts:
I have started learning Java recently and was looking into some easy algorithms.
I found the Boyer Moore voting algorithm here.

I am trying to get better at writing good code for my solutions. Please give me your suggestions.

import java.util.Scanner;

public class MajorityVoteAlgorithm {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        int size = keyboard.nextInt(); // define size of array
        int[] array = new int[size];

        // initialize array
        for (int i = 0; i < array.length; i++) {
            array[i] = keyboard.nextInt();
        }

        majorityelement(array);

    }

    private static void majorityelement(int[] array) {
        int count = 0;
        int candidate = 0;
        for (int i = 0; i < array.length; i++) {
            if (count == 0) {
                candidate = array[i];
                // set the count as 1
                count = 1;
                continue;
            } else if (candidate == array[i])
                count++;
            else {
                count--;
            }
        }

        if (count == 0) {
            System.out.println("No majority element found");

        } else {
            // set the count to zero to count the occurrence of the candidate
            count = 0;
            for (int i = 0; i < array.length; i++) {
                if (candidate == array[i])
                    count++;
            }

            if (count > array.length / 2)
                System.out.println("Majority element is " + candidate);
            else
                System.out.println("No majority element found");
        }

    }
}


texts: Swift permutations of the digits of an Integer

texts:
I want to return all of the permutations of an integer in Swift.

var outputArray = [[Int]]()
func perms ( _ input: [Int], _ output: [Int]) {
    if input.count == 0 {
        outputArray.append( [ Int( output.map{  String($0) }.joined() )! ] )
    }
    else {
        for i in 0..<input.count {
            let current = [input[i]]
            let before = Array( input [0..<i] )
            let after = Array( input [(i + 1) ..< input.count] )
            perms(before + after, current + output)
        }
    }
}

func permsOfInteger(_ input: Int) -> [[Int]] {
    var inp = input
    var inpArray = [Int]()
    while inp > 0 {
        inpArray.append(inp % 10)
        inp = inp / 10
    }
    perms(inpArray, [])
    return (outputArray)
}

( permsOfInteger(5432) )

I don't want to switch the algorithm (I'm aware of Heap's algorithm) but rather improve my implementation here. Any advice?


texts: Pattern for writing a generic string transformation function

texts:
I often need to write string processing functions that take an input string and transform that into some output string. I'm looking for a pattern to make such functions as generic as possible (with reasonable effort).

Requirements

It should be possible to supply the input as a range (like std::string or std::string_view), pair of iterators, null-terminated character arrays and pointers.
Character type should not be restricted to char, but also support wchar_t. Support char16_t and char32_t only if it doesn't require additional effort as I currently have no use for them.
Easy to use for the simple case where input and output is a std::basic_string.
Easy to write and more importantly easy to read.
Performance is less important. Processing character-by-character is good enough.

I currently approach this by splitting the interface into two template functions. The first one is the idiomatic generic interface which is iterator based, the second one is range based for convenience. The convenience interface is allowed to trade some generalism for ease-of-use.

Example

Escape all occurences of the characters '\n', '\t' and '\\' in the input string.

First the idiomatic interface.

template< class InputIt, class OutputIt >
OutputIt EscapeString( InputIt first, InputIt last, OutputIt out )
{
    while( first != last )
    {
        auto c = *first++;
        switch( c )
        {
            case '\n':
                *out++ = '\\';
                *out++ = 'n';
                break;
            case '\t':
                *out++ = '\\';
                *out++ = 't';
                break;
            case '\\':
                *out++ = '\\';
                *out++ = '\\';
                break;
            default:
                *out++ = c;
        }
    }
    return out;
}

Now the convenience wrapper. InputString can be any string range (like std::string), null-terminated char array or pointer to null-terminated string.
The result will be std::basic_string<character_type_of_InputString> by default, but can be changed to any class that has a push_back() member.

template< typename InputString,
          class ResultString = typename as_literal_traits<InputString>::std_string_type >
ResultString EscapeStringCopy( const InputString& input )
{
    // Allow both the ADL-selected overloads for user-defined types and the standard
    // library function templates to appear in the same overload set.
    using std::begin; using std::end;

    // Handle null-terminated character arrays, character pointers and ranges uniformly.
    auto inputRange = boost::as_literal( input );

    ResultString result;
    EscapeString( begin( inputRange ), end( inputRange ), back_inserter( result ) );
    return result;
}

The template as_literal_traits is an utility that is used to create a default return type of std::basic_string that has the same character type as the input string.

template< typename StringT >
struct as_literal_traits
{
    // NOTE: std::declval<StringT const&>() is used instead of just StringT{}
    // in case StringT is not default-constructible.
    using range_type = decltype( boost::as_literal( std::declval<StringT const&>() ) );
    using value_type = typename boost::range_value< range_type >::type;
    using std_string_type = std::basic_string< value_type >;
};

Live demo at Coliru

Any improvements are welcome.


texts: Determining if a product is taxable or imported

texts:
This should tell me whether the product is taxable or imported. Name should indicate if the product is imported or certain keywords should tell that the product is non-taxable (chocolates, book, pills).

Could you please review the following class products?

class Product
  NON_TAXABLE = [/chocolates/, /book/, /pills/]

  def initialize(product_name)
    @product_name = product_name
  end

  def is_taxable?
    taxable = false
    NON_TAXABLE.each { |x| taxable = x.match(@product_name) if taxable }
    !taxable
  end

  def is_imported?
    /imported/.match(@product_name)
  end
end


texts:
I made a string separator below. It's like strtok, but it separates based on entire strings instead of single char delimiters. Any comments/answers on how I could improve the performance or readability would be great. I'm also leaking some memory according to valgrind, but that is only a minor concern for my use case.

It takes two char arrays, a buffer(string?) and a separator. It returns an array of strings containing all of the separated strings. For example, if the buffer is foobar and the separator is foo, it'll return {"bar", NULL}. But if I'm passed foobarfoobarfoobar and the separator is bar, it'll return {"foo", "foo", "foo", NULL}.

Edit: Comments added to clarify intended functionality.

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

char **sepstr(const char *buf, const char *sep){
    int i = 0, j = 0, k = 0, l = 0, stringCount = 0;

    /* If separator > buffer, return NULL */
    while (buf[i]) i++;
    while (sep[j]) j++;
    if (j > i) return NULL;

    char **strings = malloc(0);

    /* While we're not at the end of the buffer */
    while (*(buf+k)){
        /* If the characters match, check to see if it is the separator */
        if (*(buf+k) == *(sep)){
            for (l = 0; l < j; l++){
                /* If it isn't the separator, break */
                if (*(buf+k+l) != *(sep+l)) break;
                /* If it is the separator and the separator isn't the
                    beginning, add buf to buf+k bytes as a string */
                if (l == j-1 && k != 0){
                    strings = realloc(strings, (stringCount+1)*sizeof (char *));
                    strings[stringCount] = malloc(k+1);
                    memcpy(strings[stringCount++], buf, k);
                    buf += (j + k), k = -1;
                /* If it is the separator, but it's the beginning
                    of the string, skip it */
                } else if (l == j-1 && k == 0) {
                    buf += j, k = -1;
                }
            }
        }
        k++;
    }

    /* Add a string for the left over bytes if sep isn't the end */
    if (i != k && *(buf)){
        while (buf[l]) l++;
        strings = realloc(strings, (stringCount+1) * sizeof (char *));
        strings[stringCount] = malloc(l+1);
        memcpy(strings[stringCount++], buf, l);
    }

    /* Append NULL to array of strings */
    strings = realloc(strings, (stringCount+1) * sizeof (char *));
    strings[stringCount] = malloc(sizeof NULL);
    strings[stringCount] = NULL;

    return strings;
}

int main(){
    const char buffer[] = "foobarfoobarfoobar";
    const char separator[] = "bar";
    char **strings = sepstr(buffer, separator);

    while(*strings){
        printf("%s\n", *(strings));
        free(*(strings++));
    }

    free(strings);

    return 0;
}