texts:
We've just finished learning about queues in my data structures class; I want to make sure I really understand it.  I'm still feeling a bit lost on how to optimize the data use of a queue. I've created a little program here:

#include <iostream>

class Queue{
public:
    Queue(int size = 10){
        ptr = new int[size];
        head = counter = 0;
        qSize = size;
    }

    void push(int value){
        if(counter == qSize)
            doubleSize();
        ptr[counter++] = value;
    }

    int pop(){
        if(counter == 0){
            std::cout << "The queue is empty!!! \n";
            return -1;
        }
        if(head >= counter - 1){
            int temp = ptr[head];
            std::cout << "This is the last item in the queue. \n";
            delete[] ptr;
            ptr = new int[qSize];
            head = counter = 0;
            return temp;
        }
        return ptr[head++];
    }
private:
    int *ptr;
    int head;
    int counter;
    int qSize;

    void doubleSize(){
        int prevSize = qSize;
        qSize *= 2;
        int *temp = new int[qSize];

        for(int i = 0; i < prevSize; i++){
            temp[i] = ptr[i];
        }
        delete[] ptr;
        ptr = temp;
    }
};

So, as you can test, the program runs fine; but what I'm looking for is how I can optimize my queues to be as efficient as possible. I.E. Is there a specific way that I should be programming these queues that uses the minimum amount of data, and has the smallest Order complexity?

P.S. I am aware that there is a queue library. I am more seeking to optimize how I program out queues themselves.


texts:
I have tried to write a test-spy myself. Just for getting more familar with the topic.

Here's the code:

// --------- SPY - Start -----------------------------------
class Spy {
  constructor(func) {
    this.func = func;
    this.returnValue = null;
    this.result = null;
    this.countFuncCalled = 0;
  }

  invoke(...givenArgs) {
    this.receivedArgs = givenArgs;
    this.returnValue = this.func(...givenArgs);
    this.countFuncCalled++;
  }
}
// --------- SPY - End ------------------------------------

const calc = {
  add: (a, b) => {
    return a + b;
  },
  sub: (a, b) => {
    return a - b;
  }
}

const addSpy = new Spy(calc.sub);

addSpy.invoke(9, 4);
console.log(`Used arguments: ${addSpy.receivedArgs.join(", ")}`);
console.log(`Return value: ${addSpy.returnValue}`);
console.log(`Count of function-calls: ${addSpy.countFuncCalled}`);

addSpy.invoke(8, 7);
console.log(`Used arguments: ${addSpy.receivedArgs.join(", ")}`);
console.log(`Return value: ${addSpy.returnValue}`);
console.log(`Count of function-calls: ${addSpy.countFuncCalled}`);

What do you think about my implementation? Is is done in a basically correct way?

I'm I using the ES6-features (Classes, Rest, Spread) right?

What would you have done differently and why?

Looking forward to reading your comments and answers.


texts: Method that receives a hexadecimal string and returns a formatted matrix of those values

texts:
This method is part of a larger project and comes after encoding ascii characters into hexadecimal values, so it assumes the parameter is always a valid hex string.

public static String toMatrix(String hex) {

    StringBuilder builder = new StringBuilder();
    int rows = 0;
    int columns = 16;
    int row = 0;
    int column = 0;

    rows = ( hex.length() / 32 ) + ( hex.length() % 32 );

    for (row = 0; row < rows; row++) {

        for (column = 0; column < columns; column++) {

            if (hex.length() > 0) {

                builder.append(hex.substring(0,2));
                hex = hex.substring(2,hex.length());

                if ((column + 1) % 4 == 0) {

                    builder.append("  ");
                }else {

                    builder.append(" ");
                }
            }
        }

        builder.append("\n");
        column = 0;
    }

    return builder.toString().trim();
}

Input:

1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D

Output:

1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C
1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C
1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D
1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D

In which way can this method be better?


texts: Algorithm to get an arbitrary perpendicular vector

texts:
Is there a more efficient/direct way to find an arbitrary perpendicular vector of another vector?

def perpendicular_vector(v):
    r""" Finds an arbitrary perpendicular vector to *v*. """

    a, b = random.random(), random.random()
    if not iszero(v.z):
        x, y, z = v.x, v.y, v.z
    elif not iszero(v.y):
        x, y, z = v.x, v.z, v.y
    elif not iszero(v.x):
        x, y, z = v.y, v.z, v.x
    else:
        raise ValueError('zero-vector')

    c = (- x * a - y * b) / z

    if not iszero(v.z):
        return Vector(a, b, c)
    elif not iszero(v.y):
        return Vector(a, c, b)
    elif not iszero(v.x):
        return Vector(b, c, a)


texts:
This class is actually a wrapper around HttpWebRequest to issue a POST request with some payloads:

public class SendMessageService
{
    public async Task Send()
    {
        var request = WebRequest.Create("url") as HttpWebRequest;

        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        request.Headers["authorization"] = "token";

        byte[] byteArray = Encoding.UTF8.GetBytes("{"
                                                + "\"app_id\": \"appId\","
                                                + "\"extra_parameter\": \"value\"}");

        string responseContent = null;

        try
        {
            using (var writer = await request.GetRequestStreamAsync())
            {
                writer.Write(byteArray, 0, byteArray.Length);
            }

            using (var response = await request.GetResponseAsync() as HttpWebResponse)
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    responseContent = await reader.ReadToEndAsync();
                }
            }
        }
        catch (WebException ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
            System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
        }

        System.Diagnostics.Debug.WriteLine(responseContent);
    }
}

this class is going to be used in a web environment (ASP.NET Core app) so I registered this service as transient (created each time it is requested):

services.AddTransient<SendMessageService, SendMessageService>();

I would appreciate any improvement suggestions.


texts: IntModulus long addition and subtraction

texts:
One of the remarks in this answer to my question concerning IntModulus says

  What's more problematic is that you don't have matching argument symmetry for add and subtract. You should have long versions of those.

and the reason for this part missing is that I hoped to get something faster than the trivial

public int add(long x, long y) {
    return mod(mod(x) + mod(y));
}

The optimized solution has only one modulus operation (sure, only benchmarking will tell if it was worth it).

Please have a short look at the original question before reviewing. I mean the comments, not the code.

public final class IntModulus {
    ///////// Irrelevant code removed, see the original question if you miss anything.

    ///////// New code below.

    /** Return a non-negative value less than modulus and congruent to the exact sum. */
    public int add(long x, long y) {
        final long sum = x + y;
        // The addition overflowed iff both operands have the same sign are the result's sign differs.
        final boolean overflow = (x^y) >= 0 & (x^sum) < 0;
        return overflow ? overflowedMod(sum) : mod(sum);
    }

    /** Return a non-negative value less than modulus and congruent to the exact sum. */
    public int sub(long x, long y) {
        final long diff = x - y;
        // The subtraction overflowed iff the operands have opposing signs and the result's sign differs from the minuend.
        final boolean overflow = (x^y) < 0 & (x^diff) < 0;
        return overflow ? overflowedMod(diff) : mod(diff);
    }

    /**
     * Compute a modulus of the argument under the assumption that it overflowed by exactly {@code 2**64},
     * i.e., it's a result of an overflowing {@code long} addition or subtraction.
     *
     * <p>This means that the sign is surely wrong and that the number would fit into a 65-bit signed integer.
     */
    private int overflowedMod(long x) {
        // The proper value of the argument divided by two and floored (i.e., rounded towards negative infinity).
        // The sign bit got restored by simply flipping it as we know it was wrong.
        final long half = (x >> 1) ^ Long.MIN_VALUE;
        final long lsb = x & 1; // the least significant bit
        long result = 2L * mod(half) + lsb;
        // Now the result lies in the range 0 to 2*modulus+1 (both included), so conditionally reduce it twice.
        if (result>=modulus) result -= modulus;
        if (result>=modulus) result -= modulus;
        return (int) result;
    }

    ///////// Old but relevant code below.

    /** Return a non-negative value less than modulus and congruent to the operand. */
    public int mod(long x) {
        // As modulus is an int, the cast is safe.
        return fixModulus((int) (x % modulus));
    }

    /**
     * Fix the modulus, i.e., make it non-negative.
     * The argument must be between {@code -modulus+1} and  {@code modulus-1}.
     */
    private int fixModulus(int x) {
        return x<0 ? x+modulus : x;
    }

    @Getter private final int modulus;
}

The benchmark results shows that it's much faster than using BigInteger (suffix "bi"). It's assuming that the operands are already available in the needed form (i.e., they don't have to be converted to/from BigInteger).

Subtraction is not shown, as it's obviously as fast as addition. The code for multiplication is given in the old question.


texts:
I have a list of Comment objects comments. Each Comment has several properties, one of which is the date the comment was posted. I've sorted this list by date and there is at least 1 comment per date in a range.

I would like to loop over comments and for every date, create a new list of comments just for that day. However, the way I'm currently doing it feels very inefficient. Is there a more pythonic or efficient way to do this? (I've implemented a daterange(start_date, end_date) generator function according to this answer):

comment_arrays = [] #array of arrays
for d in date_range(date(2015,1,1), date(2016,1,1)):
    day_comments = []
    for c in comments:
        if c.date == d:
            day_comments.append(c)
        else if c.date > d:
            comment_arrays.append(day_comments)


texts: refactor python strategy pattern to use abstract base class

texts:
I came across this strategy pattern implementation
https://github.com/jtortorelli/head-first-design-patterns-python/blob/master/src/python/chapter_1/adventure_game.py
class Character:
    def __init__(self):
        self.weapon_behavior = None

    def set_weapon(self, weapon_behavior):
        self.weapon_behavior = weapon_behavior

    def fight(self):
        self.weapon_behavior.use_weapon()

class Queen(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = KnifeBehavior()

class King(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = BowAndArrowBehavior()

class Troll(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = AxeBehavior()

class Knight(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = SwordBehavior()

class WeaponBehavior:
    def use_weapon(self):
        raise NotImplementedError

class KnifeBehavior(WeaponBehavior):
    def use_weapon(self):
        print("Stabby stab stab")

class BowAndArrowBehavior(WeaponBehavior):
    def use_weapon(self):
        print("Thwing!")

class AxeBehavior(WeaponBehavior):
    def use_weapon(self):
        print("Whack!")

class SwordBehavior(WeaponBehavior):
    def use_weapon(self):
        print("Thrust!")

knight = Knight()
king = King()
queen = Queen()
troll = Troll()
knight.fight()
king.fight()
queen.fight()
troll.fight()

Would it be correct to refactor it the following way, using an ABC?
from abc import ABC, abstractmethod

class Character:
    def __init__(self):
        self.weapon_behavior = None

    def set_weapon(self, weapon_behavior):
        self.weapon_behavior = weapon_behavior

    def fight(self):
        self.weapon_behavior.use_weapon()

class Queen(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = KnifeBehavior()

class King(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = BowAndArrowBehavior()

class Troll(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = AxeBehavior()

class Knight(Character):
    def __init__(self):
        super().__init__()
        self.weapon_behavior = SwordBehavior()

class WeaponBehavior(ABC):
    @abstractmethod
    def use_weapon(self, message):
        print(message)

class KnifeBehavior(WeaponBehavior):

    def use_weapon(self):
        super().use_weapon("Stabby stab stab")

class BowAndArrowBehavior(WeaponBehavior):
    def use_weapon(self):
        super().use_weapon("Thwing!")

class AxeBehavior(WeaponBehavior):
    def use_weapon(self):
        super().use_weapon("Whack!")

class SwordBehavior(WeaponBehavior):
    def use_weapon(self):
        super().use_weapon("Thrust!")

knight = Knight()
king = King()
queen = Queen()
troll = Troll()
knight.fight()
king.fight()
queen.fight()
troll.fight()


texts:
The code's gonna be pretty simple and YES, I do know, what a proper UUID4 implementation is and what are possible approaches to implement RFC 4122.
But somewhere there exists a small piece of software, where possible dependencies should be minified if possible. Because of this and some other reason let's consider the following UUID generator:
#pragma once
#include <random>

static std::string generate_uuid(size_t len) {
  static const char x[] = "0123456789abcdef";

  std::string uuid;
  uuid.reserve(len);

  std::random_device rd;
  std::mt19937 gen(rd());

  std::uniform_int_distribution < > dis(0, sizeof(x) - 2);
  for (size_t i = 0; i < len; i++)
    uuid += x[dis(gen)];

  return uuid;
}

The output of the function is to be used in cases when some unique ID is required for a custom storage. Like "here we put this data, and there is its 16-byte ID", meaning it would be enough if collisions are just "not likely at all, like winning a lottery twice in a row".
As far as modern C++ has improved random utils, it seemed a not-so-bad custom solution, but now I'm not that sure.
What would you say? Thanks in advance


texts:
I'm designing a basic ticketing system using ASP.NET MVC with Entity Framework.

I'm passing a DbSet<TicketModel> into a method as an IQueryable<TicketModel> that adds to a category counter based on a couple columns.

Tickets have four different states and an age. I need to display counters for the total as well as each of these states and counters for those between 60 and 90 days old and those above 90 days old.

As I understand it, operating on IQueryable is more efficient as it actually changes the query sent to the database. Operating on an actual List pulls the entire table then works on it. However, LINQ-to-Entities only works with columns in the database. How can I get around this?

Model:

public class TicketModel
{
    public int Id { get; set; }
    public StatusType Status { get; set; }
    public enum StatusType { Open, Resolved, Responded, Archived };
    public DateTime DateOfCreation { get; set; }
    public bool Is60To90DaysOld
    {
        get
        {
            TimeSpan age = DateTime.Today - DateOfCreation;
            return (age.Days >= 60 && age.Days < 90);
        }
    }
    public bool Is90DaysOld
    {
        get
        {
            TimeSpan age = DateTime.Today - DateOfCreation;
            return (age.Days >= 90);
        }
    }
}

ViewModel:

// Avoid using fully-qualified name for StatusType
using static MyProject.Models.TicketModel;
public class TicketCountersViewModel
{
    // Counters for each type of ticket
    public struct TicketCounts
    {
        public int Total { get; set; }
        public int Open { get; set; }
        public int Responded { get; set; }
        public int Resolved { get; set; }
        public int Archived { get; set; }
        public int Age60To90 { get; set; }
        public int Age90Plus { get; set; }
    }

    public TicketCounts Counters;

    public TicketCountersViewModel(IQueryable<TicketModel> ticketList)
    {
        Counters.Total = ticketList.Count();
        Counters.Open = ticketList.Count(e => e.Status == StatusType.Open);
        Counters.Responded = ticketList.Count(e => e.Status == StatusType.Responded);
        Counters.Resolved = ticketList.Count(e => e.Status == StatusType.Resolved);
        Counters.Archived = ticketList.Count(e => e.Status == StatusType.Archived);
        // Can't use LINQ-to-Entities here -- Is60To90DaysOld and Is90DaysOld aren't columns in database
        List<TicketModel> list = ticketList.ToList();
        Counters.Age60To90 = list.Count(e => e.Is60To90DaysOld);
        Counters.Age90Plus = list.Count(e => e.Is90DaysOld);
    }
}

Controller:

public class TicketsController
{
    private MyDbContext db = new MyDbContext();
    public ActionResult Index()
    {
        return View(new TicketCountersViewModel(db.Tickets));
    }
}


texts: Solve quadratic equation in standard form

texts:
The first code I ever wrote, sorry that the prints are in German.
I tried to do some code improvements myself but well whenever I do I fail.
Hopefully somebody can help me improve my coding skills.

while True:
    print(" ")
    print("ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6")
    import time

    print("Auf ein Neues?")

    U1 = input("input a ")
    I1 = input("input b ")
    O1 = input("input c ")
    if (U1.isalpha() or I1.isalpha() or O1.isalpha()) is False:
        print("doing some math")
        a = float(U1)
        b = float(I1)
        c = float(O1)
        if ((b * b) - (4 * a * c)) > 0:
            q = float(((b * b) - (4 * a * c)) ** (1 / 2))
            x = float(2 * a)
            y = float(-1 * b)
            z = float(q * (-1))
            result1 = str((y + q) / x)
            result2 = str((y + z) / x)

            print("Nullstelle1=" " " + result1 + "")
            print("Nullstelle2=" " " + result2 + "")

            abc = float((-1 * b) / (2 * a))
            Moo = float((4 * a * c) - (b ** 2)) / (4 * a)

            cba = str(abc)
            oom = str(Moo)

            print("Scheitelpunkt: (" + cba + "|" + oom + ")")

            if (a > 0) is True:
                print("Nach oben geöffnete Funktion")
                print("Schnittpunkt mit der Y-Achse ist" " " + O1 + " ")

            else:
                print("Nach unten geöffnete Funktion")
                print("Schnittpunkt mit der Y-Achse ist" " " + O1 + " ")

        else:
            print("sorry, geht nicht da eine negative zahl unter der wurzel sein würde")
            time.sleep(3)
    else:
        print("nur Zahlen bitte")


texts:
I've created this adjacency list, but I don't like the design of the graph. The issue is that there is one pointer in the node to its adjacency list and there is a pointer in an adj_list node to the actual node. I am also using next pointers to traverse the graph in the order in which nodes were added and the list to get the adjacency list of a node.

Any suggestions?

#include <queue>

enum color{
    WHITE,
    GREY,
    BLACK
};

struct adj_list;

struct node{
    int id;
    int weight;
    color visited;
    adj_list* adj;
    node(int n){
        id = n;
        weight = _I32_MAX;
        visited = WHITE;
    }

};

    struct adj_list{
        adj_list* next;  //This next pointer for visiting each node one after another in the order in which the nodes were added to the graph
        adj_list* list;
        node* n;
        adj_list(node& _n){
            n = &(_n);
            next = NULL;
            list = NULL;
        }
    };

node* add_node(int id,std::queue<int> q , node* root)
{
    node* n = new node(id);
    adj_list* adj = new adj_list(*n);
    n->adj = adj;

    if(root == NULL){
      return n;
    }
    std::queue<adj_list*> q1;

    while(1){
        adj_list* iter = root->adj;
        if(q.empty())break;
        int k = q.front();
        q.pop();
        while(iter){
            if(iter->n->id == k){
                q1.push(iter);
                adj_list*  temp = iter->list;
                iter->list = new adj_list(*n);
                iter->list->list = temp;
                break;
            }
            iter = iter->next;
        }
    }

    adj_list* iter = root->adj;
    while(iter->next){
        iter = iter->next;
    }

    iter->next = adj;

    while(!q1.empty()){
        adj_list* temp = q1.front();
        q1.pop();
        adj_list* new_adj = new adj_list(* temp->n);
        adj->list = new_adj;
        adj = new_adj;
    }
    return root;
}

Adding a new node to the graph:

std::queue<int> q;
q.push(4);
q.push(9);

add_node(20,q , &root);

Update:

I have made some changes here to make it more C++, but an issue here I don't like is that driver has to know about the other vertexes to add to their adjacency list. I'm not sure how to get rid of that if we have to create the graph incrementally.

Another is to provide the graph with a matrix, but that just beats the idea behind adjacency matrix.

#include "iostream"
#include "vector"
#include "list"

struct edge{

int destination_vertex;

    edge(int ver){
        destination_vertex = ver;
    }
    };

struct vertex{
    int id;
    std::list<edge>  list;
    vertex(int _id){
        id = _id;
    }
};

class graph
{
private:
    std::vector<vertex*> vertexes;
    int next;

public:
    graph(void){
        next = 0;
    }

    ~graph(void){}

    void add_node(std::vector<int> edges ){

        vertex* v = new vertex(next++);
        vertexes.push_back(v);

        for(unsigned int i=0;i<edges.size();i++){

            vertex* existing_vertex = vertexes[edges[i]];
            existing_vertex->list.push_back(*(new edge (v->id)));

            edge* e = new edge(edges[i]);
            v->list.push_back(*e);
        }
    }

    void print(){
        for(unsigned int i = 0 ; i < vertexes.size();i++){
            vertex* v =  vertexes[i];
            std::cout << v->id <<"->";
            for(std::list<edge>::iterator iter = v->list.begin() ; iter != (v->list).end();iter++)
            {
                std::cout << iter->destination_vertex <<",";
            }
            std::cout << std::endl;
        }
    }
};


texts: Constructing an odd-even mergesort sorting network

texts:
I was searching for a non-recursive odd-even mergesort implementation and found this one:

Sedgewick R.

The resulting sorting network is not an odd-even-merge sort network. When one draws a diagram of the pairs, it can be seen that too many pairs are generated and others are missed.

So here is an image of a correct network with 32 inputs. A vertical line between 2 horizontal lines means compare value a[x] with a[y], if greater then swap the values in the array.

 (clickable)

The code from the book translated into C:

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

void sort(int l, int r)
{ int n = r-l+1;

  for (int p=1; p<n; p+=p)
    for (int k=p; k>0; k/=2)
      for (int j=k%p; j+k<n; j+=(k+k))
        for (int i=0; i<n-j-k; i++)
          if ((j+i)/(p+p) == (j+i+k)/(p+p))
              printf("%2i cmp %2i\n", l+j+i, l+j+i+k);
}
int main(char* argv, int args)
{ const int COUNT = 8;
  sort(0, COUNT-1);
}

See my StackOverflow question for more details and a diagram for the falsly generated network.

So I took the sorting network images for length = 1 << i and tried to write an algorithm that generates 2 indices x and y. These are needed to calculate the resource consumption of the sorting network in hardware.

I checked my function with length = 2, 4, 8, 16.

Here is my C code:

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

int log2ceil(int a)
{ int i;
  int cmp = 1;
  for (i = 0; cmp < a; i++)
  { cmp <<= 1; }
  return i;
}

void sort(int length)
{ int G = log2ceil(length);                      // number of groups
  for (int g = 0; g < G; g++)                    // iterate groups
  { int B = 1 << (G - g - 1);                    // number of blocks
    for (int b = 0; b < B; b++)                  // iterate blocks in a group
    { for (int s = 0; s <= g; s++)               // iterate stages in a block
      { int d = 1 << (g - s);                    // compare distance
        int J = (s == 0) ? 0 : d;                // starting point
        for (int j = J; j+d < (2<<g); j += 2*d)  // iterate startpoints
        { for (int i = 0; i < d; i++)            // shift startpoints
          { int x = (b * (length / B)) + j + i;  // index 1
            int y = x + d;                       // index 2
            printf("%2i cmp %2i\n", x, y);
          }
        }
      }
    }
  }
}
int main(char* argv, int args)
{ const int COUNT = 8;
  sort(COUNT);
}

Is it correct?
Can it be improved? E.g. just 4 loops.
It need not be very fast, because it's a hardware generation and check routine.


texts: Run the needle program for a query against the subject files and return the result

texts:
I have written the script to run locally the needle program for a query against the subject files. It returns the highest percentage result file as a string. In addition it also converts to html file (write_html function).

Can you help me to improve the script?

subject_path = settings.MEDIA_ROOT+"subject_files/"
query_path = settings.MEDIA_ROOT+"query_file/"

def run_bug():
    """The script runs the needle program for a query file against all the subject files in a folder and keeps only
    the highest identity score alignments.
    """

    query_list_fastafiles, subject_list_fastafiles = start_function()
    files_ending_with_one = filter_files_ending_with_one(subject_list_fastafiles)

    for j in range(len(query_list_fastafiles)):
        initial = 0
        needle_alignment_result = ''

        #take the scaffold sequence one by one
        for i in range(len(files_ending_with_one)):

            #path of the files
            file1 = query_path+ordered_query_fastafiles[j]
            file1 = subject_path+files[i]
            needle_output = run_needle_two_sequences(file1, file2)

            if needle_output == None:
                return needle_alignment_result = needle_output
            else:
                #print(ordered_query_fastafiles[j],ordered_scaffold_fastafiles[i])
                identity_percentage, result_file_as_string = needle_output
                #print(identity_percentage, results)
                identity_percentage = float(identity_percentage)

                if identity_percentage > initial:
                #keeps the highest percentage result among the files
                    initial = identity_percentage
                    needle_alignment_result = result_file_as_string

    write_html(needle_alignment_result)
    return needle_alignment_result


texts:
I have created template class to easily get the current number of instances a class has. It's threadsafe and I tried to make it as hard as possible to abuse.

#include <atomic>
#include <cstdint>
#include <type_traits>

template<typename t_derived>
struct countable
{
    friend t_derived;

    struct counter
    {
        friend countable<t_derived>;

    private:
        static std::atomic<uint32_t> s_counter;
    };

    static uint32_t instances()
    {
        static_assert(std::is_base_of<countable<t_derived>, t_derived>::value,
                      "Trying to get count of non counted class");
        return counter::s_counter;
    }

private:
    countable()
    {
        ++counter::s_counter;
    }

    countable(const countable&)
    {
        ++counter::s_counter;
    }

    ~countable()
    {
        --counter::s_counter;
    }
};

template<typename t_derived>
std::atomic<uint32_t> countable<t_derived>::counter::s_counter(0);

Edit:

There seem to be some misunderstandings about this class. I'm sorry, I should've explained it a bit. Here is an example main.cpp. It requires at least C++11:

#include <iostream>

// paste implementation here

struct counted1 : countable<counted1>
{
    counted1()
    {
        std::cout << "counted1::counted1()\n";
    }
    ~counted1()
    {
        std::cout << "counted1::~counted1()\n";
    }
};

struct counted2 : countable<counted2>
{
    counted2()
    {
        std::cout << "counted2::counted2()\n";
    }
    ~counted2()
    {
        std::cout << "counted2::~counted2()\n";
    }
};

int main()
{
    std::cout << "counted1 [" << counted1::instances() << "]\n";
    std::cout << "counted2 [" << counted2::instances() << "]\n";

    counted1 s1;

    std::cout << "counted1 [" << counted1::instances() << "]\n";
    std::cout << "counted2 [" << counted2::instances() << "]\n";

    {
        counted1 s2;
        counted2 s3;

        std::cout << "counted1 [" << counted1::instances() << "]\n";
        std::cout << "counted2 [" << counted2::instances() << "]\n";
    }
    std::cout << "counted1 [" << counted1::instances() << "]\n";
    std::cout << "counted2 [" << counted2::instances() << "]\n";

    return 0;
}

Why did I make the ctors private & not protected? Simply if they were protected every class could inherit from it. Making them private & declaring the template parameter a friend enforces the correct use of the crtp pattern:

struct my_counted_struct : countable<some_other_struct>{};   // error!

This has the side effect that all actual private data (s_counter) is also exposed to the derived class, so this would be possible:

struct my_struct : countable<my_struct>
{
    void do_something_nasty()
    {
        countable<my_struct>::s_counter = 0;
    }
};

That's why the actual private data is in the inner class counter which declares countable a friend, giving it access to its private data.


texts:
The task is taken from LeetCode

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two
lists.
Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:
Input: l1 = [], l2 = []
Output: []

Example 3:
Input: l1 = [], l2 = [0]
Output: [0]

Constraints:

The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both l1 and l2 are sorted in non-decreasing order.

The following solutions are identical logically. They only differ in style:
Style 1
 /**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    if (!l1) return l2;
    if (!l2) return l1;
    if (l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2);
        return l1;
    }
    l2.next = mergeTwoLists(l2.next, l1);
    return l2;
};

Style 2
 /**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    if (!l1 || !l2) return l1 || l2;
    const linkThem = (smaller, greater) => {
        smaller.next = mergeTwoLists(smaller.next, greater);
        return smaller;
    };
    return l1.val < l2.val ? linkThem(l1,l2) : linkThem(l2,l1);
};


texts:
Trying to implement something like CommandLineToArgV:

template<typename InIter, typename OutIter>
inline InIter CmdLineToArgvWUnescape(InIter begin, InIter end, OutIter target)
{
    if (std::distance(begin, end) < 2 || *begin != L'"')
    {
        // ""s are required
        throw MalformedEscapedSequence();
    }
    ++begin; //Skip "
    std::size_t backslashCount = 0;
    for(; begin != end; ++begin)
    {
        switch(*begin)
        {
        case L'\\':
            backslashCount++;
            break;
        case L'"':
            if (backslashCount)
            {
                std::fill_n(target, backslashCount / 2, L'\\');
                *target++ = L'"';
                backslashCount = 0;
            }
            else
            {
                return ++begin;
            }
        default:
            if (backslashCount)
            {
                std::fill_n(target, backslashCount, L'\\');
                backslashCount = 0;
            }
            *target++ = *begin;
        }
    }
    throw MalformedEscapedSequence();
}


texts: Finding an element without pair in a list O(n**2)

texts:
I'm practicing algorithms, and I just can not come up with a faster solution to this problem, but I'm not hitting the benchmark.
Problem: In a large list of large integers, I must find the one element, that is present in odd numbers. E.g. [1,1,1,1, 2,2, 3,3,3, 4,4,4,4].
I wrote several solutions, but I can not increase the speed of the execution.
import random

def testdata():
  space = []
  for i in range(10000):
    space = (
        space
        + [random.randint(0,1000000000)]
        * (random.randint(1,10) * 2)
    )
  odd = random.randint(0,1000000000)
  print(odd)
  space = space + [odd]
  random.shuffle(space)
  return space

def solution(A):
  A.sort()
  index = 0
  while True:
    count = A.count(A[index])
    if count%2:
      return(A[index])
    else:
      index = index + count

def solution_b(A):
  for elem in set(A):
    if A.count(A)%2:
      return(elem)

I'm not only looking for a better solution, but I'd appreciate it if someone explained, how to approach this kind of Big O notation problems. Without using pandas or numpy, etc.


texts: View model with properties that represent years and months

texts:
I have a view model with properties that represent years and months:

public IEnumerable<SelectListItem> Years
{
    get
    {
        return new SelectList(
            Enumerable.Range(1900, 112)
            .OrderByDescending(year => year)
            .Select(year => new SelectListItem
            {
                Value = year.ToString(CultureInfo.InvariantCulture),
                Text = year.ToString(CultureInfo.InvariantCulture)
            }
        ), "Value", "Text");
    }
}

public IEnumerable<SelectListItem> Months
{
    get
    {
        return new SelectList(
            Enumerable.Range(1, 12)
            .OrderByDescending(month => month)
            .Select(month => new SelectListItem
            {
                Value = month.ToString(CultureInfo.InvariantCulture),
                Text = month < 10 ? string.Format("0{0}", month) : month.ToString(CultureInfo.InvariantCulture)
            }
        ), "Value", "Text");
    }
}

I definitely use copy & paste approach here.  How can I refactor this code? Maybe somehow passing the numbers as parameters to some helper method?


texts: Integer square root in x86 assembly (NASM)

texts:
This program calculates the square root of an unsigned 32-bit number with some bit fiddling to get a very close approximation, then one iteration of the Babylonian method to get an exact value. I don't know if this could be faster, but hope it can.

I have trouble with clearly commenting my code, so I will gladly explain unclear portions of code.

[global sqrti]
sqrti:
        mov     eax, [esp+4]
        xor     ecx, ecx       ; clear register to put our approximation in
        ; make the lower 16 bits of CX equal the even-numbered bits of EAX
        shr     eax, 3
        rcr     cx, 1
%rep 14
        shr     eax, 2
        rcr     cx, 1
%endrep
        ; do one iteration of the Babylonian method
        or      ecx, 1          ; prevent a division by zero
        mov     eax, [esp+4]
        xor     edx, edx        ; clear top half of DIV's implied operand
        div     ecx
        add     eax, ecx
        shr     eax, 1
        ret


texts:
We are given a vector of std::pair<int, int>s, start int and stop int, and I need to extract the path out of it.

For instance:
given start = 2, stop = 8 and list of std::pairs as [(0, 5) (6,8), (5,6), (2,0)]. I am ordering the vector into:
[(2,0), (0,5), (5,6), (6,8)]. Now I need to isolate the nodes to get the path as [2,0,5,6,8]. (i.e. (2,0) and (0,5) become [2,0,5] and so on).

I have the following code. It works but I feel that it is needlessly long. Any idea to make it more compact and "safe"?

std::vector<int> get_pretty_path(const std::vector<std::pair<int,int>>& path_arcs, int s, int t){

    std::vector<std::pair<int,int>> ordered_arcs;

    assert(path_arcs.size() > 0);

    int _s = s;
    int _t = t;

    bool l_flag= true;

    std::vector<int> path;

    while (l_flag) {
        for(auto &arc: path_arcs){
            if (arc.first == _s){
                ordered_arcs.push_back(arc);
                _s = arc.second;
                if(arc.second == _t){
                    l_flag = false;
                    break;
                }
            }
        }
    }

    if(ordered_arcs.size() == 1){
        path.push_back(ordered_arcs.begin()->first);
        path.push_back(ordered_arcs.begin()->second);
    }
    else if (ordered_arcs.size() == 2){
        for (auto it = ordered_arcs.begin(); it != ordered_arcs.end()-1; ++it){
            if (it->second == (it+1)->first){
                path.push_back(it->first);
                path.push_back(it->second);
            }

            if((it+1) == ordered_arcs.end()-1){
                path.push_back((it+1)->second);
            }
        }
    }
    else{

        for (auto it = ordered_arcs.begin(); it != ordered_arcs.end()-1; ++it){
            if (it->second == (it+1)->first){
                path.push_back(it->first);
            }
            if((it+1) == ordered_arcs.end()-1){
                path.push_back((it+1)->first);
                path.push_back((it+1)->second);
            }
        }
    }

    return path;
}

This function is called in the order of 10,000 times. I was wondering if it can be as fast as possible. The max length of path_arcs is around 7-8 but is is usually 4-5 or less.

Note that the paths are not weighted. There is only one path. I just need it to be ordered from start to end. Some more examples:

input = [(2,0)] // given by the user
start = 2       // given by the user
stop = 0        // given by the user
output = [2,0]  // This should be the output

input = [(1,4), (2,1)] // given by the user
start = 2              // given by the user
stop = 4               // given by the user
output = [2,1,4]

input = [(4,5),(7,4),(2,3),(5,2)] // given by the user
start = 7                         // given by the user
stop =  3                         // given by the user
output = [7,4,5,2,3]


texts: Kadane's algorithms to leetcode "121 Best Time to Buy and Sell Stock"

texts:
I employed the conventional Kadane's algorithms to solve a maximum subarray problem in leetcode  Best Time to Buy and Sell Stock - LeetCode

Description

  Best Time to Buy and Sell Stock

  Say you have an array for which the ith element is the price of a given stock on day i.

  If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

  Note that you cannot sell a stock before you buy one.

  Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

  Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

My solution

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        local_max = global_max = 0
        gains = [prices[i]-prices[i-1] for i in range(1, len(prices))]
        for cur in gains:
            local_max = max(local_max + cur, cur)
            global_max = max(global_max, local_max)
        return global_max

  Runtime: 64 ms, faster than 14.96% of Python3 online submissions for Best Time to Buy and Sell Stock.

  Memory Usage: 14 MB, less than 5.08% of Python3 online submissions for Best Time to Buy and Sell Stock

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        loc = glo = 0
        for i in range(1, len(prices)):
            loc = max(loc+prices[i]-prices[i-1], prices[i]-prices[i-1])
            glo = max(glo, loc)
        return glo

  Runtime: 48 ms, faster than 53.38% of Python3 online submissions for Best Time to Buy and Sell Stock.

  Memory Usage: 13.8 MB, less than 5.08% of Python3 online submissions for Best Time to Buy and Sell Stock

TestCase

class MyCase(unittest.TestCase):
    def setUp(self):
        self.solution = Solution3()

    def test_a(self):
        prices = [7,1,5,3,6,4]
        answer = 5
        check = self.solution.maxProfit(prices)
        self.assertEqual(answer, check)

    def test_b(self):
        prices = [1,2,3,4,5]
        answer = 4
        check = self.solution.maxProfit(prices)
        self.assertEqual(answer, check)

    def test_c(self):
        prices = [7,6,4,3,1]
        answer = 0
        check = self.solution.maxProfit(prices)
        self.assertEqual(answer, check)

unittest.main()

The memory usage ranks very low.


texts:
while practicing Promises, I ended up with a simple weather application which works on the command line. I would highly appreciate it if you can point out any flaws in my code. They can be related to the efficiency, etc. I'm looking for anything you can provide in the review.

package.json:

{
  "name": "weather-app",
  "version": "1.0.0",
  "description": "A simple weather app.",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Hassan Althaf",
  "license": "MIT",
  "dependencies": {
    "request": "^2.67.0",
    "yargs": "^3.30.0"
  }
}

app.js:

var weather = require('./weather.js');
var location = require('./location.js');
var argv = require('yargs')
    .options({
        location: {
            demand: false,
            alias: 'l',
            type: 'string',
            description: 'Enables you to specify a location.'
        }
    })
    .help('help')
    .argv;

if(argv.location) {
    weather(argv.location).then( function(message) {
        console.log(message);
    }).catch( function(error) {
        console.log(error);
    });
} else {
    location().then( function (location) {
        return weather(location);
    }).then( function(output) {
        console.log(output);
    }).catch ( function(error) {
        console.log(error);
    });
}

location.js:

var url = 'http://ipinfo.io';
var request = require('request');

module.exports = function() {
    return new Promise( function(resolve, reject) {
        request({
            url: url,
            json: true
        }, function (error, response, body) {
            if (error || !body) {
                reject('Failed to fetch the location.');
            }

            resolve(body.city);
        });
    });
};

weather.js:

var request = require('request');

module.exports = function (location) {
    return new Promise( function(resolve, reject) {
        location = encodeURIComponent(location);

        if(!location) {
            reject('No location provided!');
        }

        var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&units=metric&appid=2de143494c0b295cca9337e1e96b00e0';

        request({
            url: url,
            json: true
        }, function (error, response, body) {
            if(error) {
                reject('Failed to fetch the weather!');
            }

            resolve('It\'s ' + body.main.temp + ' degrees Celsius in ' + body.name + '!');
        });
    });
};


texts:
This is legacy, so I'm not really looking for improvements on architectural approach.

Here's what the method does:

Extracts filename from a string containing full file path (passed in as parameter)
Checks to see if the filename extracted is not null or empty or just white spaces
If check in step 2 passes, then it uses naming conventions in the filename, to determine the logical "Type" for the file as follows:

If filename contains __Import__, then setType to Source Data
If filename contains __Export__, then setType to Destination Data
If filename contains __Transform__, then setType to Transformational Data
If none of the conditions from 3.1 through 3.3 are met, then default the "Type" to General.

Is there a way to make the if...else if... else if... block more concise, and elegant without loss of functionality?

private static string GetFileDataType(string fullFileNameWithPath)
{
    // extract filename only
    var fileName = Path.GetFileNameWithoutExtension(fullFileNameWithPath);
    var fileDataType = string.Empty;

    // if filename is not empty
    if (!string.IsNullOrWhiteSpace(fileName))
    {
        // if... else... to determine type of file contents based on file name convention
        // legacy code, so not looking for architectural improvements etc... :)
        if (fileName.Contains("__Import__"))
        {
            fileDataType = "Source Data";
        }
        else if (fileName.Contains("__Export__"))
        {
            fileDataType = "Destination Data";
        }
        else if (fileName.Contains("__Transform__"))
        {
            fileDataType = "Transformational Data";
        }
        else
        {
            fileDataType = "General";
        }
    }

    return fileDataType;
}


texts:
I  have been working on a board game in c++ using qt. The game cosist of four palyer with four different colors. I am looking forward to improving my board looking.

This is all working fine, but I want to know if there is any other way to do this?

"Readable online" The code for this part.

  std::vector<std::pair<char,char> > directions{std::make_pair(1,-1),std::make_pair(1,1),std::make_pair(-1,1),std::make_pair(-1,-1) };
    for(size_t d =0; d < directions.size(); ++d){
        for(int i=0; i<5;++i){
            if(d % 2 == 0)
                x_pos += directions[d].first * offset;
            else
                y_pos += directions[d].second * offset;
            fieldPos.push_back(QPointF(x_pos,y_pos));
        }
        x_pos += directions[d].first * small_offset;
        y_pos += directions[d].second * small_offset;
        for(int i=0; i<5;++i){
            fieldPos.push_back(QPointF(x_pos,y_pos));
            if(d % 2 == 0)
                y_pos += directions[d].second * offset;
            else
                x_pos += directions[d].first * offset;
        }
        for(int i=0; i<2;++i){
            fieldPos.push_back(QPointF(x_pos,y_pos));
            if(d % 2 == 0)
                x_pos += directions[d].first * large_offset;
            else
                y_pos += directions[d].second * large_offset;
        }
        fieldPos.push_back(QPointF(x_pos,y_pos));
    }

I also wonder how to get my board to look like the (rounded )one on the right. That would be very big help for me :)


texts:
I have the following Data.json file and I would like to update some of the  values.

{
"A0_Water":"-306.3",
"A1_Water":"0.0",
"A2_Water":"0.0",
"A3_Water":"0.0",
"Barometer":"100.8",
"Bar_Offset":"0",
"Temp":"29.95",
"ip":"192.168.2.47",
"serial":"02:42:52:bf:82:27",
"A0_Sensor":"PS30A",
"A1_Sensor":"None",
"A2_Sensor":"None",
"A3_Sensor":"None",
"A0_Offset":"0",
"A1_Offset":"0",
"A2_Offset":"0",
"A3_Offset":"0"
}

I am new to coding so any help will be much appriciated.
This is the code that I have working: The var data object that I created contains the entries that I want to update in the Data.json file but I was not sure how to use it. The remainder of the code is what I was able to get working but I am sure there is a better way to update the entries in the Data.json file

var data = {
'A0_Water': c_inh2o_A0,
'A1_Water': c_inh2o_A1,
'A2_Water': c_inh2o_A2,
'A3_Water': c_inh2o_A3,
'Barometer': b_mbar_corrected,
'Temp': b_temp
};

var fileName = '/home/admin/reactwatertracker/src/var/Data.json';
var file4 = require(fileName);
var file5 = file4;
var file6 = file4;
var file7 = file4;
var file8 = file4;
var file9 = file4;

file4['A0_Water'] = c_inh2o_A0;
file5['A1_Water'] = c_inh2o_A1;
file6['A2_Water'] = c_inh2o_A2;
file7['A3_Water'] = c_inh2o_A3;
file8['Temp'] =   b_temp;
file9['Barometer'] = b_mbar_corrected;

console.log('Writing to' + fileName);
fs.writeFile(fileName, JSON.stringify(file4,file5,file6,file7,file8,file9, null, 2),  function (err) {
 if (err) return console.log(err);
 console.log (JSON.stringify(file4));
});


texts: Using Templates to add virtual tables to non-virtual classes

texts:
So I have these classes that are meant to be low level and fast. I don't want them to generally be virtual - rather I want the functions to be inline.

In this case they are mutex implementations:

class MutexOne
{
public:
   void lock        () { /* implementation inline */ }
   bool tryLock     () { /* implementation inline */ }
   void unlock      () { /* implementation inline */ }
   void reset       () { /* implementation inline */ }

   static const char* implementationName() { return "MutexOne"; }
};

class MutexTwo
{
public:
   void lock        () { /* implementation inline */ }
   bool tryLock     () { /* implementation inline */ }
   void unlock      () { /* implementation inline */ }
   void reset       () { /* implementation inline */ }

   static const char* implementationName() { return "MutexTwo"; }
};

... etc ...

All the mmutexes have the same api. Within a testing framework I kind of wish they were virtual so that I can do something like:

testMutexImplementation( MutexVirtual& mutex )
{
    mutex.lock();  // etc... do a lot of complex validating
}

So within the testing framework I wish I had a nice clean virtual base class interface. But in production I don't want to pay for a virtual function on every mutex operation many of which are like 2-3 opcode in the general case.

So I thought of this way to use templates to add a virtual table after the fact, only when I need it.

So I start by creating the desired base class:

class MutexVirtual
{
public:

   virtual void lock        () = 0;
   virtual bool tryLock     () = 0;
   virtual void unlock      () = 0;
   virtual void reset       () = 0;

   virtual const char* implementationName() = 0;
};

And then use template magic to fill in the virtual table:

template < typename T > class MutexPostVirtual : public MutexVirtual, public T
{
public:
   void lock           () { T::lock(); }
   bool tryLock        () { return T::tryLock(); }
   void unlock         () { T::unlock(); }
   void reset          () { T::reset(); }

   const char* implementationName() { return T::implementationName(); }
};

I'm pretty happy and it works great:

MutexPostVirtual<MutexOne> mutex1;
MutexPostVirtual<MutexTwo> mutex2;

testMutexImplementation( mutex1 );
testMutexImplementation( mutex2 );

I can't help thinking that maybe there is a cleaner simpler way? How can this code be better?


texts:
I'm currently learning C with The C Programming Language by K&R and this is my current exercise:

  Rewrite appropriate programs from earlier chapters and exercises with pointers instead of array indexing. Good possibilities include getline, atoi, itoa, reverse, strindex and getop.

This is my atoi solution with pointers:

#include <ctype.h>

int atoi(const char *nptr)
{
    while(isspace(*nptr++)) // skip white space
        ;

    long long val = 0;
    const char *start = nptr;

    if(*nptr == '-' || *nptr == '+')
        nptr++;

    while(*nptr >= '0' && *nptr <= '9')
        val = val*10 + *nptr++ - '0';

    return (*start == '-') ? -val : val;
}

I'm currently a little bit unhappy with the idea, that my code can't do anything against values smaller than INT_MIN and values greater than INT_MAX, but I can't come up with a solution that fits my expectations of good code.

I could just return INT_MIN and INT_MAX, but then the caller can't decide between the actual values and an error in form of INT_MIN/INT_MAX.
It is also possible to use a second argument - a pointer to an int. The function will write the value into this int and will return 1 if it was successful and 0 if it wasn't.

I want to hear your thoughts on how I should handle this special case.


texts:
I'm designing a new esoteric language, and the interpreter is in Python3. It is going to use Prefix Notation, so as part of the interpreter, I need a function that evaluates a string as prefix notation and returns a number. Here is my code so far:

import re
import math

class Operator:
    def __init__(self, arity, function):
        self.arity = arity
        self.function = function

    def __call__(self, *args):
        assert(len(args) == self.arity)
        return self.function(*args)

operatorTable = { "+": Operator(2, lambda a,b: a+b),
             "-": Operator(2, lambda a,b: a-b),
             "/": Operator(2, lambda a,b: a/b),
             "*": Operator(2, lambda a,b: a*b),
             "<": Operator(2, lambda a,b: a<b),
             ">": Operator(2, lambda a,b: a>b),
             "_": Operator(1, lambda a: -a),
             "p": Operator(0, lambda: math.pi),
             "e": Operator(0, lambda: math.e)
}

def prefixParse(code):
    if code[0] in operatorTable:
        operator = operatorTable[code[0]]

        if operator.arity == 2:
            arg1, chomp1 = prefixParse(code[1:])
            arg2, chomp2 = prefixParse(code[chomp1 + 1:])
            return operator(arg1, arg2), chomp1 + chomp2 + 1

        elif operator.arity == 1:
            arg, chomp = prefixParse(code[1:])
            return operator(arg), chomp + 1

        elif operator.arity == 0:
            return operator(), 1

    match = re.match("^\d+", code)
    if match:
        return int(match.group(0)), match.end()

    if code[0] == ' ':
        res = prefixParse(code[1:])
        return res[0], res[1] + 1

print(prefixParse("+2*5 10")[0])

I'm interested in hearing any improvements you have to offer, but I'm particularly interested in these design questions:

Is the recursive prefixParse a good/suitable algorithm for parsing prefix notation, or is there a simpler way to do it?
Is it overkill to use the Operator class?
Is there a way to "chomp" the string in place rather than handing a bunch of string indices back and forth? That would be nice because then to get an integer result from the parse function, I don't have to do prefixParse(code)[0] which looks kinda ugly IMO.
Is the layout of the multi-line operatorTable assignment good code formatting?


texts:
I wrote the following code. A user in STACKOVERFLOW website recommended me to write my code here in order to be reviewed for optimization.
How could I optimize it?
Could I have this code in a pro and better form and performance?

EXPLANATION: This code calculate multiplication of three matrix in c() function. Then, using Omo as old and Omn as new into c() calculate L().Finally, defining two if statement accept Ls which are bigger than 1 and R3 which is random number. THIS CODE IS MCMC FITING DATA. HERE I FIT omn and Mn.

import numpy as np
import emcee
import matplotlib.pyplot as plt
from math import *
from scipy.integrate import quad
from scipy.integrate import odeint
O_m=chi=None
xx=np.array([0.01,0.012])
yy=np.array([32.95388698,33.87900347])
Cov=[[137,168],[28155,-2217]]     # this is a covariance matrix for simplification I chose the 2*2 one

temp=1e5
z0=0
M=2
Omo = 0.3
Odo=0.7
H0=70

def ant(z, Om, Od):
    return 1/sqrt(((1+z)**2)*(1+Om*z)-z*(2+z)*Od)
def dl(n, Om, Od, M):
    Od=1-Om
    q=quad(ant,0,xx[n],args=(Om,Od))[0]
    h=5*log10((1+xx[n])*q)
    fn=(yy[n]-M-h)
    return fn

def c(Om, Od, M):
    f_list = []
    for i in range(2):  # the value '2' reflects matrix size
        f_list.append(dl(i,Om,Od,M))
    rdag=[f_list]
    rmat=[[f] for f in f_list]
    a=np.dot(rdag,Cov)
    b=np.dot(a,rmat)
    Matrix=np.linalg.det(b)*0.000001
    return Matrix
N=2000
with open('txtfile.txt', 'w') as f:
    for i in range (1,N):
        R1=np.random.uniform(0,1)
        R2=np.random.uniform(0,1)
        R3=np.random.uniform(0,1)
        R4=np.random.uniform(0,1)
        def delta(r1, r2):
            sig=0.04
            d=sig*(np.sqrt(-2*np.log(r1))*np.cos(np.radians(r2)))
            return d
        Omn=Omo+delta(R1, R2)
        Odn=1-Omn
        Mn=M+delta(R3,R4)
        R3=np.random.uniform(0,1)

        def L():
            l=np.exp(-0.5*(c(Omn,Odn,Mn)-c(Omo,Odo,M)))
            return l
        if L()>1:
            O_m=Omn
            chi=c(Omn,Odn,Mn)

        elif L()>R3:
            O_m=Omn
            chi=c(Omn, Odn, Mn)

        f.write("{0}\t{1}\n".format(chi, O_m))
    print("Minimum of chi squre is")
    if chi<temp:
        temp=chi
        chimin=temp
    print(chimin)
    print(input("Press any key to exit... "))

I appreciate your help and your attention


texts: Ruby script to deactivate or add users to database table

texts:
I have a Ruby script meant for some basic database tasks, such as add a user and deactivate a user.  The end user can load up the script and follow the basic path of "Do I want to add a user?", or "Do I want to deactivate a user?". They have the option to retreat back to the main menu if needed.

The script works just fine, but being new to Ruby, I am starting to sense I have made things overly complicated and some simple refactoring could make the code much cleaner.  I am also interested to hear any other feedback.

  require 'yaml'

  config = YAML.load_file('config.yml')  ## Loads in the config file with databases eligible for selection

  puts 'Loading configured Databases'

  config.each do |k, v|
    puts " #{k}, #{v}"
  end

  def path  # Method to create a reusable menu
    puts "Press 1 to add a new user\nPress 2 to mark a user as active or inactive \nPress 3 to Exit"

    path = gets.chomp.to_i

    if path == 3
      puts 'Exiting...'
      exit
    else
      path_switch(path)
    end
  end

    def path_switch(path_var)
      config = YAML.load_file('config.yml')  ## Loads in the config file with databases eligible for selection
      path = path_var
      rds = ''
      table = ''
      choicelen = config.length
    case path
      when 1
        puts 'Select the numeric ID of the ICE installation to add the user to\n Enter 0 to go back'
        config.each do |k, v|
          puts "#{v['id']}: #{k}"
        end
          choice_client_ice = gets.chomp.to_i
           if choice_client_ice > choicelen
             puts 'error, not a valid selection'
             path
           end
          path if choice_client_ice == 0
          config.each do |k, v|
            if v['id'].to_i == choice_client_ice
              rds = v['rds']
              table = v['table']
            end
          end
            puts "Your current focus is: #{rds} at #{table}"
            path_add(rds, table)
      when 2
        puts 'Select the numeric ID of the ICE installation to edit the user for or type in 0 to go back'
        config.each do |k, v|
          puts "#{v['id']}: #{k}"
        end
          choice_client_ice = gets.chomp().to_i
          path if choice_client_ice == 0
          if choice_client_ice > choicelen
            puts 'error, not a valid selection'
            path
          end
          config.each do |k, v|
            if v['id'].to_i == choice_client_ice
              rds = v['rds']
              table = v['table']
            end
          end
            puts "Your current focus is: #{rds} at #{table}"
            path_edit(rds, table)
        else
          puts "Error, #{path} is not a valid option."
          path
      end
  end

  def path_add(rds, table)
    puts 'Input the users email address or enter the word exit to go back to the beggining'
    email = gets.chomp
    if email == 'exit'
      path
    else
    puts 'Please add the users group id'
    groupid = gets.chomp.to_i
    puts 'Please add the users course style id'
    coursestyleid = gets.chomp.to_i
    puts "This will create a user with email address #{email}, group id of #{groupid} and course style id of #{coursestyleid}.  Please confirm (y/n)"
    confirm = gets.chomp
    if confirm == 'y'
      ## Add in sequel call
      puts 'user has been added as xxx'
    else
      path
    end
  end
  end

  def path_edit(rds, table)
    puts 'Input the users ID or enter the word exit to go back to the beggining'
    uid = gets.chomp
    if uid == 'exit'
      path
    else
      puts 'The user xxx is currently xxx, this will mark him as xxx, continue? (y/n)'
      confirm = gets.chomp
        if confirm == 'y'
          ## Add in sequel call
          puts 'User has been marked as xxx'
        else
          path
        end
    end
  end

  def ice_select
  end

path


texts: Project Euler # 38 Pandigital multiples in Python

texts:
Take the number 192 and multiply it by each of 1, 2, and 3:

  192 × 1 = 192
  192 × 2 = 384
  192 × 3 = 576

  By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)

  The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).

  What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?

Awaiting feedback.

def check_pandigital(n):
    """Assumes n is a string of numbers.
    returns True if 1-9 in number, False otherwise."""
    for i in range(1, 9):
        if str(i) not in n:
            return False
    return True

def multiply_concatenate(n):
    """Assumes n is a positive integer.
    returns concatenations of number multiplied by a range if (1-9) in number."""
    s = str(n)
    for i in range(2, 10):
        s += str(i * n)
        if check_pandigital(s):
            return s

def check_range(n):
    """Assumes n is a range(integer).
    generates pandigitals within the range."""
    for i in range(2, n):
        mult_conc = multiply_concatenate(i)
        if mult_conc and len(mult_conc) <= 9:
            yield mult_conc

if __name__ == '__main__':
    print(max(int(number) for number in check_range(10000)))


texts:
I think this code is not optimized:

function changeSalesStage(value){

    var $form = $( getProductsForm() );

    if( typeof(value) == 'undefined' ) value = $("#sales_stage", $form).val();

    // Failure
    var cause = $("#causes_failure", $form);
    var notes = $("#failure_notes", $form);
    var seconder = $("#seconder", $form);

    if( cause.length == 0 || seconder.length == 0 ) return;

    var el1 = cause.parentsUntil('tr');
    var el2 = notes.parentsUntil('tr');
    var el3 = seconder.parentsUntil('tr');
    var display = 'none';
    if(value == 'Closed Lost'){
        el1.css('display', '');
        el2.css('display', '');
        el1.prev().css('display', '');
        el2.prev().css('display', '');
        el3.css('display', 'none');
        el3.prev().css('display', 'none');
        seconder.val('');
    }
    else if(value == 'IdentifyAnalysis') {
        el3.css('display', '');
        el3.prev().css('display', '');
        cause.val('');
        notes.val('');
        el1.css('display', 'none');
        el2.css('display', 'none');
        el1.prev().css('display', 'none');
        el2.prev().css('display', 'none');
    }
    else {
        display = 'none';
        el3.css('display', display);
        el3.prev().css('display', display);
        el1.css('display', display);
        el2.css('display', display);
        el1.prev().css('display', display);
        el2.prev().css('display', display);
    }
    // validate
    var formname = $form.attr('name');
    var formname1 = $form.attr('name1');
    if( typeof(validate[formname1]) == 'undefined' ) {return;}
    else if( typeof(validate[formname]) == 'undefined' ) return;

    var index = -1, label, name = "causes_failure", name1 = "seconder";
    for( i=0; i < validate[formname].length ||  i < validate[formname1].length; i++ ) {
        if( validate[formname][i][nameIndex] == name || validate[formname][i][nameIndex] == name1){
            index = i;
            label = validate[formname][i][msgIndex];
            label = validate[formname1][i][msgIndex];
            break;
        }
    }
    if( index == -1 ) return;

    if( display == 'none' ) {
        cause.val('');
        notes.val('');
        seconder.val('');
        validate[formname][index][requiredIndex] = false;
        validate[formname1][index][requiredIndex] = false;
    }
    else {
        validate[formname][index][requiredIndex] = true;
        validate[formname1][index][requiredIndex] = true;
    }
}


texts:
My first attempt at Scheme (Chicken Scheme) - a simple RPN calculator. Please comment on exception handling as well as the general coding style. Here is the code:

(use stack)
(use srfi-69)
(use simple-exceptions)

(define prompt "> ")

(define stack (make-stack))
(define words (make-hash-table))

(define (init-words)
  (hash-table-set! words "bye" '(quit))
  (hash-table-set! words ".s" '(stack-print))
  (hash-table-set! words "+" '(add))
  (hash-table-set! words "-" '(subtract))
  (hash-table-set! words "*" '(multiply))
  (hash-table-set! words "/" '(divide))
  (hash-table-set! words "." '(pop-print))
  (hash-table-set! words "dup" '(dup))
  (hash-table-set! words "drop" '(drop))
  (hash-table-set! words "swap" '(swap)))

(define (stack-print)
  (display (stack->list stack))
  (newline))

(define (pop-print)
  (display (stack-pop! stack))
  (newline))

(define (add)
  (stack-push! stack
           (+ (stack-pop! stack)
          (stack-pop! stack))))

(define (subtract)
  (swap)
  (stack-push! stack
           (- (stack-pop! stack)
                  (stack-pop! stack))))

(define (multiply)
  (stack-push! stack
           (* (stack-pop! stack)
          (stack-pop! stack))))

(define (divide)
  (swap)
  (stack-push! stack
           (/ (stack-pop! stack)
          (stack-pop! stack))))

(define (dup)
  (let ((first (stack-pop! stack)))
    (stack-push! stack first)
    (stack-push! stack first)))

(define (drop)
  (stack-pop! stack))

(define (swap)
  (let ((first (stack-pop! stack))
    (second (stack-pop! stack)))
    (stack-push! stack first)
    (stack-push! stack second)))

(define (f-read)
  (display prompt)
  (flush-output)
  (read-line))

(define (f-parse line)
  (string-split line))

(define (process word)
  (cond
   ((hash-table-exists? words word)
    (eval (hash-table-ref words word)))
   ((string->number word)
    (stack-push! stack (string->number word)))))

(define (f-eval words)
  (cond
   ((null? words) "")
   (else (process (car words))
     (f-eval (cdr words)))))

(define (f-print line)
  (display line))

;; user-interrupt ?

(define (repl)
  (guard
   (exn (((exception-of? 'user-interrupt) exn)
     (quit))
    ((exception? exn)
     (display (message exn))
     (newline)
     (repl))
    (else
     (display (arguments exn))
     (newline)
     (repl)))
   (init-words)
   (f-print (f-eval (f-parse (f-read))))
   (repl)))


texts:
I have a function which sends an email via outlook when given text, a subject, and recipients shown below:

def __Emailer(text, subject, recipient, auto=True):
    import win32com.client as win32

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    if type(recipient) == type([]):
        for name in recipient:
            mail.Recipients.Add(name)
    else:
        mail.To = recipients
    mail.Subject = subject
    mail.HtmlBody = text
    if auto:
        mail.send
    else:
        mail.Display(True)

Now, I know that type comparisons in Python are strongly discouraged, but I can't think of a better way to do this.  I want it to send to multiple addresses if recipient is a list using the mail.Recipients.Add(name), and mail.To if there is only one name (not given as a list).  How can I accomplish this without using nasty type comparisons?


texts:
I have three checboxes in my form. I have to check which one is checked and start the action. What do you think? Is this the easiest way of doing it?

Checkbox 1 = cat
Checkbox 2 = dog
Checkbox 3 = dog
Only cat ->           form action
Cat & any of dogs ->  play music
Dog & dog ->          play music
Nothing ->            form action

HTML:

    <form action="sample_action" method="get">
            <input type="hidden" name="sample_name" value="sample_value">

<input id="checkbox1" type="checkbox" name="pet" value="cat">Cat

<input id="checkbox2" type="checkbox" name="pet" value="dog">Dog 1

<input id="checkbox3" type="checkbox" name="pet" value="dog">Dog 2

          <button type="submit">Check my pets</button>
   </form>

Solution:

function checkPets () {
  var cat = $('#checkbox1').is(":checked");
  var dog1 = $('#checkbox2').is(":checked");
  var dog2 = $('#checkbox3').is(":checked");
  return !cat &&(dog1 || dog2);
}

$(window).load(function(){
$('.pets form').submit( function(e){
    if(checkPets()) {
        e.preventDefault();
        $('body').append('<audio></audio>');
        $('audio').attr({'src': 'audio.mp3', 'autoplay': 'autoplay'});
    }
});


texts:
My code recovers all sent messages (ending with "\r\n") in function read_message. I would like to improve this code, make it more efficient? If it's possible, I am open to all reviews!

Code

static char     *read_message(char *data)
{
    static char     *buffer = NULL;
    char            *message = NULL;
    char            *ptr;
    size_t          size;

    if (buffer)
    {
        size = strlen(buffer) + strlen(data) + 1;
        if (!(buffer = realloc(buffer, size)))
            return (NULL);
        strcat(buffer, data);
    }
    else {
        if (!(buffer = strdup(data)))
            return (NULL);
    }
    if ((ptr = strstr(buffer, "\r\n")))
    {
        size = ((unsigned int)ptr - (unsigned int)buffer) + 1;
        if (!(message = (char*)malloc(sizeof(char) * size)))
            return (NULL);
        strncpy(message, buffer, size);
        ptr += 2;
        if (!(ptr = strdup(ptr)))
            return (NULL);
        free(buffer);
        buffer = ptr;
    }
    return (message);
}

static t_message    *parse_message(char *buffer)
{
    int     id;

    id = atoi(buffer);
    printf("L'id du message est %d\n", id);
    return (NULL);
}

static void     handle_message(void)
{
    printf("OK\n");
}

void            listen_client(t_args *args)
{
    ssize_t     count;
    char        buffer[BUFF_SIZE + 1] = { 0 };
    char        *msg_str;
    t_message   *msg;

    while ((count = recv(args->client->s, buffer, BUFF_SIZE, 0)))
    {
        buffer[count] = '\0';
        if (!(msg_str = read_message(buffer)))
            continue ;
        if (!(msg = parse_message(msg_str)))
            continue ;
        handle_message();
    }
    printf("Fin de connexion\n");
}


texts: Javascript function to convert SQL resultset to a string

texts:
function get_sql_string(dbConn,query_string,col_delim,row_delim) {
    var result = dbConn.executeCachedQuery( query_string );
    var result_string = '';
    var column_count = result.getMetaData().getColumnCount();
    if ( col_delim ){
        col_delim = col_delim;
    }
    else {
        col_delim = ',';
    }

    if ( row_delim ){
        row_delim = row_delim;
    }
    else {
        row_delim = '\n';
    }

    if(result.size() > 0){
        while (result.next()) {
            i = 1;
            var line = '';
            while (i <= column_count) {
                line = line + result.getString(i) + col_delim;
                i++;
            }
            result_string = result_string + line.slice(0, -1) + row_delim;
        }
        result_string = result_string.slice(0, -1);
        result.close();
        if (result_string.toString() != 'null' || result_string != null) {
            return result_string.trim();
        }
        else {
            return '';
        }
    }
    else {
        dbConn.close();
        return '';
    }
    dbConn.close();
}

Executes a SQL select query and creates a string from the results

@param0 {String} dbConn - connection string for database
@param1 {String} query_string - query to execute
@param2 {String} col_delim - column delimiter separates each value in a row, default value is a commma
@param3 {String} row_delim - row delimiter separates earch row in the resultset, default value is a newline character
@return {String} returns the resultset as a string with column and row delimiters

Above is a function in that converts a SQL resultset to a string. I want to learn how to make this code more succint for maintainability. Can someone help? Thanks!


texts: Custom Global Store using React.js context and hooks

texts:
I wanted to use an external global state to a React.js application with a redux-like sort of pattern (with reducers, actions, etc). However, I don't want to use redux itself, as it's just a small project and redux might be too much boilerplate.

Below is a sort of imitation of Redux with React.js Hooks and State. It's a variation of a design found in this article

// src/store/index.js
import React, { createContext, useContext, useReducer} from "react";
import { initialAppState } from "./types";
import { reducer } from "./reducers";

// Redux Mini :)

let dispatchOuter;

const StateContext = createContext(initialAppState);

export const StateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialAppState);
  dispatchOuter = dispatch;
  return (
    <StateContext.Provider value={state}>{children}</StateContext.Provider>
  );
};

export const useStore = () => [
  useContext(StateContext),
  dispatchOuter,
];

Usage:

// src/index.js
ReactDOM.render(
  <StateProvider>
    <ExampleComponent/>
  </StateProvider>,
  document.getElementByID("root")
);

// src/components/ExampleComponent.js
export function ExampleComponent() {
  const [state, dispatch] = useStore();
  return (

      <Button onClick={() => {dispatch({type: "INCREMENT_CLICKS"})}}/>
      {state.clicks}

  );
}

The StateProvider component is actually a StateContext.Provider, which provides context accessed by the useStore(). With some initial tests it seems to work pretty well.

Are there any major flaws with this design? Any changes you would suggest? Will I be shooting myself in the foot down the road using this pattern?


texts: HMSegmentedControl react to tapping on currently selected segment

texts:
I'm using HMSegmentedControl, an open-source UISegmentedControl subclass. I'm trying to react to the user tapping on the currently selected segment. HMSegmentedControl only supports reacting to a segment CHANGE, with either UIControlEventValueChanged or a block that executes when the index is changed. I need to react to the currently selected segment in order to present a drop-down menu. Here is what I've done so far:

-(void)segmentedControlValueChanged:(HMSegmentedControl *)control {
    CGFloat midX = self.view.frame.size.width / 2 - _filterView.frame.size.width / 2;
    _filterView.frame = CGRectMake(midX, -_filterView.frame.size.height+64, _filterView.frame.size.width, _filterView.frame.size.height);
    _filterView.hidden = YES;

    _filterBackgroundView.alpha = 0.0f;
    _filterBackgroundView.hidden = YES;
}

-(void)segmentedControlTouchUpInside:(UIGestureRecognizer *)gr {

    if(!_filterView) {
        _filterView = (HomeFilterView *)[[NSBundle mainBundle] loadNibNamed:@"HomeFilterView" owner:self options:nil].firstObject;
        CGFloat midX = self.view.frame.size.width / 2 - _filterView.frame.size.width / 2;
        _filterView.frame = CGRectMake(midX, -_filterView.frame.size.height+64, _filterView.frame.size.width, _filterView.frame.size.height);
        _filterView.delegate = self;
        [self.view insertSubview:_filterView belowSubview:self.segmentedControl];
    }

    if(!_filterBackgroundView) {

        _filterBackgroundView = [[UIView alloc] initWithFrame:self.view.bounds];
        _filterBackgroundView.backgroundColor = [UIColor blackColor];
        _filterBackgroundView.alpha = 0.0f;
        [self.view insertSubview:_filterBackgroundView belowSubview:_filterView];
    }

    _filterView.hidden = NO;
    _filterBackgroundView.hidden = NO;

    [UIView animateWithDuration:0.5f delay:0.0f usingSpringWithDamping:0.55f initialSpringVelocity:0.0f options:UIViewAnimationOptionCurveLinear animations:^{

        CGFloat midX = self.view.frame.size.width / 2 - _filterView.frame.size.width / 2;
        CGFloat y = self.segmentedControl.frame.size.height + self.segmentedControl.frame.origin.y;
        _filterView.frame = CGRectMake(midX, y-70, _filterView.frame.size.width, _filterView.frame.size.height);

    } completion:^(BOOL finished) {

    }];

    [UIView animateWithDuration:0.25f animations:^{

        _filterBackgroundView.alpha = 0.5f;

    } completion:^(BOOL finished) {

    }];
}

I added a tap gesture recognizer to the segmented control. So, if a user selects the current segment, only segmentedControlTouchUpInside: will be fired. If a user selected a different segment, segmentedControlTouchUpInside: is fired, followed by segmentedControlValueChanged:. I'm relying on the segmentedControlValueChanged: method to be called after the gesture-recognizer method, and essentially "undo" the adding of the drop-down to the UI.

This is the only way I could figure out to handle the tapping of the current segment. It seems to accomplish what I'm going for in the UI, but can anyone think of a better way of doing this? Is this safe to do?


texts:
I'm trying to expand my use of classes and better understand how/when to use them. Please review the code and let me know if I'm on the right track or where I need to make improvements. For example, should I remove the database call from the class, why or why not?

<?php
class Model{

    private $_db;

    private $first;
    private $last;
    private $gender;
    private $birthYear;
    private $agency;
    private $picture;

    public function __construct($db){
        $this->_db = $db;
    }

    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }

        return $this;
    }

    public function add_model(){
        $statement = $this->_db->prepare("insert into models (first_name, last_name, gender, birth_year, agency, picture) values (:first, :last, :gender, :birth_year, :agency, :picture)ON DUPLICATE KEY UPDATE gender = VALUES(gender), birth_year=VALUES(birth_year), agency=VALUES(agency), picture=VALUES(picture)");

        $statement->bindParam(':first', $this->first);
        $statement->bindParam(':last', $this->last);
        $statement->bindParam(':gender', $this->gender);
        $statement->bindParam(':birth_year', $this->birthYear);
        $statement->bindParam(':agency', $this->agency);
        $statement->bindParam(':picture', $this->picture);

        $result = $statement->execute();
        if ($result){
            return true;
        } else {
            return false;
        }
    }

}
?>


texts:
I have a problem with my code, because his is required a long time to be done(only when I put big numbers like 2000)...
I am trying to do the Hamming Numbers kata on codewars.com:

A Hamming number is a positive integer of the form 2i3j5k, for some non-negative integers i, j, and k.
Write a function that computes the nth smallest Hamming number.
Specifically:

The first  smallest Hamming number is 1 = 203050
The second smallest Hamming number is 2 = 213050
The third  smallest Hamming number is 3 = 203150
The fourth smallest Hamming number is 4 = 223050
The fifth  smallest Hamming number is 5 = 203051

The 20 smallest Hamming numbers are given in example test fixture.
Your code should be able to compute all of the smallest 5,000 (Clojure: 2000, NASM: 13282) Hamming numbers without timing out.

And my code is:
function isHumming(x){
    while(x % 2 === 0) x /= 2;
    while(x % 3 === 0) x /= 3;
    while(x % 5 === 0) x /= 5;
    return x == 1;
}

function hamming (n){
    let duzina = 1;
    let trenutni = 2;
    let poslednji = 1;
    while(duzina < n){
        if(isHumming(trenutni)){
            if(trenutni >= n){
                poslednji = trenutni;
            }
            duzina++;
        }
        trenutni++
    }
    return poslednji;
}
console.log(hamming(100));

The problem arises when I try to put a large number like 5000, because the code seems stuck...Can anyone help me to create code which can do that in max 12 sec?


texts: Intended to return account address using account ID, which uses Spring Stored Procedure class

texts:
I have not used Springs stored procedure class before to return data and I was hoping someone would be able to check this for me..

If it will A. Return data, B. Can be improved. C. If I wanted to return multiple rows how would this need to be changed?

public class AccountAddress extends StoredProcedure implements DAOConstants{

    private static final String STOREDPROC = "storedProc";
    private static final String CURSOR = "cursor";

    public AccountAddress() {
        super(Config.getJdbcTemplate, STOREDPROC);
        declareParameter(new SqlParameter("accountID", OracleTypes.VARCHAR);
        declareParameter(new SqlOutParameter(CURSOR,OracleTypes.CURSOR, new AccountAddressMapper());
        setFunction(false);
        compile();
    }

    public List<String> getAccountAddress(String accountId) {
        Map<String,Object> params = new HashMap<~>();
        Map<String,Object> results = new HashMap<~>();
        List<String> data = new LinkedList<~>();
        try{
            params.put("accountId",accountId);
            results = execute(params);
            data = (List<String>) results.get(0);
        } catch (DataAccessException e) {
            // log errors
        }
        return data;
    }

    public class AccountAddressMapper implements RowMapper<List<String>> {
        @Override
        public List<String> mapRow(Resultset rs, int i) throws SQLException{
            List<String> data = new ArrayList<~>();
            data.add(rs.getString(4));
            data.add(rs.getString(5));
            data.add(rs.getString(6));
            data.add(rs.getString(7));
            data.add(rs.getString(8));
            return data;
        }
    }
}


texts:
I have completed an exercise where there are 4 different color boxes and 1 main box below them that is blank, when you click on one of the colored boxes, the main box changes to the color of the box you just clicked on. Also there should be working undo and redo buttons.

Am I doing this the "Angular" way by using $event or no?

(function() {
  'use strict';

function angularBoxesCtrl() {
  var vm = this;
  vm.mainBoxColor;

  var colorHistory = [];
  var undoRedo = [];

  var changeColor = function() {
    vm.mainBoxColor = colorHistory[colorHistory.length - 1];
  }

  vm.logClass = function(e) {
    var boxColor = e.target.classList[1];
    //mainBox is already same color as clicked box
    if (boxColor === vm.mainBoxColor) {
      return;
    }
    colorHistory.push(boxColor)
    changeColor();
  }

  vm.undo = function() {
    if (!colorHistory.length) {
      return;
    }
    var undoColor = colorHistory.pop();
    undoRedo.unshift(undoColor);
    changeColor();
  }

  vm.redo = function() {
    if (!undoRedo.length) {
      return;
    }
    var redoColor = undoRedo.shift();
    colorHistory.push(redoColor);
    changeColor();
  }
}

angular.module('angularBoxes', [])
  .controller('angularBoxesCtrl', [
    angularBoxesCtrl
    ]);

})();
div {
  box-sizing: border-box;
}

.boxHolder {
  border: 1px solid black;
  text-align: center;
  font-size: 0;
}

.buttonHolder {
  text-align: center;
  position: relative;
  top: 40px;
}

.box {
  width: 180px;
  height: 180px;
  display: inline-block;
  border: 1px solid black;
  margin: 4px;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
}

.yellow {
  background-color: yellow;
}

.mainBox {
  width: 400px;
  height: 400px;
  margin: 0 auto;
  border: 1px solid black;
  position: relative;
  top: 80px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Angular Boxes</title>
  <link rel="stylesheet" href="styles.css">

    <button ng-click="vm.undo()">Undo</button>
    <button ng-click="vm.redo()">Redo</button>


texts: Creating two output files from two formatted files

texts:
I've been working on a project to take data from csv files, re-format it, and display it as charts.  I'm working for a company over the summer and when I leave, I would like my code to be readable/editable by whoever takes over in the future.

This code reads in two files, formats them, and creates two output files.  It takes in one command line argument as a filepath to the source folder for the data.  The formatting just counts the number of occurrences of a word and increments a corresponding value in a 2D array.

Would you understand what this is doing if I hadn't given an explanation?  Should I change anything about it to make it more readable?

#!/usr/bin/perl

use strict;
use warnings;

my $src = $ARGV[0];
my %files = (
    'LM' => [$src . '\raw\casesByCategory_LM.csv', $src . '\casesByCategoryLM.csv'],
    'TM' => [$src . '\raw\casesByCategory_TM.csv', $src . '\casesByCategoryTM.csv'],
);

foreach my $file (keys %files) {
    my @categories = (
        ['RMA Request', 0],
        ['Product Info Request', 0],
        ['Dealer Locator (New or Resupply)', 0],
        ['Order Request', 0],
        ['Order Status', 0],
        ['Wireless Activation/Deactivation', 0],
        ['Pricing', 0],
        ['Account Setup/Registration', 0],
        ['Other', 0],
    );
    my $total = 0;
    open (DATA, $files{$file}[0]) or die $!;

        # Remove header
        <DATA>;
        my $match = 0;
        while (my $line = <DATA>) {
            # Remove \n character
            chomp $line;
            # Search through list of categories to find a match
            if ($line =~ /^"(.+)"$/) {
                foreach my $cat (@categories) {
                    if ($1 eq $cat->[0]) {
                        $cat->[1]++;
                        $match = 1;
                    }
                }
            }
            # Add case to 'Other' if no match was found
            if (not $match) {
                $categories[8]->[1]++;
            } else {
                $match = 0;
            }
            $total++;
        }

    close (DATA);

    # Write organized data to new CSV file for chart
    open (OUTPUT,'>', $files{$file}[1]) or die $!;

        print OUTPUT "Total: $total\n";
        foreach my $cat (@categories) {
            print OUTPUT "$cat->[0],$cat->[1]\n";
        }

    close (OUTPUT);
}


texts:
I am trying to make a 3D grid plot in Python using Matplotlib. The grid consists of hexahedral cells (with qudrilateral surfaces). The surfaces should be colored according to their height, that is: the z coordinate. A colorbar should accompany the plot.

Here is an example plotting three surfaces:

from matplotlib import pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np

def getFaceMidpointsZ(pc):
    a=[]

    for i in pc:
        v=0
        for j in i:
            v=v+j[2]
        v=v/4.
        a.append(v)
    return a

def getColors(m,a):
    b=m.to_rgba(a)
    return [(i[0],i[1],i[2]) for i in b]

fig = plt.figure()
ax = plt.axes(projection='3d')
P=[(0,0,0),(2,0,0),(2,2,0),(0,2,0),(0,2,2),(2,2,2),(0,0,2)]
F=[[0,1,2,3],[2,3,4,5],[0,3,4,6]]

x = [t[0] for t in P]
y = [t[1] for t in P]
z = [t[2] for t in P]

pc=[[P[i] for i in f] for f in F]

fz=getFaceMidpointsZ(pc)

q = Poly3DCollection(pc, linewidths=1)
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array([min(z),max(z)])
m.set_clim(vmin=min(z),vmax=max(z))

q.set_facecolor(getColors(m,fz))
ax.add_collection3d(q)

fig.colorbar(m)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_xlim(min(x),max(x))
ax.set_ylim(min(y),max(y))
ax.set_zlim(min(z),max(z))

ax.view_init(elev=18., azim=-43.)
plt.show()

I am starting to learn Python and Matplotlib, so any comments would be appreciated.


texts: Determining the largest sum of contiguous integers in a list

texts:
I'm curious how I can improve the readability of this short program I wrote. Mainly, if and how there is a way to remove the for loops and maybe refactor the getTruncatedSubListsOf methods to one method since they are pretty similar. I tried using comments only when clarification was necessary.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;

/**
 *  A program to determine the largest sum of contiguous integers in a list.
 *  The first argument is a path to a filename containing a comma-separated list of integers, one per line.
 *  The largest sum is printed to stdout. In other words, of all the possible contiguous subarrays for a given array,
 *  the one with the largest sum is found and printed.
 */
public class SumOfIntegers {

    public static void main(String[] args) throws IOException {

        Files.newBufferedReader(Paths.get(args[0])).lines()
                                                    .map(SumOfIntegers::turnToIntegerList)
                                                    .map(SumOfIntegers::getAllContiguousSubarrays)
                                                    .map(SumOfIntegers::getSumsOfSubarrays)
                                                    .mapToInt(Collections::max)
                                                    .forEach(System.out::println);
    }

    private static List<Integer> turnToIntegerList(String line) {

        return asList(line.split(",")).stream()
                                      .map(Integer::valueOf)
                                      .collect(toList());
    }

    /**
     * Returns all possible contiguous subarrays for a given List. This method calls getEndTruncatedSubListsOf each
     * different frontTruncatedSubList, yielding all possible front and end truncated lists - which are all subarrays.
     * @param integerList A List containing Integer values.
     * @return A List of all subarrays as Lists.
     */
    private static List<List<Integer>> getAllContiguousSubarrays(List<Integer> integerList) {
        List<List<Integer>> result = new ArrayList<>();

        for (List<Integer> frontTruncatedSubList : getFrontTruncatedSubListsOf(integerList)) {
            result.addAll(getEndTruncatedSubListsOf(frontTruncatedSubList));
        }

        return result;
    }

    private static List<List<Integer>> getFrontTruncatedSubListsOf(List<Integer> list) {
        List<List<Integer>> result = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            result.add(list.subList(i, list.size()));
        }

        return result;
    }

    private static List<List<Integer>> getEndTruncatedSubListsOf(List<Integer> list) {
        List<List<Integer>> result = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            result.add(list.subList(0, list.size() - i));
        }

        return result;
    }

    private static List<Integer> getSumsOfSubarrays(List<List<Integer>> subarrays) {
        return subarrays.stream()
                .map(subsubarray -> subsubarray.stream()
                                                .mapToInt(integer -> integer)
                                                .sum())
                .collect(toList());
    }

}


texts: Did I convert this C++ class to Common Lisp correctly?

texts:
Here is the original C++ class I converted to Lisp at the very bottom of this post.

class TrainingData
{
public:
    TrainingData(const string filename);
    bool isEof(void) { return m_trainingDataFile.eof(); }
    void getTopology(vector<unsigned> &topology);

    // Returns the number of input values read from the file:
    unsigned getNextInputs(vector<double> &inputVals);
    unsigned getTargetOutputs(vector<double> &targetOutputVals);

private:
    ifstream m_trainingDataFile;
};

It is a class from a C++ Neural Network I am converting to Common Lisp. The entire 400 line Neural Net is here.

Below is the conversion I came up with.  Based on the Neural Network I linked above, can anyone tell me if I converted the C+ class, above, correctly with the following Lisp code?  I'd rather have a little assurance before I start converting the entire 400 lines.

(defclass training-data ()
  ((training-data-stream :reader training-data-stream
                         :writer |set training data stream (using a funky name)|
                         :initarg :training-data-stream))
  )

;;; initialize-instance :after -- This is your 'constructor' code.

(defmethod initialize-instance :after ((td training-data)
                                       &key
                                       training-data-stream
                                       &allow-other-keys)
  ;; Initialize the slot.

  ;; Note that 'opening' a stream, as it is implied by the C++ class
  ;; definiton and leaking the open stream handle is very impolite.

  (let ((is (etypecase training-data-stream
              ((string pathname) (open training-data-stream :direction :input))
              (stream (if (input-stream-p training-data-stream)
                          training-data-stream
                          (error "Not an input stream.")))))
        )
    (|set training data stream (using a funky name)| is td)
    ))

(defgeneric is-eof (td)
  (:method ((td training-data))
   ;; Are you sure you want this method?
   ))

EDIT:  As far as tests go, please let me explain:

Due to the fact I'm just a intermediate at Linear Algebra I had a wee bit of a time understanding Neural Networks.  This conversion into Lisp is the way I figured out how to figure out what Neural Networks do.  I'm best at Lisp, pretty good at C, and sort of good at C++, so I'm trying to learn Neural Networks by converting a C++ nn to Lisp.

I don't have enough info to test any specific piece of the code I posted here or at the link yet.  I'm still in the process of learning std::stringstream and I've just learned what bitwise XOR was.  I can post the instructions that tell how to run the C++ nn at the link in its entirety, and the code to create the data file for it, so you can see how it runs or explain how the incomplete snippet I posted ties in with the rest of the code.  The incomplete member functions I added in this post have completed counterparts within the rest of the code at the link I just added.


texts:
I'm looking for the best and fastest way to do a determinant, for determinants until 15x15.

int Determinant(const vector<vector<int> > &a,int n)
{
   int i,j,j1,j2;
   int det = 0;
   vector<vector<int> > m(n, vector<int>(n));

    if (n == 1) { /* Shouldn't get used */
      det = a[0][0];
   } else if (n == 2) {
      det = a[0][0] * a[1][1] - a[1][0] * a[0][1];
   } else {
      det = 0;
      for (j1=0;j1<n;j1++)
      {
         for (i=1;i<n;i++)
         {
            j2 = 0;
            for (j=0;j<n;j++)
            {
               if (j == j1)
                  continue;
               m[i-1][j2] = a[i][j];
               j2++;
            }
         }
         det += pot(-1,1+j1+1) * a[0][j1] * Determinant(m,n-1);
      }
   }
   det = abs(det)%2;
   return det;
}


texts: Python code to split csv into smaller csvs, not splitting IDs

texts:
I have Python code that splits a given large csv into smaller csvs. This large CSV has an ID column (column 1), which consecutive entries in the csv can share. The large csv might look something like this:

sfsddf8sdf8, 123, -234, dfsdfe, fsefsddfe
sfsddf8sdf8, 754,  464, sdfgdg, QFdgdfgdr
sfsddf8sdf8, 485,  469, mgyhjd, brgfgrdfg
sfsddf8sdf8, 274, -234, dnthfh, jyfhghfth
sfsddf8sdf8, 954, -145, lihgyb, fthgfhthj
powedfnsk93, 257, -139, sdfsfs, sdfsdfsdf
powedfnsk93, 284, -126, sdgdgr, sdagssdff
powedfnsk93, 257, -139, srfgfr, sdffffsss
erfsfeeeeef, 978,  677, dfgdrg, ssdttnmmm
etc...

The IDs are not sorted alphabetically in the input file, but consecutive identical IDs are grouped together.

My code does not split the IDs into different csvs, ensuring that each id appears in only one output csv.

My code is:

import pandas as pd
import os

def iterateIDs(file): #create chunks based on tripID
    csv_reader = pd.read_csv(file, iterator=True, chunksize=1, header=None)
    first_chunk = csv_reader.get_chunk()
    id = first_chunk.iloc[0,0]
    chunk = pd.DataFrame(first_chunk)
    for l in csv_reader:
        if id == l.iloc[0,0] or len(chunk)<1000000: #Keep adding to chunk if less than 1,000,000, or in middle of trip
            id = l.iloc[0,0]
            chunk = chunk.append(l)
            continue
        id = l.iloc[0,0]
        yield chunk
        chunk = pd.DataFrame(l)
    yield chunk

waypoint_filesize = os.stat('TripRecordsReportWaypoints.csv').st_size #checks filesize

if waypoint_filesize > 100000000: #if file too big, split into seperate chunks
    chunk_count = 1
    chunk_Iterate = iterateIDs("TripRecordsReportWaypoints.csv")

    for chunk in chunk_Iterate:
        chunk.to_csv('SmallWaypoints_{}.csv'.format(chunk_count),header=None,index=None)
        chunk_count = chunk_count+1

However, this code runs very slowly. I tested it on a small file, 284 MB and 3.5 million rows, however it took over an hour to run. Is there any way I can achieve this result quicker? I don't mind if it's outside of python.