texts: Graph: Depth First Search (N citizens with pairs of friends)

texts:
I have solved problem 10608 on UVA Online Judge using Python 3.5.1. My solution works, but it takes too long to run when the online judge evaluates it.
Problem
There is a town with N citizens. It is known that some pairs of people are friends. According to the famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends
and B and C are friends then A and C are friends, too.
Your task is to count how many people there are in the largest group of friends.
Input
Input consists of several datasets. The first line of the input consists of a line with the number of test
cases to follow.
The first line of each dataset contains tho numbers N and M, where N is the number of town’s
citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known
to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N,
A ̸= B) which describe that A and B are friends. There could be repetitions among the given pairs.
Output
The output for each test case should contain (on a line by itself) one number denoting how many people
there are in the largest group of friends on a line by itself.
Sample Input
2
3 2
1 2
2 3
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 1
1 2
9 10
8 9

Sample Output
3
7

testCases = int(input())

for x in range(testCases):
    temp = input().split()
    N = int(temp[0])
    M = int(temp[1])

    nodes = []
    edges = []
    for _ in range(M):
        temp = input().split()
        A = int(temp[0])
        B = int(temp[1])
        edges.append([A, B])

    counter = 0
    for y in range(N):
        counter += 1
        nodes.append(counter)

    hashmap = {}
    for h in range(len(nodes)):
        neighbours = []
        for j in range(len(edges)):
            if edges[j].__contains__(nodes[h]):
                index_of_node = edges[j].index(nodes[h])
                if index_of_node == 0:
                    neighbours.append(edges[j][1])
                    hashmap[h + 1] = neighbours
                else:
                    neighbours.append(edges[j][0])
                    hashmap[h + 1] = neighbours
    current_group = 0
    highest_group = 0

    def reset_array():
        visited = []
        for _ in range(1, N + 2):
            visited.append(False)
        return visited

    visited = reset_array()

    def dfs(at):
        if visited[at]:
            return
        else:
            visited[at] = True
            global current_group
            current_group += 1
        if at in hashmap:
            neighbours = hashmap[at]
            for next in neighbours:
                dfs(next)
        else:
            return

    counter = 0
    for i in range(len(nodes)):
        dfs(i + 1)
        if current_group > highest_group:
            highest_group = current_group
        visited = reset_array()
        current_group = 0

    print(highest_group)


texts: Python Decorator - inspecting function argument values

texts:
Some of my functions use a "fail_silently" flag.  It is used in the following way:

def test(a, b, c=1, fail_silently = False)
    try:
        return int(a) + c
    except:
       if fail_silently:
           return None
       raise

Therefore, if there is an error, we catch it and fail gracefully. The key here is that it can be toggled dynamically by whoever is calling it.

I am using this for a many different functions and class methods and thought to make it a decorator.

There are a few problems:

I want to be able name the flag "raise_exception" or "fail_silently" or "whatever"...
The flag may or may not have a default value
The flag may or may not be passed in (usually not)
It needs to work with class methods too

Thus my decorator needs to look for (assuming the flag is called "fail_silently")
the flag in the following locations in this order

**kwargs (the passed in function arguments), simple dictionary get on flag
*args - get the positional argument of the flag, then scan for index in args (which might not be there)
Get the default value of the flag from the function

The problem is the code is now getting really messy and has many points of failure.

def try_except_response(parameter = 'fail_silently'):
    def real_decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs) # the function itself,
            except: # if it raises an Exception!
                # check to see if the Flag is in passed in kwargs!
                if kwargs.get(parameter)== True:
                    return None
                elif kwargs.get(parameter) == False:
                    raise
                else:
                    # Flag is not in kwargs, check to see if it is in args
                    function_args, vargs, kewords, defaults = inspect.getargspec(func) # get the index of argument of interest
                    try:
                        argument_index = function_args.index(parameter)  # get the index of argument of interest
                    except ValueError:
                        raise ValueError('The inputted decorator for "fail_silently" was not found!  The behavior will not work.')

                    if len(args) > argument_index: # check to see if it is inputted

                        keyword = args[argument_index] # get the value!!
                        if keyword == True:
                            return None
                        elif kwargs == False:
                            raise
                        else:
                            raise ValueError('The "fail_silently" flag did not return a value that we understand.  Must be True or False')

                    else:
                        # not in args either! let's go get the default value.
                        # TODO MORE STUFF!!!
                        raise
                    raise
                raise
        return wrapper

What is the best way this can be cleaned up?  Or alternatives?  I am thinking about implementing a version of locals() that will create a dictionary of all parameters passed into the function and then check from there...

There are simplifying assumptions we can make, but that would require the person writing the function to know something ('flag is always last argument, or default value is always False...'), but I am hoping to get the decorator to be as transparent as possible so it just "works" and lets the function be a function (or class method)


texts:
I stumbled on this SO question which was asking about a way to convert larger hex values to a positive numeric value:

?Val("&H8000")
 -32768
Val("&HFFFF")
 -1

My answer involved iterating the string digits one by one, and computing their respective value into the result:

Function ConvertHex(ByVal value As String) As Double

    If Left(value, 2) = "&H" Then
        value = Right(value, Len(value) - 2)
    End If

    Dim result As Double

    Dim i As Integer, j As Integer
    For i = Len(value) To 1 Step -1

        Dim digit As String
        digit = Mid$(value, i, 1)

        result = result + (16 ^ j) * Val("&H" & digit)
        j = j + 1

    Next

    ConvertHex = result

End Function

It works, but I can't help thinking I've done something stupidly over-complicated for something that should be pretty simple.

There's a better way, isn't there?


texts: Golang visitor pattern for marshaling shapes as JSON, and XML

texts:
I was trying to implement visitor pattern in Golang, and came across an idea of using a generic func type instead if interface as visitor. Here is my code:

package main

import (
    "encoding/json"
    "encoding/xml"
    "fmt"
)

type Visitor func(shape Shape)

type Shape interface {
    accept(Visitor)
}

type Circle struct {
    Rad int
}

func (c Circle) accept(v Visitor) {
    v(c)
}

type Line struct {
    Length int
}

func (l Line) accept(v Visitor) {
    v(l)
}

func JsonVisitor(shape Shape) {
    bytes, err := json.Marshal(shape)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(bytes))
}

func XmlVisitor(shape Shape) {
    bytes, err := xml.Marshal(shape)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(bytes))
}

func main() {
    circle := Circle{12}
    line := Line{42}
    circle.accept(JsonVisitor)
    line.accept(JsonVisitor)

    circle.accept(XmlVisitor)
    line.accept(XmlVisitor)
}

Besides the code review I have a question: is it still considered a Visitor pattern if using one generic function for all the Shapes?


texts: Speeding up my implementation of Project Euler #3

texts:
Project Euler problem 3 asks for the largest prime factor of 600851475143.

I have gone from 96 lines to 17 lines taking hits at this one.  This is what I am left with after all of that effort:

public class IntegerFactoriseFive {

    public static void main(String[] args)
    {
        long n = 600851475143L;
        for (long i = 2; i <= n; i++)
        {
            if (n % i==0)
            {
                System.out.println(i);
                n = n / i;
                i = 2;
            }
        }
    }
}

Is there any way to make it faster?

I'm not suggesting that it isn't quick enough already, but for the sake of it and for improving the way I tackle problems in the future. My other solutions were taking forever.  I was using recursion, and I even only iterated up to the square root of the numbers I was checking (from early school maths I know to only check up to the square root, it is a lot quicker), but it was still to slow.  In the end, iterating by one and dividing this huge number was the wrong way to go about it, so instead, I figured that dividing the number as much as possible was the only way I could do it in any good time.

Please offer suggestions.  As you can see by the class name, it is my fifth official solution for it that is the quickest of the ones I came up with.


texts:
I am trying to create an area graph from the upper and lower limit values.

First I created two line graph from those points as:

Sample data points are:

 var line1dataPoints:[CGPoint] = [CGPoint(x: 10, y: 120),CGPoint(x: 20, y: 130),CGPoint(x: 20, y: 120),CGPoint(x: 70, y: 130),CGPoint(x: 70, y: 120),CGPoint(x: 80, y: 130),CGPoint(x: 90, y: 120),CGPoint(x: 100, y: 110),CGPoint(x: 120, y: 120),CGPoint(x: 120, y: 130)]
 var line2dataPoints:[CGPoint] =  [CGPoint(x: 10, y: 170),CGPoint(x: 20, y: 180),CGPoint(x: 20, y: 170),CGPoint(x: 70, y: 180),CGPoint(x: 70, y: 170),CGPoint(x: 80, y: 180),CGPoint(x: 90, y: 170),CGPoint(x: 100, y: 180),CGPoint(x: 120, y: 160),CGPoint(x: 120, y: 170)]

Method to create those line graphs are:

func addFirstLine(){

        let graphPath = UIBezierPath()
        graphPath.moveToPoint(line1dataPoints[0])

        for i in 1..<line1dataPoints.count {

            let nextPoint = line1dataPoints[i]
            graphPath.addLineToPoint(nextPoint)

        }
        let lineLayer = CAShapeLayer()
        lineLayer.lineWidth = 1.0
        lineLayer.path = graphPath.CGPath
        lineLayer.strokeColor = UIColor.blueColor().CGColor
        lineLayer.fillColor = UIColor.clearColor().CGColor
        self.view.layer.addSublayer(lineLayer)

    }

    func addSecondLine(){

        let graphPath = UIBezierPath()
        graphPath.moveToPoint(line2dataPoints[0])

        for i in 1..<line2dataPoints.count {

            let nextPoint = line2dataPoints[i]
            graphPath.addLineToPoint(nextPoint)

        }
        let lineLayer = CAShapeLayer()
        lineLayer.lineWidth = 1.0
        lineLayer.path = graphPath.CGPath
        lineLayer.strokeColor = UIColor.redColor().CGColor
        lineLayer.fillColor = UIColor.clearColor().CGColor
        self.view.layer.addSublayer(lineLayer)
    }

I created an area graph with the method as:

func createAreaGraph(){

    let rev = Array(line2dataPoints.reverse())
    line1dataPoints.appendContentsOf(rev)

    let graphPath = UIBezierPath()
    graphPath.moveToPoint(line1dataPoints[0])

    for i in 1..<line1dataPoints.count {

        let nextPoint = line1dataPoints[i]
        graphPath.addLineToPoint(nextPoint)

    }
    let lineLayer = CAShapeLayer()
    lineLayer.path = graphPath.CGPath
    lineLayer.fillColor = UIColor.grayColor().CGColor
    self.view.layer.addSublayer(lineLayer)
}

The results:

However, I am wondering if this is the right way to create an area graph or not.


texts:
How can I improve the performance (in terms of computation time) of this code?

# Settings
const nbloci = 100         # length of the genome
const N = 100              # Number individuals in the population
const nbgenerations = 100  # number of generations
const mu = 1/10^5          # mutation rate
const s = 0.01             # effect of a given mutation on fitness

# Packages
using Distributions.Binomial
using Distributions.wsample

# Type and Functions
type Ind
    Genome
end

function makepopulation(N)
    Pop = Array(Ind, N)
    for i = 1:N
        Pop[i] = Ind(ones(Float64, nbloci))
    end
    return(Pop)
end

function calculatefitnesses(Pop)
    fitnesses = Array(Float64, N)
    for (i,I) = enumerate(Pop)
        fit = 1
        for l = I.Genome
            fit *= l
        end
        fitnesses[i] = fit
    end
    return(fitnesses)
end

function mutate(I)
    nbmut = rand(Binomial(nbloci, mu), 1)[1]
    mutposs = rand(1:nbloci, nbmut)
    for mutpos = mutposs
        I.Genome[mutpos] == 1.0 ? I.Genome[mutpos] = mutfit : I.Genome[mutpos] = 1.0
    end
end

function reproduce(Pop)
    fitnesses = calculatefitnesses(Pop)
    newPop = Array(Ind, N)
    for i = 1:N
        newPop[i] = deepcopy(wsample(Pop, fitnesses, 1)[1])
        mutate(newPop[i])
    end
    return(newPop)
end

##### MAIN #####

# Just a useful constant
const mutfit = 1.0-s

# Simulation
Pop = makepopulation(N)             # Create population
for generation = 1:nbgenerations    # Iterate over all generations
    Pop = reproduce(Pop)
end

The above code simulates a population of individuals (Ind) that all have a genome long of nbloci (independent) loci (a locus (=sing. of loci) is a position on a chromosome). makepopulation creates a population of clones at the beginning of the simulation. Then, iterating over all generations (for loop) the function reproduce is called on the population. The function reproduce calls calcfitnesses who return an array of fitnesses. reproduce sample the individuals according to fitnesses and then mutate the sampled individuals by calling the function mutate. After reproducing, all individuals die (no overlap of generations).

In mutate, each locus has a probability mu of mutating. In calcfitness an individual that has for example 8 mutant alleles (allele=variant of a gene) has a fitness of (1-s)^8. In reproduce, individuals are chosen to reproduce with some probability given by their fitness. N designates the population size and nbgenerations obviously designates the number of generations to simulate.

My main doubts and questions

The calcfitness function might eventually be improved by first counting the number of mutants and then using a power function to calculate the fit of an Ind. In such case, I may eventually want to code True/False instead of the Float64 objects 1.0/1.0-s in their genome. I could as well have an Array where at position i is the fitness of on individual that has i mutations. What do you think would be the best solution?
I feel like I used lots of functions and an eventually unnecessary type. It has the advantage to make the code easier to read, but does it significantly slow down the simulations?
I am not 100% sure about the use of the const prefix in my settings either. Would I be better off passing all these settings to each function instead of defining them as constant?
There might have a better solution than deep-copying all individuals forming the next generation. Would it be better to sample them all first and then to deep-copy only the individuals that has been sampled more than once?


texts: Interpolating given value and legacy value from serialization buffer

texts:
Here's a function that interpolates between a given value and a value fetched out of a legacy serialization buffer:

template<typename T>
T interpolate(Buffer& buffer, const T currentValue, const float prop)
{
    T bufferValue;
    buffer.readT(&buferValue);
    return currentValue + (bufferValue-currentValue)*prop;
}

This works great for interpolate<float> and interpolate<int> and so on. However if I want to pass a more complex structure such as a vector, I'd rather the currentValue parameter was passed by reference instead of by value.  I can use overloading to handle that situation:

// in addition to original function
Vector interpolate(Buffer& buffer, const Vector& currentValue, float prop)
{
    Vector bufferValue;
    buffer.readT(bufferValue);
    return currentValue + (bufferValue-currentValue)*prop;
}

Even if you rip out the lerp into a helper function, it still isn't ideal to repeat the function like this when the only difference from the original is the & parameter, especially if there's more than one type I'd like to pass by reference.

I can use traits to auto-detect when to use a reference:

// to replace original function

template<typename T>
struct RefTrait { typedef const T Ref; }

template<>
struct RefTrait<Vector> { typedef const Vector& Ref; }

template<typename T>
T interpolate(Buffer& buffer, typename RefTrait<T>::Ref currentValue, const float prop)
{
    T bufferValue;
    buffer.readT(&buferValue);
    return currentValue + (bufferValue-currentValue)*prop;
}

However now the compiler can't induce the type of T by default, and the calling code has to explicitly state type:

floatVal = interpolate<float>(buffer, floatVal, 0.5f);
vectorVal = interpolate<Vector>(buffer, vectorVal, 0.5f);

Is there anyway to have compact calling code as well as a single defined function?


texts: Prim algorithm implementation for adjacency list represented graph

texts:
Please review the implementation of Prim algorithm. Points on which I have doubt:

My Graph doesn't have any ID for nodes. Nodes are accessed based on their data. Is there any general approach in that? Should nodes be referenced by an ID as that will also make these algo somewhat easier to implement by using id as index into arrays.
With current graph representation, are there any issue in the algo implementation?
Are there any issues in method of accessing vertex and edges shared_ptr? Should weak_ptr be used at some places? Any shared_ptr validity issue?
Anything that you can suggest to improve will be helpful.

Vertex:

class Vertex {
public:
    Vertex() {
        bVisited = false;
    }
    int data = 0;
    EdgeList edgeList;
    bool bVisited = false;
};

Edge:

struct Edge {
    int cost;
    boost::weak_ptr<Vertex> srcVertex;
    boost::weak_ptr<Vertex> dstVertex;
};

Graph:

typedef std::list<boost::shared_ptr<Vertex>> VerticesList;
typedef std::map<int, VerticesList::const_iterator> DataVertexMap;
class Graph {

    VerticesList _verticesList;
    DataVertexMap _dataVertexMap;

    //TODO: Need some design to have this function internal only and not exposed to client
    boost::shared_ptr<Vertex> addAndGetVertex(int data);
public:
    Graph();
    ~Graph();

    bool isEmpty() const;
    //We don't check for duplicate vertex
    void addVertex(int data);
    void addEdge(int srcData, int dstData, int cost);
    int getCostForEdge(int srcData, int dstData);
    void displayGraph();
    void dfsTraversal();
    void bfsTraversal();

    void findShortestPath(int srcData, int dstData);
    void kruskalMST();
    void primMST();
};

Prim's implementation:

 //return min cost edge
 boost::shared_ptr<Edge> getMinEdge(const EdgeList& edgeList) {
    int min = INFINITY;
    boost::shared_ptr<Edge> minEdge;
    for(boost::shared_ptr<Edge> edge : edgeList) {
        if(edge->cost < min) {
            min = edge->cost;
            minEdge = edge;
        }
    }

    return minEdge;
}

void Graph::primMST() {
    EdgeList mstEdgeList;
    EdgeList potentialEdgeList;

    //insert edges for first vertex
    boost::shared_ptr<Vertex> firstVertex = _verticesList.front();
    potentialEdgeList.insert(potentialEdgeList.begin(), firstVertex->edgeList.begin(), firstVertex->edgeList.end());

    while(mstEdgeList.size() < _verticesList.size() - 1) {
        boost::shared_ptr<Edge> minEdge = getMinEdge(potentialEdgeList);
        mstEdgeList.push_front(minEdge);
        potentialEdgeList.remove(minEdge);
        //Mark the vertices visited so that edge having them as destination are not again included
        (minEdge->srcVertex).lock()->bVisited = true;
        (minEdge->dstVertex).lock()->bVisited = true;
        EdgeList& dstVertexEdgeList = (minEdge->dstVertex).lock()->edgeList;
        for(boost::shared_ptr<Edge> edge : dstVertexEdgeList) {
            if(!(edge->dstVertex).lock()->bVisited)
                potentialEdgeList.push_front(edge);
        }
    }

    //TODO: set all bVisited false

    // print the contents of result[] to display the built MST
    printf("Following are the edges in the constructed MST\n");
    for (boost::shared_ptr<Edge> edge : mstEdgeList)
        printf("%d -- %d == %d\n", (edge->srcVertex).lock()->data, (edge->dstVertex).lock()->data,
               edge->cost);
    return;
}


texts: Codeigniter 3 loading models in a different way

texts:
I'm currently building an application that uses the same models in different controllers. Instead of using the normal way, being loading the model in the controller I've build a "core controller" (Foundation_controller) which can load models all other controllers extend from this controller in a way.

In those extended controllers I load my model the following way:

PHP Code: an example controller extends from Foundation

class Mod_controller extends Foundation_controller
{
 private $list_model;
 public function __construct()
    {
       parent::__construct();
       #function from foundation_controller
       $this->list_model = $this->load_model('list_model', true, false);
     }
 private function get_full_list(){
   $this->list_model->get_list_info();
 }
}

PHP Code: Foundation controller

#Function to load the models from foundation controller

protected function load_model($model_id, $mandatory = false, $die_on_fail = false)
{

    $model_data = $this->get_model_info($model_id);

    if(empty($model_data['model_alias']) || empty($model_data['model_path'] || empty($model_data['model_class_name']))
    ){
        #outputs simple json fail object..
        api_message_present_simple_failure_message('mi-error-01: ' . $model_id);
    }

    if ($this->model_did_load_check($model_data['model_class_name'])) {
        #model is already loaded return the object
        return $this->get_model_object_from_alias($model_data['model_alias']);
    }

    if ($this->check_model_php_file_exists($model_data['model_path'])) {
        #load the model here based on file path and alias.
        $this->load->model($model_data['model_path'], $model_data['model_alias']);
        if ($mandatory) {
            if (!$this->model_did_load_check($model_data['model_class_name'])) {
                if ($die_on_fail) {
                    #outputs simple json fail object..
                    api_message_present_simple_failure_message('mi-error-02: ' . $model_data['model_alias']);
                }
                return false;
            }
        }
    } else {
        if ($mandatory) {
            if ($die_on_fail) {
                #outputs simple json fail object..
                api_message_present_simple_failure_message('mi-error-03: ' . $model_data['model_alias']);
            }
            return false;
        }
    }
    #model successfully loaded return the object
    return $this->get_model_object_from_alias($model_data['model_alias']);
}

*It' might look confusing here because I load the model in the constructor, but in some controllers I load a specific model (or get the object) inside of a function or at a certain point in a process.

Everything works and fast but now I'm concerned this could lead to a potential security risk, since the models are being loaded "somewhat" globally.

Some models are in subfolders and some versions of the app require a different version of a model. Or don't have some model files at all. (Lite version)

The main thing is that each controller in the app extends from Foundation_controller to use the load function, some controllers are being used for pages with "public" access and others are behind a authenticated users part. The main reason why I have the load_model function is that I don't want to repeat code to check if the model file exists, a particular function exists and that the class has already loaded. Also this approach has less chance for typos and if a model path changes less work to refactor.

Now I have doubts that this is secure, and I wonder if this can pose a security risk of any kind.


texts:
I wrote some code to parse Lua 5.2 strings in Lua 5.1, using patterns. It works perfectly as far as I tested.

local squote = "'"
local dquote = '"'

-- escape "sequences"
local escapeSequences = {
  a = '\a',
  b = '\b',
  f = '\f',
  r = '\r',
  n = '\n',
  t = '\t',
  v = '\v',
  ['"'] = '"',
  ["'"] = "'",
  ['\\'] = '\\'
}

local pads = {
  z = "\\z",
  x = "\\x",
  ['0'] = '\\0',
  ['1'] = '\\1',
  ['2'] = '\\2',
  ['3'] = '\\3',
  ['4'] = '\\4',
  ['5'] = '\\5',
  ['6'] = '\\6',
  ['7'] = '\\7',
  ['8'] = '\\8',
  ['9'] = '\\9'
}

setmetatable(pads, {
    __index = function(t,k)
      return "\\v" .. k .. "/"
    end
  })

-- Parse a string like it's a Lua 5.2 string.
local function parseString52(s)
  -- "validate" string
  local startChar = string.sub(s,1,1)
  assert(startChar==squote or startChar==dquote)
  assert(string.sub(s, -1, -1) == startChar)

  -- remove quotes
  local str = string.sub(s, 2, -2)

  -- TODO check for unescaped quotes

  -- replace "normal" escapes with a padded escape
  str = string.gsub(str, "\\(.)", function(c)
      -- swap startChar with some invalid escape
      if c == startChar then
        c = "m"
        -- swap the invalid escape with startChar
      elseif c == "m" then
        c = startChar
      end
      return pads[c]
    end)

  -- check for a padded escape for startChar - remember this is actually our invalid escape
  assert(not string.find(str, "\\v" .. startChar .. "/"), "invalid escape sequence near '\\m'")

  -- then check for non-escaped startChar
  assert(not string.find(str, startChar), "unfinished string")

  -- pad 1-digit numerical escapes
  str = string.gsub(str, "\\([0-9])[^0-9]", "\\00%1")

  -- pad 2-digit numerical escapes
  str = string.gsub(str, "\\([0-9][0-9])[^0-9]", "\\0%1")

  local t = {}
  local i = 1
  local last = 1
  -- split on \z
  for from,to in function(x,y) return string.find(x, "\\z", y+1) end, str, 0 do
    t[i] = string.sub(str, last, from - 1)
    last = to+1
    i = i + 1
  end
  t[i] = string.sub(str, last, #str)

  -- parse results
  local nt = {}
  for x,y in ipairs(t) do
    nt[x] = string.gsub(y, "\\(([vx0-9])((.).))",
      function(a,b,c,d)
        if b == "v" then
          return escapeSequences[d] or (d == "m" and startChar or assert(false, "invalid escape sequence near '\\" .. d .. "'"))
        elseif b == "x" then
          local n = tonumber(c, 16)
          assert(n, "hexadecimal digit expected near '\\x" .. c .. "'")
          return string.char(n)
        else
          local n = tonumber(a)
          assert(n < 256, "decimal escape too large near '\\" .. a .. "'")
          return string.char(n)
        end
      end)
    if x > 1 then
      -- handle \z
      nt[x] = string.gsub(nt[x], "^[%s]*", "")
    end
  end
  -- merge
  return table.concat(nt, "")
end

return {
  parse52 = parseString52,
}

(For test cases see here, I decided to keep them separate so to not bloat up the post)

Things I'm not too sure about:

Should I use if not (condition) then error(msg) end instead of assert(condition, msg)? (Usually assertions are reserved for tests, but I'm not sure if this holds in Lua? I'm also not sure if assert() calls are JITted by LuaJIT.)

Should I return nil, msg instead of erroring?

Should I handle long strings?
Should I error if the unparsed string literal is smaller than the passed buffer? (That is, if you pass in something like [["<unparsed string literal>"<rest of buffer>]]) Or should I find the end of the string myself?

If so, should I return the end position?

Should I take an optional start position?
Can this be made faster?


texts: JavaScript responsive menu (dropdown/dropup)

texts:
I have the following front-end code for a responsive navigation menu which I thought using in my WordPress website.

Clicking the .burger element should cause adjacent .menu element to appear or disappear, in dropdown or dropup respectively, but without a breakpoint conflict such as this, which I suffer from:

We open a browser window <=959px and open the menu.
We resize the window to >=960px and then we resize back to <=959px.
We see that the menu is still open and isn't restarted.

Why I seek review

Many programmers advised me to take a pure CSS approach (no JavaScript) but in this case I create my markup with a WordPress page builder (Elementor) hence it feels inefficient to me. I also feel my JavaScript is too long and a bit confusing.

You might know a simpler and shorter (more methodal and more intuitive) pattern in vanilla JavaScript available in 2018 (ES6/ES7?) or in jQuery 3.x.x.

Code

document.addEventListener('DOMContentLoaded', ()=>{
    let clicks = 0;
    let menu = document.querySelector('#menu-primary');
    let burger = document.querySelector('.burger');
    let isMenuVisible = false;

    burger.addEventListener('click', ()=>{
      isMenuVisible = !isMenuVisible;
      menu.style.display = isMenuVisible ? 'block' : 'none';
    });

    let mobileBehavior = ()=>{
      menu.style.display = 'none';
    };

    if (window.innerWidth <= 959) {
      mobileBehavior();
    }

    window.addEventListener('resize', ()=>{
      if (window.innerWidth <= 959) {
        clicks = 1;
      } else if (window.innerWidth >= 960) {
        menu.style.display = 'block';
      }
    });
});
.burger {display: block; text-align: center; color: var(--w); margin-bottom: 0 !important; font-weight: bold}
#menu-primary {display: none}

@media screen and (min-width: 960px) {
 .burger {display: none}
 #menu-primary {display: block}
}

BARS

Homepage

Contact_us

Update

I reported a problem with the code in this StackOverflow session; the problem is that the code can conflict with some page builders and does conflict with Elementor WordPress-Drupal page builder, as described there.


texts: Usage of a C library in a C++ project (std::string char array conversion)

texts:
Abstract

I have little C/C++ skills.  I've learned programming mainly with Java, and so I chose C++ (targeting C++11) as the language to learn better. In my current C++ project, I have to use the discount C library for its Markdown functions.

To explain briefly my code: the member variable std::string markdown_ is the Markdown I want to "compile" to HTML. To do so, I have to use the following functions from discount:

MMIOT *mkd_string(char *string, int size, int flags);
int mkd_compile(MMIOT *document, int flags);
int mkd_document(MMIOT *document, char **doc);
mkd_css and mkd_toc are alike mkd_document

Questions

As you see, I need to copy the markdown_ string and make it a char*. To do so, I used a std::vector as suggested in Converting an std::string into a char array, but I would like to know if doing it this way is appropriate in my case, or if there are other ways to achieve that.
MMIOT *mkd_string(char *string, int size, int flags); is defined in the main page to return null on error. Is it correct to use nullptr like I do in the following code to check the return value?
Do you have suggestions to improve this code, or does it looks good?

Code extract

const std::string Markdown::error_msg_mkd_string = "libmarkdown failed to "
    "parse the following Markdown:\n";

void Markdown::compile()
{
    MMIOT* doc;
    int size;
    char *cstr_buff;
    int flags = MKD_TOC|MKD_SAFELINK|MKD_EXTRA_FOOTNOTE;

    std::vector<char> buff(markdown_.cbegin(), markdown_.cend());
    doc = mkd_string(&buff[0], buff.size(), flags);

    if(doc == nullptr)
        throw std::runtime_error(
            std::string(error_msg_mkd_string)
                .append(&buff[0], buff.size())
            );

    mkd_compile(doc, flags);

    // It is not a bad practice to reuse 'size' and 'cstr_buff' like in the
    // following code, or is it?
    size = mkd_css(doc, &cstr_buff);
    css_.assign(cstr_buff, size);

    size = mkd_document(doc, &cstr_buff);
    html_.assign(cstr_buff, size);

    size = mkd_toc(doc, &cstr_buff);
    toc_.assign(cstr_buff, size);

    mkd_cleanup(doc);
}


texts:
I have been teaching myself Python 3. I watched a video on YouTube entitled "stop writing classes". The Gtable class doesn't even have an init function, so I can't help but wonder if I should have done something different. Also as someone teaching themselves a language for the first time I would really appreciate any critique on how to write the code more efficiently, as well as any anti-idioms unintentionally used. Specifically I feel like there was probably a better way to generate the dictionaries, but especially with the first one I was having trouble writing a comprehension.

##input file text
##|HAAS T|TARGET T|XGEOM|ZGEOM
##$T0101$T0101$X22.960$Z20.0$
##$T0202$T0606$X32.425$Z7.376$
##$T0303$T0404$X30.588$Z15.620$
##$T0404$T0202$X22.367$Z18.549$
##$T0505$T0808$X33.291$Z8.197$

class GeometryTable(dict):
    "create a geometry table from a file for use in regexes"
    def __init__(self):
        self.d={}
    def create(self,location):
        f=open(location,'r')
        tablestring=f.read()
        f.close()
        tablelist=[]
        tablelist=tablestring.split('$')
        #delete unecessary data from list
        tablelist.pop(0)
        tablelist=[item for item in tablelist if item!='\n']
        #create a dictionary
        count=0
        keylist=[]
        valuelist=[]
        while count<len(tablelist):
            keylist.append(tablelist[count])
            valuelist.append([tablelist[count+1],tablelist[count+2],tablelist[count+3]])
            count+=4
        self.d=dict(zip(keylist,valuelist))
    def xval(self,string):
        if string in self.d:
            return (self.d[string][1])
        else:return(r"X20.0")
    def zval(self,string):
        if string in self.d:
            return (self.d[string][2])
        else:return(r"Z20.0")
    def tval(self,string):
        if string in self.d:
            return (self.d[string][0])
        else:return(r"T2020")
    def report(self,string):
        if string in self.d:
            return (self.d[string])
        else:return(r"(no value)")

class GTable(GeometryTable):
    """for replacing geometries that were given
       default values before this program was created"""
    def load(self,location):
        GeometryTable.load(self,location)
        b=self.__dict__["d"].values()
        redict={x[0]:x for x in b}
        self.d=redict

##output dictionaries for regular expressions
##>>> test.d
##{'T0101': ['T0101', 'X22.960', 'Z20.0'],
## 'T0202': ['T0606', 'X32.425', 'Z7.376'],
## 'T0303': ['T0404', 'X30.588', 'Z15.620'],
## 'T0404': ['T0202', 'X22.367', 'Z18.549'],
## 'T0505': ['T0808', 'X33.291', 'Z8.197']}


texts: Pythonic way to cast a dictionary into a pd.DataFrame with two columns?

texts:
I have a dictionary where for each key, a single value is stored. Say

import pandas as pd
dd = {'Alice': 40,
      'Bob': 50,
      'Charlie': 35}

Now, I want to cast this dictionary to a pd.Dataframe with two columns. The first column contains the keys of the dictionary, the second column the values and give the columns a name (Say "Name" and "Age"). I expect to have a function call like:

 pd.DataFrame(dd, columns=['Name', 'Age'])

which gives not desired output, since it only has 0 rows.

Currently I have two "solutions":

# Rename the index and reset it:
pd.DataFrame.from_dict(dd, orient='index', columns=['Age']).rename_axis('Name').reset_index()
pd.DataFrame(list(dd.items()), columns=['Name', 'Age'])

# Both result in the desired output:
    Name    Age
0   Alice   40
1   Bob     50
2   Charlie 35

However, both appear a bit hacky and thus inefficient and error-prone to me. Is there a more pythonic way to achieve this?


texts:
I am trying to merge JSON objects which have common values.

This is the original JSON:

{
    "setA":[
        {
            "setId":"setA"
            ,"prodId":"A"
            ,"price":"5"
            ,"delivertCost":"1"
            ,"name":"Set_Prod01"
        }

        ,{
            "setId":"setA"
            ,"prodId":"B"
            ,"price":"5"
            ,"delivertCost":"1"
            ,"name":"Set_Prod01"
        }
    ]
}

Since it has same setId and name, I want to make it like this:

{
    "setA": {
        "setId":"setA"
        ,"prodId":"A,B"
        ,"price":"5"
        ,"deliveryCost":3
        ,"name":"Set_Prod01"
    }
}

To do this, I made this JavaScript code, but it looks terrible and more elements have attributes with if else than needed.

function groupBy(coll, f) {
  return coll.reduce(function(acc, x) {
    var k = f(x);
    acc[k] = (acc[k] || []).concat(x);
    return acc;
  }, {});
}

var test = {
  items: [{
    setId: 'setA', prodId: "A", price: '5', deliveryCost : '1', name: "Set_Prod01"
  }, {
    setId: 'setA', prodId: "B", price :'5', deliveryCost : '2', name: "Set_Prod01"
  }]
};

console.log(JSON.stringify(test));

var result = groupBy(test.items, function(x){return x.setId});
//first grouping
console.log(JSON.stringify(result));

//begin spagetti code... T^T
var secondResult = {};
for(var key in result){
    var secondObjForSet = {};
    var setGroup = result[key];
    for(var i = 0; i < setGroup.length; i++) {
        var singleSetItem = setGroup[i];
        for(var innerKey in singleSetItem){
            if(innerKey == 'deliveryCost'){
                secondObjForSet[innerKey] = (typeof secondObjForSet[innerKey] === 'undefined') ? 0 + singleSetItem[innerKey] : (secondObjForSet[innerKey] * 1) + (singleSetItem[innerKey] * 1);
            }else if(innerKey == 'prodId'){
                secondObjForSet[innerKey] =
                    (typeof secondObjForSet[innerKey] === 'undefined' || secondObjForSet[innerKey] == '') ?
                        singleSetItem[innerKey] : secondObjForSet[innerKey] + ',' + singleSetItem[innerKey];
            }
            else{
                secondObjForSet[innerKey] = singleSetItem[innerKey];
            }
        }
    }
    secondResult[key] = secondObjForSet;
}

console.log(JSON.stringify(secondResult));

This is not flexible at all, so I need some help to make it more efficient.


texts: Encode object to JSON and encrypt with AES (with tests)

texts:
While the task at hand is relatively straightforward, it turned out AES in Go is a bit clunky so I was wondering if this seems right. Also, any tips on Go coding in general are more than welcome.

// Package aesjson provides a function to encode an object to JSON and apply
// AES encryption to it.
package aesjson

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "encoding/json"
    "io"
    "log"
)

const (
    aesKey = "U3RhY2tPdmVyZmxvdyBmb3IgdGhlIHdpbiEgICAgICA="
)

var (
    aesCipher cipher.Block
)

func init() {
    aesKeyDecoded, err := base64.StdEncoding.DecodeString(aesKey)
    if err != nil {
        log.Fatalln(err)
    }
    aesCipher, err = aes.NewCipher(aesKeyDecoded)
    if err != nil {
        log.Fatalln(err)
    }
}

func spaces(c int) []byte {
    return bytes.Repeat([]byte(" "), c)
}

// EncodeJSON encodes the given object to JSON (via json.Marshal) and then
// encrypts it using the AES encryption algorithm.
// It returns the base64 of the encrypted JSON with the IV prepended to it.
func EncodeJSON(val interface{}) (string, error) {
    valjs, err := json.Marshal(val)
    if err != nil {
        return "", err
    }
    paddingLen := 16 - len(valjs)%16
    text := append(valjs, spaces(paddingLen)...)

    ciphertext := make([]byte, aes.BlockSize+len(text))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        return "", err
    }

    mode := cipher.NewCBCEncrypter(aesCipher, iv)
    mode.CryptBlocks(ciphertext[aes.BlockSize:], text)
    return base64.StdEncoding.EncodeToString(ciphertext), nil
}

And this is my test file - really interested if this is the right approach to testing a function like this.

package aesjson_test

import (
    crand "crypto/rand"
    "log"
    "math/rand"
    "testing"

    "projectfolder/aesjson"
)

func init() {
    // Remove randomness
    crand.Reader = rand.New(rand.NewSource(1))

    log.Println("Randomness disabled!")
}

func TestEncode(t *testing.T) {
    input := &aesjson.Token{
        ID: "1234567890-1234567890",
    }
    want := "Uv38ByGCZU8WP18PmmIdcprw1O0tpU/WBGgDIBYBpYaoJ2Lay7VnJGhKzswMb7ndHORd4kaege0cnsKkHMogTA=="

    got, err := aesjson.EncodeJSON(input)
    if err != nil {
        t.Fatalf("failed with error: %v", err)
    }

    if got != want {
        t.Errorf("want: %q\ngot: %q", want, got)
    }
}


texts: Printing all even and odd numbers with threads

texts:
The original question is on careercup.

  Write a multi threaded C code with one thread printing all even numbers and the other all odd numbers. The output should always be in sequence
  ie. 0,1,2,3,4....etc

Now I want to use  C# for it.

class Program
{
    static Object obj = new Object();
    static Thread t1;
    static Thread t2;
    static LinkedList<int> a = new LinkedList<int>();
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            a.AddLast(i);
        }

        t1 = new Thread(PrintOdd);
        t2 = new Thread(PrintEven);
        t1.Name = "Odd";
        t2.Name = "Even";
        t1.Start();
        t2.Start();
        t1.Join();
        t2.Join();

        Console.WriteLine("Done!");
        Console.Read();
    }

    private static void PrintOdd()
    {
        while (true)
        {
            if (a.Count == 0)
                break;
            lock (obj)
            {
                int x = a.First();
                if (x % 2 != 0)
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                    a.RemoveFirst();
                }
            }
        }
    }

    private static void PrintEven()
    {
        while (true)
        {
            lock (obj)
            {
                if (a.Count == 0)
                    break;
                int x = a.First();
                if (x % 2 == 0)
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                    a.RemoveFirst();
                }
            }
        }
    }
}

Any improvements?


texts: Aggregating values of a path-dependent type

texts:
I have a type representing an immutable order which contains immutable order lines that belong to it. I want to use path-dependent types for this. Obviously you cannot instantiate a path-dependent type without having the value it depends on, so I decided to take a function from the constructor. Since (order: Order) => Seq[order.OrderLine] is impossible, I use a simple structural type.

final class Order private() {
  case class OrderLine(x: Int, y: Double) { }

  def this(makeOrderLines: { def apply(order: Order): Seq[order.OrderLine] }) = {
    this()
    _orderLines = makeOrderLines(this)
  }

  private var _orderLines: Seq[OrderLine] = null
  def orderLines = _orderLines
}

object Main extends App {
  val order = new Order(new {
    def apply(order: Order) =
      Seq(order.OrderLine(1, 1.0), order.OrderLine(2, 2.0))
  })
  println(order.orderLines)
}

I find this approach very ugly. Especially not being able to use a lambda expression irks me (the lambda expression would return Seq[Order#OrderLine] instead of Seq[order.OrderLine] since it has be of type Function1[_, _] where path-dependent types are not possible).

Is there a better way of doing this?


texts: Splitting an Excel file into separate sheets by data

texts:
I have a VBA macro for a file of GPS data. It copies rows and subsequent rows to a new worksheet when the GPS data shows movement to the south.

It works fine, but is pretty slow on larger files (20,000 rows+). I'm looking for suggestions on how to speed it up.

The cell values in the macro are from another macro analyzing the GPS data. 1 means movement North, 2 means no movement, 3 means movement South. I could easily change these to different datatype if that would speed up this macro.

Sub SplitIntoGroups()

Application.ScreenUpdating = False

'The data is incomplete in the first 50 and last 50 rows, so this is so it doesn't analyze that data

Dim NearEnd As Integer
Dim NearStart As Integer
NearStart = 52
NearEnd = (Cells(Sheet1.Rows.Count, 3).End(xlUp).row) - 50

'Groups are the different sheets of data. I start with zero, because the first is usually unimportant

Dim Groups As Integer
Dim r As Integer

'GroupsCheck is the variable used to go through each row
Dim GroupsCheck As Integer

'WentNorth is a boolean to ensure there was movement to the north before creating a new sheet.
Dim WentNorth As Boolean

Sheets.Add.Name = "Group 0"
Groups = 0
'r is used as the row offset, so each row can be copied on the next row in the proper worksheet
r = 0

For GroupsCheck = NearStart To NearEnd

    If Sheets("Sheet1").Cells(GroupsCheck, "AB").Value = 1 Then WentNorth = True
    End if
    r = r + 1

    'once north movement (WentNorth=true) exists, a new sheet will be created when south movement first occurs (cells = 3 and previous cell <3)
        If Sheets("Sheet1").Cells(GroupsCheck, "AB").Value = 3 And Sheets("Sheet1").Cells(GroupsCheck - 1, "AB").Value < 3 And WentNorth = True Then
                Groups = Groups + 1
                Sheets.Add.Name = "Group " & Groups

                'once a new sheet is created, r and WentNorth are reset
                r = 0
                WentNorth = False
        End If

    'the copying function
    Worksheets("Sheet1").Range("A" & GroupsCheck & ": AB" & GroupsCheck).Copy Worksheets("Group " & Groups).Range("A2:AE2").Offset(r, 0)
Next GroupsCheck

Application.ScreenUpdating = True

End Sub


texts: Using callbacks in a Restangular service

texts:
I have a project built with AngularJS and using Restangular in my services to handle API requests. The problem is I haven't found a good way to test the services which I think has turned into a bit of a code smell for me. I'm using callbacks in the promise to handle pushing the data back to the controller instead of just returning the result.

Here is a simple controller and service:

myApp.controller('CustomerController', ['$scope', 'Teams', function($scope, Teams) {
    Teams.getList(function(results) {
        $scope.teams = result;
    });
}]);
myApp.factory('Teams', ['Restangular', function(Restangular) {
    var Teams = {};
    Teams.getList = function(callback) {
        Restangular.all('teams').getList().then(function(results) {
            callback(results);
        });
    };
    return Teams;
}]);

Is that really the best way to get the data back to the controller? I'm starting to feel like this isn't the correct way to do it but I haven't found another way that works.


texts: Font manager/loader class written in C++ (uses unordered_map)

texts:
This font manager is part of a game engine. It's supposed to mostly load fonts at the start, so I'm more worried about reading performance than loading performance. If there's any way of improving loading performance as well I'm happy to hear it.

How would I optimize this font manager or managers in general, and what is the best practices for doing so?
Is there any way of improving the use of the unordered_map container?
I'm also trying to write more modern C++ code. Is there anything that could be improved on that front as well?

Header file:

class FontManager {
public:
    static FontManager &Instance() {
        static FontManager singleton;
        return singleton;
    }

    const Font *LoadFont(const std::string fileName);
    void BatchLoadFonts(const std::vector<std::string>& infos);

    const Font *GetFont(const std::string& fileName);
private:
    FontManager() { }
    ~FontManager();
private:
    std::unordered_map<std::string, const Font*> m_Fonts;
};

.cpp file:

const Font *FontManager::LoadFont(const std::string fileName) {
    if (m_Fonts.count(fileName))
        return m_Fonts.at(fileName);

    m_Fonts.emplace(fileName, new Font(FONT_FOLDER_PATH + fileName));
    return m_Fonts.at(fileName);
}

void FontManager::BatchLoadFonts(const std::vector<std::string>& infos) {
    for (auto info : infos) {
        LoadFont(info);
    }
}

const Font *FontManager::GetFont(const std::string &fileName) {
    if (m_Fonts.count(fileName)) {
        return m_Fonts.at(fileName);
    }

    LoadFont(fileName);
    return m_Fonts.at(fileName);
}

FontManager::~FontManager() {
    for (auto const& f : m_Fonts) {
        delete f.second;
    }
}


texts: Calculating primes: Could this be any faster?

texts:
I've ported a prime-number calculation program from primes.pyx to C++ for benchmark purpose.
Since I wrote it in C++, I thought that my program would be faster than the original. However, mine took 25.8 ms at the fastest, while the original took only 1.45 ms on the same machine. I tested 10 times each, but got similar results (25.8~51.7ms vs 1.45~1.47ms). But, why?
Here's my code:
#include <iostream>
#include <vector>
#include <chrono>
using namespace std;

vector<int> primes(size_t nb_primes)
{
    int n;
    vector<int> p;
    p.reserve(nb_primes);

    n = 2;
    while (p.size() < nb_primes)
    {
        bool other = true;
        for (size_t i = 0; i < p.size(); i++)
        {
            if (n % p[i] == 0)
            {
                other = false;
                break;
            }
        }
        if (other)
            p.push_back(n);
        n += 1;
    }
    return p;
}

int main()
{
    auto start = std::chrono::high_resolution_clock::now();

    vector<int> p = primes(1000);
    //for (auto i : p)
    //    cout << i << ' ';

    auto finish = std::chrono::high_resolution_clock::now();

    std::chrono::duration<double> elapsed = finish - start;
    std::cout << "Elapsed Time: " << elapsed.count() << " s\n";
}

These algorithms are exactly the same, I believe.
Please don't limit the check up to sqrt(n), to achieve a sieve of Eratosthenes.
I need to compare with the original.
One thing I'm worried is the for ... else statement in the original.
I borrowed the idea to use the other flag from Username: haccks.
If you can apply another for ... else method, please go ahead.
My Windows 10 machine (i5) spec:
Clock Frequency: 1.60GHz 1.80GHz
Memory: 8.00GB
I wrote the original version on Anaconda Prompt/Python 3.8.
I write the C++ version on Visual Studio 2019.
If you need more information, please ask me.
Thank you in advance.


texts: Simple utility/convenience module - am I doing it right?

texts:
I have a large library (four packages) of data processing code that I have written over the last 12 months. I am quite new to python and would like to see if I am doing things correctly.

This utility/convenience code is currently kept in a module called utils that is imported in many places (for an example, see this question). I thought it would be a simple place to start as it has no dependency on my other code.

The purpose of the first two functions is to switch between cumulative energy meter readings and actual energy consumption values.

The second two functions allow me to move between datetime and timestamp values, usually because I store datetime information in numpy arrays of timestamps for some calculations but need them as datetimes for formatting.

The switching between gaps and flags is useful because data interpolation identifies missing data and records it as boolean numpy arrays (flags) but I often need to identify contiguous chunks of missing data.

import numpy as np, datetime, time, logging

def movement_from_integ(integ):
    return np.append(np.nan, np.diff(integ))

def integ_from_movement(movement):
    return np.append(0.0, np.cumsum(movement[1:]))

def timestamp_from_datetime(dt):
    return np.array([time.mktime(d.timetuple()) for d in dt])

def datetime_from_timestamp(ts):
    return [datetime.datetime.fromtimestamp(s) for s in ts]

def gaps_from_flags(flags, ts):
    logger = logging.getLogger('gaps_from_flags')
    """given missing flags and timestamps produces a list of contiguous gaps"""
    _gap = {'from': None, 'to': None}
    result = []
    for i in xrange(len(flags)):
        if not flags[i]:
            logger.debug(flags[i])
            if _gap['from'] != None:
                result.append(_gap)
                logger.debug('Gap saved [%s -> %s]' % (_gap['from'], _gap['to']))
                _gap = {'from': None, 'to': None}
        else:
            if _gap['from'] == None:
                logger.debug('%s: New gap initialised at %s' % (flags[i], ts[i]))
                _gap['from'] = ts[i]
            logger.debug('%s: Gap extended to %s' % (flags[i], ts[i]))
            _gap['to'] = ts[i]
    if _gap['from'] != None:
        result.append(_gap)
        logger.debug('Gap saved [%s -> %s]' % (_gap['from'], _gap['to']))
    return result

def flags_from_gaps(gaps, ts):
    """given gaps and timestamps produces an array of boolean values indicating whether data are missing at each timestamp"""
    flags = np.array([False]*len(ts), dtype=bool)
    for g in gaps:
        a = (ts >= g['from']) & (ts <=g['to'])
        flags[a] = True
    return flags

Is it OK to keep a set of functions like this in an otherwise object oriented project?

Am I doing the flags->gaps->flags processing in a sensible way?

I am aware there is such a thing as a masked array in numpy but I'm not sure how much work it would be to convert my entire code base over to using it.


texts: Better way to structure and optimise try except statements

texts:
I am new to python and I am trying to write a function with various actions based on the parameters sent. I am checking if the data has valid format then it publishes to /accepted otherwise to /rejected. If the data is fine then it does the function and then publishes to /success otherwise to /failure
Here is what i am doing now -
def data_handler(event, context):
    try:
        input_topic = context.topic
        input_message = event
        response = f'Invoked on topic {input_topic} with message {input_message}'
        logging.info(response)
        client.publish(topic=input_topic + '/accepted', payload=json.dumps({'state': 'accepted'}))
    except Exception as e:
        logging.error(e)
        client.publish(topic=input_topic + '/rejected', payload=json.dumps({'state': 'rejected'}))

    try:
        print('Perform the function based on input message')
        client.publish(topic=input_topic + '/success', payload=json.dumps({'state': 'Execution succeeded'}))
    except Exception as e:
        logging.error(e)
        client.publish(topic=input_topic + '/failure', payload=json.dumps({'state': 'Execution failed'}))

This works as of now but i think there should be a better way to implement this. Any idea?


texts: C code to reset all usb devices (because ubuntu laptop disables usb mouse after sleep)

texts:
I don't program much in c, but cobbled together some code from different places in google. I'm sure this is backwards especially in how it works with strings and directory files. Please let me know what the best practices would have been.
/* usbresetall -- reset all of the usb devices on bus 001 */

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>

#include <dirent.h>
#include <string.h>

#include <linux/usbdevice_fs.h>

int main(int argc, char **argv)
{
    int fd;
    int rc;

    DIR *d;
    char filename[256];
    struct dirent *dir;

    d = opendir("/dev/bus/usb/001/");
    strcpy(filename,"/dev/bus/usb/001/");

    if (d) {
        while ((dir = readdir(d)) != NULL) {
            strcat(filename,dir->d_name);
            printf("%s\n", filename);

        fd = open(filename, O_WRONLY);
        if (fd < 0) {
        perror("Error opening output file");
        } else {

        printf("Resetting USB device %s\n", filename);
        rc = ioctl(fd, USBDEVFS_RESET, 0);
        if (rc < 0) {
            perror("Error in ioctl");
        } else printf("Reset successful\n");

        close(fd);
            }

            strcpy(filename,"/dev/bus/usb/001/");
        }
        closedir(d);
    }

    return 0;
}


texts: Download and print reddit page which can be redirected to file

texts:
I wanted to save the a reddit thread to a .org file. I noticed that it is easier to use pandoc to convert .md to .org (esp when it comes to list items).
My code prints the output to the screen which can be redirected to the required file.
Process is as follows.
python reddit_download.py -u <url_to_download> > myfile.md
pandoc -s myfile.md -o myfile.org

My script
reddit_config.py
class Config:
    client_id = 'myID'
    client_secret = 'mySecret'
    password = 'my_password'
    user_agent = 'my_user_agent'
    username = 'my_username'

reddit_download.py
import argparse
import praw
from reddit_config import Config

def reddit():
    red = praw.Reddit(client_id=Config.client_id,
                      client_secret=Config.client_secret,
                      user_agent=Config.user_agent,
                      username=Config.username,
                      password=Config.password)
    return red

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--url', required=True, help='URL required', dest='url')
    return parser

def get_full_page(reddit_instance, url):
    post = reddit_instance.submission(url=url)

    page = [{
        # content of post
        "id": post.id,
        "parent": post.id,
        "body": post.selftext,
        "author": post.author.name,
        "ups": post.ups,
        "title": post.title
    }]

    # all comments/replies
    list_of_comments = post.comments.list()
    list_of_comments_with_desired_attributes = [{
            "id": comment.id,
            "parent": comment.parent_id.replace('t1_', '').replace('t3_', ''),
            "body": comment.body,
            "author": comment.author.name,
            "ups": comment.ups
        }
        for comment in list_of_comments
    ]

    page += list_of_comments_with_desired_attributes

    return page

def lookup(loc):
    comment_lookup = dict()
    for comment in loc:
        comment_id = comment["id"]
        if comment_id != comment["parent"]:
            parent_id = comment["parent"]
            children = comment_lookup.get(parent_id)
            if not children:
                children = comment_lookup[parent_id] = list()
            children.append(comment.copy())
        else:
            parent = comment.copy()
    return parent, comment_lookup

def hierarchy(parent_element, comment_lookup):
    parents = comment_lookup.get(parent_element["id"], list())
    for parent in parents:
        hierarchy(parent, comment_lookup)
    if parents:
        parent_element['children'] = parents
    return parent_element

def org(post_dict, parent_id, visited=None, depth=1):
    if visited is None:
        visited = set()
    visited.add(parent_id)
    print('#'*depth, post_dict.get('ups'), post_dict.get('author'), end='\n\n')
    title = post_dict.get('title')
    if title is not None:
        print(post_dict.get('title', ''), end='\n\n')
    print(post_dict.get('body'), end='\n\n')
    children = post_dict.get('children')
    if children is not None:
        for child in children:
            if child.get('id') not in visited:
                org(child, child.get('id'), visited, depth+1)
    return ''

if __name__ == '__main__':
    parser = parse_args()
    args = parser.parse_args()
    reddit = reddit()
    page = get_full_page(reddit, args.url)
    parent, comment_lookup = lookup(page)
    post = hierarchy(parent, comment_lookup)
    post_id = post.get('id')
    org(post, post_id)

Is there a way to improve this code? I am confused how to remove the print statements and build a string to write to a file. Effectively I don't have to redirect the output in shell to a file.


texts: My 'almostIncreasingSequence(sequence)' code is too slow for lists that have 10000+ elements. [CodeSignal]

texts:
I asked this question on Stackoverflow as well, but I think it's best suited here because my code needs optimization instead of error checking (that I previously thought).
I've made changes to my code as well. But the logic is pretty much the same:

My code first checks the length of the provided sequence, if it is 2 or less it automatically returns True.
Next, it creates a newlist with the first element removed and checks if the rest of the list is in ascending order.
If the sequence is not in order, the iteration breaks and a newlist is generated again and this time with the next element removed.
This continues until there are no more elements to remove (i.e. i == len(sequence) - 1), which ultimately returns as False
If in any of the iterations, the list is found to be in ascending order(i.e. in_order remains True), the function returns True.

def almostIncreasingSequence(sequence):
    # return True for lists with 2 or less elements.
    if len(sequence) <= 2:
        return True

    # Outerloop, removes i-th element from sequence at each iteration
    for i in range(len(sequence)):
        newlist = sequence[:i] + sequence[i+1:]

        # Innerloop, checks if the sequence is in ascending order
        j = 0
        in_order = True
        while j < len(newlist) - 1:
            if newlist[j+1] <= newlist[j]:
                in_order = False
                break
            j += 1
        if in_order == True:
            return True
        elif i == len(sequence)-1:
            return False

I received a suggestion that I should only use one loop, but I cannot think of a way to implement that. Nested loops seems necessary because of the following assumptions:

I have to remove every next element from the original sequence. (outer loop)
I need to check if all the elements are in order. (inner loop)

This is a brief on almostIncreasingSequence() my code follows the logic provided in the answer here, it solves almost all of the Tests as well, but it is too slow for larger lists (that are approx 10000+ elements).


texts: A dynamic string array that's loopable without requiring a count

texts:
Here's a dynamic loopable string array that doesn't require a count to be maintained at the caller level.

Definition

char **getList() {
    char **items = (char *[]) {"John", "Jane", NULL}; // dynamic/variable hard coded list

    int size = 0;
    for (char **ptr = items; *ptr; ptr++) { // count items
        size++;
    }

    char **data = malloc(sizeof(char *) * (size + 1));
    if (data == NULL) goto err;

    for (int i = 0; *items; items++, i++) { // copy
        data[i] = malloc(sizeof(char) * strlen(*items) + 1);
        if (data[i] == NULL) goto err;
        strcpy(data[i], *items);
    }

    data[size] = NULL; // last item
    return data;

    err:
    fprintf(stderr, "Allocation failed.\n");
    return NULL;
}

Caller

char **data = getList();
for (char **ptr = data; *ptr; ptr++) {
    puts(*ptr);
}
free(data);

Please review if this code can be improved upon for any redundancy or optimizations.


texts:
I'm developing a very basic product builder. Part of the builder has a basic text editor including some text color presets. As it stands, the presets remove a class that defines the text color and add in their own color class.

Looking at my code, it feels absurdly clunky and inefficient. I'm sure there has to be a better way to achieve what I'm working on, but I'm having a hard time figuring out even a starting point to research on what I would need to do to fix this.

$(".black-sel").click(function(){
  $("#prevTex").removeClass (function (index, css) {
    return (css.match (/\btextc-\S+/g) || []).join(' ');});
  $("#prevTex").addClass("textc-black");
});
$(".white-sel").click(function(){
  $("#prevTex").removeClass (function (index, css) {
    return (css.match (/\btextc-\S+/g) || []).join(' ');});
  $("#prevTex").addClass("textc-white");
});
$(".red-sel").click(function(){
  $("#prevTex").removeClass (function (index, css) {
    return (css.match (/\btextc-\S+/g) || []).join(' ');});
  $("#prevTex").addClass("textc-red");
});


texts: Entering information about a business and finding matches

texts:
I'm writing a Java Servlet application where the users must enter information about a business.  I'd like to prevent as many duplicate entries in the MySQL database as possible and I'd appreciate people's comments on the logic of the process.

When the user fills out the form and submits it, the business name and address are sent to a function which splits the address string, builds a query and queries the database for like-entries.  If there's no result or more than one result, the user's input gets cleaned up and stored.  If there's one result, the user's data is replaced by the existing business information.

private static List<Business> getBusinesses(String name, String address) throws ClassNotFoundException, SQLException {
    List<Business> businessList = new ArrayList<>();

    Connection conn = getConnection();

    //split the address for the where clause in the query
    String[] add = address.split(" ");

    //get rid of punctuation, h/t http://stackoverflow.com/users/3053630/jeff-ward
    name.replaceAll("[^a-zA-Z0-9\\s]", "").replaceAll("\\s+", " ");

    //build query
    String query = "select id from business where ";
    for (String add1 : add) {
        query += "streetAddress like '%" + add1 + "%' and ";
    }

    //find at least a partial match to the business name
    if(name.length()>5){
        query += "businessName like '%" + name.substring(0, 4) + "%';";
    }else{
        query += "businessName like '%" + name + "%';";
    }

    Statement s = conn.createStatement();
    ResultSet rs = s.executeQuery(query);

    while(rs.next()){
        //build list of businesses
        businessList.add(getBusiness(rs.getInt("id")));
    }

    rs.close();
    s.close();
    conn.close();

    return businessList;
}

I do understand that I may get some incorrect answers (for example, "Dominos Pizza" at 55 Marbach Road will match with "Dominos Pizza" at 2557 Marbach Road), but I plan on doing further evaluation/matching before finalizing.


texts:
I am working on a product application where user could sell/buy. This application is based on collection view. Collection view has collection cell where it displays product image thumbnail.

The following code gets products images from the server and it waits to download all images and then display them in the cells. The following code works but the user should wait 20-40 seconds to see products.

I highly suspect this implementation architecture is not good.

- (void)viewDidLoad {
    [super viewDidLoad];
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
     dispatch_async(queue, ^(void) {
        [self loadFromURL];
     dispatch_async(dispatch_get_main_queue(), ^{
     });
  });
}

-(void)loadFromURL {
    NSURL *url = [NSURL URLWithString:@"http://myURL/productAll.php"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

   [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
      pElements= (NSMutableArray *)responseObject;
      [collectionView reloadData];

     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Product" message:[error localizedDescription]delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
     [alertView show];
   }];
  [operation start];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return pElements.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor whiteColor];
    NSString *arrayResult = [[pElements objectAtIndex:indexPath.row] objectForKey:@"image"];
    NSData *data = [[NSData alloc] initWithBase64EncodedString:arrayResult options:NSDataBase64DecodingIgnoreUnknownCharacters];
    cell.productImage.image = [[UIImage alloc] initWithData:data];
    cell.productImage.layer.cornerRadius = 10;
    cell.productImage.clipsToBounds = YES;
    return cell;
}


texts: CLI to bump package.json version and add git tags

texts:
I'm writing a command line app in node.js. At this stage, the app does the following:

Get the version from package.json
Update the package.json with a new version depending on the command line argument
Commit the changes
Tag the commit
Push commits and tags to the remote

Some comments:

I'm really new to async/await and promises so I may be using those incorrectly in my code.
A lot of my code is wrapped in try-catch blocks which I understand is not supposed to be the case with async/await or Promises. I'm not sure how to fix this.
There's a lot of duplication with the spinner initialisation code. I am aware the ora has an ora.promise method as well. I couldn't get this to work.
Another example of duplication is with the process.exit(1) line within each catch block. Is this really needed or are there better ways to achieve this?
Do I really need to use the async IIFE at the end or is there a better way to do this?
I would also like feedback on whether I've divided my code into functions adequately.
I haven't added much error checking yet. For example, later, I'd like to check if a package.json exists, and if it doesn't, get the current version from git tags. How can I structure my code in such a way that I can easily add such functionality in the future?

Any other feedback is also welcome. If you can address even some of the above, I would appreciate it.

Usage:

ship <major|premajor|minor|preminor|patch|prepatch|prerelease>

(I named the script index.js, and created a symbolic link ship to it in /usr/local/bin)

#!/usr/bin/env node
'use strict';

const fs = require('fs');
const semver = require('semver');
const readPkg = require('read-pkg');
const writePkg = require('write-pkg');
const git = require('simple-git/promise')(process.cwd());

const ora = require('ora');
const chalk = require('chalk');

const env = process.env;

const validArgs = [
    'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'
];

const argv = require('yargs').argv;
const arg = argv._[0];

let spinner;

if (arg === undefined) {
    console.error(chalk.red(`Missing argument.`));
    console.error(chalk.red(`Should be one of ${validArgs.join(', ')}.`));
    process.exit(1);
}

if (!validArgs.includes(arg)) {
    console.error(chalk.red(`Invalid argument ${arg}`));
    process.exit(1);
}

async function nextVersion() {
    let current;

    try {
        const data = await readPkg();
        current = data.version;
    } catch(err) {
        process.exit(1);
        // todo: get version from git tags
    }

    return semver.inc(current, arg);
}

async function updatePkg(version) {
    spinner = ora('Writing package.json').start();

    try {
        const data = await readPkg();
        delete data._id;
        data.version = version;
        await writePkg(data);
        spinner.succeed();
    } catch (err) {
        spinner.fail();
        process.exit(1);
    }
}

async function commit(msg) {
    spinner = ora('Commiting changes').start();

    try {
        await git.add('package.json');
        await git.commit(msg);
        spinner.succeed();
    } catch (err) {
        spinner.fail();
        process.exit(1);
    }
}

async function makeTags(name) {
    spinner = ora('Adding tag').start();

    try {
        await git.addTag(name);
        spinner.succeed();
    } catch (err) {
        spinner.fail();
        process.exit(1);
    }
}

async function push() {
    spinner = ora('Pushing changes').start();

    try {
        // both of these may run together
        await git.push();
        await git.pushTags();
        spinner.succeed();
    } catch (err) {
        spinner.fail();
        process.exit(1);
    }
}

(async () => {
    const next = await nextVersion();

    console.log(); // gap between input and spinners

    await updatePkg(next);
    await commit(next);
    await makeTags(next);
    await push();
})();


texts: Creating a slider to adjust the width and two click events

texts:
I have some JavaScript that was put together for functionality but I wanted to know if there was a better way to write it. As it stands it's a little hard to read and follow.

$(document).ready(function(){
var loop = null;

$("li").click(function(){
    $("li").css("box-shadow", "none");
    $(".selector").css("visibility","hidden");
    var offSet = 7;
    if($(this).hasClass('Selected')){
        $(this).removeClass('Selected');
        $(this).children("div").css("visibility","hidden");
        $(this).css("box-shadow", "none");
    } else{
        $("li").removeClass('Selected');
        $(this).addClass('Selected');
        $(this).children("div").css("visibility","visible");
        $(this).css("box-shadow", "inset 0 0 " + offSet + "px #333");
    }
});

$("#sideNav > ul > li").click(function(){
    var element = $("#content");
    var offsetElement = $("#subSideNav");
    var width = 0;
    var offSet = parseInt(offsetElement.css("width")) + 2;

    if($(this).attr('id') === "Selected" && !element.hasClass('large')){
        $(this).attr('id', '');
        width = parseInt(element.css("width")) + 2;
        slider(element, offSet, 'hidden');
        $(element).addClass('large');
    } else if($(this).attr('id') !== 'Selected' && element.hasClass('large')){
        $("#subSideNav").css('display', 'block');
        $(this).attr('id', 'Selected');
        width = parseInt(element.css("width")) - 2;
        slider(element, offSet, 'visible');
        $(element).removeClass('large');
    }else if($(this).attr('id') !== 'Selected' && !element.hasClass('large')){
        $("#sideNav > ul > li").attr('id', '');
        $(this).attr('id', 'Selected');
    }
});

function slider(element, offSet, visibility){
    var width = parseInt(element.css("width"));
    if('visible' === visibility){
        width -= 1;
    } else{
        width += 1;
    }
    offSet -= 1;
    if(0 < offSet){
        element.css("width", width + "px");
        loop = setTimeout(function(){slider(element, offSet, visibility)}, 5);
    } else{
        clearTimeout(loop);
    }
}
})

The functions are basically supposed to create a slider to adjust the width and two click events. One event make a cover selector div visible to let you know it has been clicked, and the other does the same plus triggering the slider function. The reason there are two different clicks is because there are two separate menus, and only one needs the slider function.


texts: Check if a string has 20 numbers in a row in it

texts:
My code will check if the variable myString has 20 running numbers. I'm new to JavaScript and I'm wondering if there is a simpler way to do this. How can I shorten my code and possibly make it more efficient?

var myString = "tuxwuhkocx14789470019215498263ljmgwsxvne";
var runningNumbers = 0;

for (i = 0; i < myString.length; i++) {

    var character = myString.charAt(i);

    if (!isNaN(character)) {
        // If character is a number:
        runningNumbers = runningNumbers + 1;
    } else {
        // If character is NOT a number:
        runningNumbers = 0;
    }

    if (runningNumbers == 20) {
        console.log("myString has 20 running numbers.");
    }

}

Output:

  myString has 20 running numbers.


texts: Performance of critical function (STL transform)

texts:
I have finished the first part of my project, i.e., getting a full working program. However, the performance is not too impressive. The function expectedCosts(state const &S) took around 96% of the total running time, so any performance increase in this function might be worthwhile.

For profiling purpose I used a reasonable large problem instance that took 2374 seconds to solve. After some hours of profiling and optimizing, the total runtime is decreased to 39 seconds :). However, the majority of the runtime still goes to the same function. Since almost all runtime is caused by this single function I'm convinced that micro-optimizations are justified. The 39 seconds are not that bad, however I would like to solve instances of greater size which still take 3000+ seconds to solve. Can you help me to improve the function a bit more?

The current implementation of the function is shown at the bottom of this post. I expect that a performance gain is possible in line 24-25 (tmp = {0, 0, 0, d1, d2} and transform(..)) since these lines both take around 20-25% of the total time of the function.

I was skeptic about the benefit of __builtin_expect since I have never seen any situation where it did help. Surprisingly, the performance increase is on average (ten runs) more than 2%. I have already tried to remove the unlikely if-statements (if (__builtin_expect(pA < 0.00001, 0))). However, this more than doubled the runtime.

I use the gcc compiler with --std=c++11 -Wall -g -O2 -flto. Both -O3 and -ffast-math seems to decrease the performance of the program.

Do you have any suggestions?

Edit: state is a typedef for std::vector<size_t>. Just out of curiousity,  I changed the typedef to std::valarray<size_t>. This decreased the runtime of the current test instance to 31 seconds. I cannot explain the reason for this huge improvement since I had no time for a new extensive profiling session yet and I have never used std::valarray before. What confuses me is that most of us (people on Stack Overflow) are quite negative about the std::valarray.

double MDPsolver::expectedCosts(state const &S)
{
  double value = 0.0;
  vector<size_t> tmp {0,0,0,0,0};

  size_t const endA = d_F - S[3];
  size_t const endB = d_F - S[4];

  // Loop over all reachable states
  for (size_t d1 = 0; d1 <= endA; ++d1)
  {
    double const pA = d_p[S[3]][S[3] + d1];

    if (__builtin_expect(pA < 0.00001, 0))
      break;

    for (size_t d2 = 0; d2 <= endB; ++d2)
    {
      double const pB = d_p[S[4]][S[4] + d2];

      if (__builtin_expect(pB < 0.00001, 0))
        break;

      tmp = {0, 0, 0, d1, d2};
      transform(begin(tmp), end(tmp), begin(S), begin(tmp), plus<size_t>());

      value += pA * pB * d_values[hash(tmp)];
    }
  }

  return value;
}


texts: Another Brainfuck interpreter in Haskell

texts:
I came up with the following Brainfuck interpreter in Haskell after thinking about how to represent the program and the memory functionally using zippers to represent current location. This works since in Brainfuck, there is no way to reference more than one memory location away from your present location at one time.

import Control.Monad
import System.Environment

data ZL a = EM | ZL [a] a [a]

fromList []           = EM
fromList (x:xs)       = ZL [] x xs
zprv EM               = EM
zprv (ZL [] x rs)     = EM
zprv (ZL (l:ls) x rs) = ZL ls l (x:rs)
znxt EM               = EM
znxt (ZL ls x [])     = EM
znxt (ZL ls x (r:rs)) = ZL (x:ls) r rs
zmap (ZL ls x rs) f   = ZL ls (f x) rs

run code = go (fromList (repeat 0)) (fromList code)
  where
    go m EM                          = return m
    go m              i@(ZL _ '>' _) = go (znxt m) (znxt i)
    go m              i@(ZL _ '<' _) = go (zprv m) (znxt i)
    go m              i@(ZL _ '+' _) = go (zmap m (\x -> x + 1)) (znxt i)
    go m              i@(ZL _ '-' _) = go (zmap m (\x -> x - 1)) (znxt i)
    go m@(ZL ml x mr) i@(ZL _ '[' _) = go m (if x /= 0 then znxt i else skip znxt 0 i)
    go m@(ZL ml x mr) i@(ZL _ ']' _) = go m (if x == 0 then znxt i else skip zprv 0 i)
    go m@(ZL  _ x  _) i@(ZL _ '.' _) = putChar (toEnum x) >> go m (znxt i)
    go m@(ZL ml _ mr) i@(ZL _ ',' _) = getChar >>= \x -> go (ZL ml (fromEnum x) mr) (znxt i)
    go m@(ZL ml x mr) i@(ZL _   _ _) = go m (znxt i) -- Ignore
    skip _  1 i@(ZL _ ']' _)         = znxt i
    skip _ (-1) i@(ZL _ '[' _)       = znxt i
    skip d  n i@(ZL l '[' r)         = skip d (n+1) (d i)
    skip d  n i@(ZL l ']' r)         = skip d (n-1) (d i)
    skip d  n i@(ZL l   _ r)         = skip d n (d i)

main = do
  getArgs >>= \args -> case args of
    []    -> putStrLn "Usage: bf <program.bf>"
    (x:_) -> readFile x >>= run >> return ()


texts:
I am practicing to code in the right way and make it testable. Please review this code and tell me anything bad practices of it.

Entity:

namespace MockBlog\Entities;

use Doctrine\ORM\Mapping as ORM;
//use Doctrine\Common\Collections\ArrayCollection;

/**
* @ORM\Entity
* @ORM\Table(name="mockblog_page")
*/
class Page {

/**
 * @ORM\Id
 * @ORM\GeneratedValue
 * @ORM\Column(type="integer")
 */
protected $id;

/**
 * @ORM\Column(type="string")
 */
protected $title;

/**
 * @ORM\Column(type="string")
 */
protected $slug;

/**
 * @param $title
 */
public function setTitle($title)
{
    $this->title = $title;
}

/**
 * @param $slug
 */
public function setSlug($slug)
{
    $this->slug = $slug;
}

/**
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * @return string
 */
public function getTitle()
{
    return $this->title;
}

/**
 * get url of the page
 *
 * @return string
 */
public function getSlug()
{
    return $this->slug;
}
}

Interface post repository:

interface PostRepository {

/**
 * Find post by the title
 *
 * @param $title
 * @return mixed
 */
public function findByTitle($title);

/**
 * Find post by the url
 *
 * @param $slug
 * @return mixed
 */
public function findBySlug($slug);

/**
 * Find post by user id
 *
 * @param $userId
 * @return mixed
 */
public function findByUserId($userId);

}

Base repository (still blank but i think i will need it later):

class BaseRepository extends EntityRepository  {

}

Base post repository :

abstract class BasePostRepository extends BaseRepository implements PostRepository {

abstract public function save($data, $id);

public function findBySlug($slug)
{
    return $this->findBy(['slug' => $slug]);
}

public function findByTitle($title)
{
    return $this->findBy(['title' => $title]);
}

public function findByUserId($userId)
{
    return $this->findBy(['user_id' => $userId]);
}

}

Doctrine page repository:

class DoctrinePageRepository extends BasePostRepository  {

public function save($data, $id = 0)
{

    $entity = (empty($id)) ? $this->_class : $this->find($id);

    $entity->setTitle($data['title']);
    $entity->setSlug($data['slug']);

    try{

        EntityManager::persist($entity);
        EntityManager::flush();

        return true;

    } catch (Exception $err){

        return FALSE;

    }
}

}

Service provider:

public function register()
{
    // TODO: Implement register() method.

    $this->app->bind(DoctrinePageRepository::class, function($app){
        return new DoctrinePageRepository(
            $app['em'], $app['em']->getClassMetaData(Page::class)
        );
    });

}


texts: Determine if a string is a sequence of dictionary words

texts:
This is Leetcode problem 139: "Wordbreak"

  Problem:  Given a non-empty string s and a dictionary wordDict
  containing a list of non-empty words, determine if s can be segmented
  into a space-separated sequence of one or more dictionary words.

Note:

  The same word in the dictionary may be reused multiple times in the
  segmentation. You may assume the dictionary does not contain duplicate
  words.

Example:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true

Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.
my solution

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        """

        """

        def prune(i):
            if i == len(s):
                return True
            elif  i >len(s):
                return False
            else:
                for word in wordDict:
                    m = len(word)
                    if s[i:i+m] == word and prune(i+m):
                        return True

                return False
        wordDict.sort(key = lambda x:-len(x))
        return prune(0)

I believe the time complexity for my solution to be O(m^n), where m is the amount of words in wordDict and n is the length of the string s. Space wise is just the recursion stack so O(n). I'm having a hard time figuring out how to optimize my solution by either using bfs/dfs or dynamic programming. What would I memoize?


texts: A function determining intervals of values greater than threshold

texts:
I wonder if there exists a shorter/more elegant functional programming way than listing all the possible cases. Here, a function that determines positions of beginning/end of subintervals greater than threshold is coded. The idea behind the listed code is to mark and retain the beginning of such an interval, then to push a tuple of (beginning,ending) as soon as the interval ends. Feel free to choose any other approach if needed.

-- | Determines the intervals greater than threshold.
--
-- Examples:
-- >>> intervals 0.5 [0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0]
-- [(3,4),(8,10)]
-- >>> intervals 0.5 [1,0,0,0,1,1,0,0,0,1,1,1,0]
-- [(0,0),(4,5),(9,11)]
-- >>> intervals 0.5 [1,0,0,0,1,1,0,0,0,1,1,1,0,1,1,1]
-- [(0,0),(4,5),(9,11),(13,15)]
intervals :: Ord a => a -> [a] -> [(Int, Int)]
intervals threshold ys = f False 0 p
  where p = zip [0..] . map (> threshold) $ ys
        f :: Bool -> Int -> [(Int, Bool)] -> [(Int, Int)]
        f _ _ [] = []
        f True startPos ((bPos,b):[]) | b = [(startPos, bPos)]
                                      | otherwise = [(startPos, startPos)]
        f False _ ((bPos,b):[]) | b = [(bPos, bPos)]
                                | otherwise = []
        f True startPos ((aPos,a):(bPos,b):as) | a && b = f True startPos ((bPos,b):as)
                                               | a && (not b) = ((startPos, aPos)) : (f False 0 as)
                                               | otherwise = (startPos, startPos) : (f False 0 ((bPos,b):as))
        f False _ ((aPos,a):as) | a = f True aPos as
                                | otherwise = f False 0 as


texts: Open a window and render to it a texture

texts:
I'm new to C++ and SDL2. I made this program that makes a window. I want to make sure I'm implementing this in the most sensible way possible. I've been learning for free from online tutorials, so I wouldn't be surprised if I could improve it.

Are there ways to shorten this code? Does this violate programming principles?

Game.h

#ifndef GAME_H
#define GAME_H

class Game {
private:
    SDL_Event   _ev;
    bool        _isRunning;
public:
    Game();
    ~Game();

    void        run();
};

#endif

Game.cpp

/*
 * Graphics.cpp
 * Holds info for dealing with game's graphics
 *
 *
 */

#include <SDL2/SDL.h>
#include <iostream>

#include "Graphics.h"
#include "functions.h"

Graphics::Graphics() :
    _windowTitle            ("SDL2 project"),
    _windowWidth            (640),
    _windowHeight           (480),
    _renderingDriverIndex   (-1),                                                   // get the index of the first graphics driver available(?)
    _rendererFlags          (SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)  // use GPU, VSYNC
{
    _window=        SDL_CreateWindow(_windowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _windowWidth, _windowHeight, SDL_WINDOW_SHOWN);
    if(_window == 0){
        printError("SDL_CreateWindow");
        SDL_Quit();
    }

    _renderer=              SDL_CreateRenderer(_window, _renderingDriverIndex, _rendererFlags);
    if(_renderer == NULL){
        printError("SDL_CreateRenderer");
        SDL_Quit();
    }
}

Graphics::~Graphics() {
    SDL_DestroyWindow(_window);
    SDL_DestroyRenderer(_renderer);
}

void Graphics::changeWindowSize(int width, int height){
    SDL_SetWindowSize(_window, width, height);
}

SDL_Renderer* Graphics::getRenderer(){
    return _renderer;
}

int Graphics::getWindowWidth(){
    return _windowWidth;
}

int Graphics::getWindowHeight(){
    return _windowHeight;
}

Layer::Layer(SDL_Renderer* renderer, int width, int height) :
    _texture(SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height))
{

}

Layer::~Layer(){
    SDL_DestroyTexture(_texture);
}

SDL_Texture* Layer::getTexture(){
    return _texture;
}

functions.h

/*
 * functions.h
 *
 */

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void printError(const char* errorMessage);

#endif /* FUNCTIONS_H */

functions.cpp

/*
 * functions.cpp
 *
 */

#include <SDL2/SDL_log.h>
#include <SDL2/SDL_error.h>
#include <iostream>

#include "functions.h"

void printError(const char* errorMessage){
    std::cout << errorMessage << " error: " << SDL_GetError() << std::endl;
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, errorMessage, " error: %s\n", SDL_GetError());
}

main.cpp

/*
 * main.cpp
 * Entry point for game
 *
 */

#include <SDL2/SDL.h>
#include <iostream>

#include "Game.h"
#include "functions.h"

int main(int argc, char* argv[]) {
    Game game;
    game.run();

    return 0;
}


texts: The modularization of the Express entry point

texts:
I've been working on a project to make myself more comfortable with NodeJS, especially Express and TypeScript. Searching and reviewing a lot of approaches of the people, providing bootstraps for it, I was merely satisfied with the results I've found (including the git repos from Microsoft). So I started with the Express generator and started to convert it to a TypeScript conform structure. I moved the root/bin folder with it's "www" file to root/src/bin and renamed the file "index.ts".

Now the problem I faced was that the port variable, which was initialized in the outer function, has lead tslint to mark the port variable inside the normalizePort function as "no-shadowed-variable". That's when I decided to extract the normalizePort function, as well as the event handlers onError and onListening into modules at the same directory. I'd like to get some advice, if the conversion of the variables (var -> let, const) and the modularization seems reasonable to you.

Please let me know if you want me to also include the other two modules.

Please keep in mind that I'm fairly new to programming in general and haven't had the opportunity to work on a project in a production environment.

The whole project until now can be found here.

tslint.json:

{
  "defaultSeverity": "error",
  "extends": [
      "tslint:recommended"
  ],
  "jsRules": {},
  "rules": {
    "quotemark": [true, "single"],
    "trailing-comma": [ false ]
  },
  "rulesDirectory": []
}

root/src/bin/index.ts:

#!/usr/bin/env node
'use strict';

/**
 * Module dependencies.
 * @private
 */

import { createServer } from 'http';
import app from '../app';
import { onError, onListening } from './expressHandlers';
import { normalizePort } from './normalizePort';

/**
 * Get port from environment and store in Express.
 */

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

const server = createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Module exports.
 * @public
 */

export {
  port,
  server
};


texts: Make some inputs inside functions instead of main

texts:
I'm very new to OOP, and I'm trying to do it correctly!
I have been doing a simple friendbook where you can add, remove and show the friends you have. However, I dont know if I should be satisfied or not with my code.

class Friendbook:

    listOfFriends = {}

    def __init__(self, name, lastname):
        self.name = name
        self.lastname = lastname

    def addFriend(self):
        self.listOfFriends[self.name] = self.lastname

    def showFriends(self):
        for firstname, lastname in self.listOfFriends.items():
            print(firstname, lastname)

    def removeFriend(self):
        removeName = input("Enter name to remove\n")
        del self.listOfFriends[removeName]

while True:

    print("1. Add Friend\n2. Showfriends\n3. RemoveFriend\n9. Quit\n")
    try:
        selectedOption = int(input())
        if selectedOption == 1:
            name = input("Enter firstname\n") #Can i move this to a function?
            lastname = input("Enter lastname\n") #Can i move this to a function?
            makeFriends = Friendbook(name, lastname)
            makeFriends.addFriend()
        elif selectedOption == 2:
            makeFriends.showFriends()
        elif selectedOption == 3:
            makeFriends.removeFriend()
        elif selectedOption == 9:
            break
        else:
            print("Not a valid option")
    except:
        print("Only integers allowed")

I'm happy with it except for the code related to selectedoption 1, can I do something to put it inside the function so it looks nicer?
What do you think about my code in general, appreciate feedback!


texts: Summing all primes below 2,000,000 - Project Euler #10 in Assembly

texts:
I am currently learning assembly for university, and I'd like to hear some feedback concerning what I've written.
Currently I have implemented Problems 1, 2, 3 and 10 from ProjectEuler. The goal is to sum all primes ranging from 0 to 2,000,000.

For problem 10 I use the formula 6n +- 1 to check for primes. To actually check them, I test divisors 2, 3, 5, 7, ... I'm currently only using the general purpose registers of the x64 architecture.

Do you have any feedback concerning this code? Can I do something better? Optimize something?

I use NASM in x64 mode.
This is my current implementation:

; CurrentPrime          Current prime to test
; Sum               Sum
; CurrentN              n of 6n +- 1
; PrimeMode             Wether we're doing + or - 1 (0 means -)
%define Sum r9
%define CurrentPrime r8
%define CurrentN r10
%define PrimeMode r12

section .text
global main
main:
    mov Sum, 5 ; 2+3 not included in 6n +- 1
    mov CurrentN, 0 ; This gets inc'ed below

loop:

    ; Increase n
    inc CurrentN

    ; Break every 10000 Ns for debugging reasons
    mov rax, CurrentN
    mov rbx, 10000
    mov rdx, 0
    div rbx
    cmp rdx, 0
    jne _debug_next
    nop ; Break here
_debug_next:

    ; multiply it by 6 and save it to CurrentPrime
    mov rax, CurrentN
    mov rbx, 6
    mul rbx
    mov CurrentPrime, rax

    ; Start with 6n-1
    dec CurrentPrime

    ; Reset registers for testing
    mov PrimeMode, 0
    ; This is our divisor
    mov rcx, 2

next_prime_test:

    ; When the number to test is >= 2000000, then exit
    cmp CurrentPrime, 2000000
    jge finish

    ; When divisor_to_test > (number_to_test/2), then this is prime
    mov rax, CurrentPrime
    mov rbx, 2
    mov rdx, 0
    div rbx
    cmp rax, rcx
    jl is_prime

    ; Test divisor for divisor
    mov rax, CurrentPrime
    mov rbx, rcx
    mov rdx, 0
    div rbx
    cmp rdx, 0
    je check_next_prime

    ; We only check odd numbers.
    ; But to get from 2 to 3, we may not inc when we're at 2.
    cmp rcx, 2
    je skip_add

    inc rcx

skip_add:

    ; This divisor isn't a divisor of our number. Let's try with the next divisor.
    inc rcx
    jmp next_prime_test

is_prime:
    ; This number is prime, add it to our result.
    add Sum, CurrentPrime

check_next_prime:

    ; If we're doing 6n-1, increase by 2 to get 6n+1, then check again
    cmp PrimeMode, 0
    ; If we've done 6n+1, then go for the next n
    jne loop

    mov PrimeMode, 1 ; Set plus
    mov rcx, 2 ; Reset rcx to start over with a new prime
    add CurrentPrime, 2 ; 6n-1 +2 = 6n+1

    ; Check 6n+1
    jmp next_prime_test

finish:
    ; Result is in rax
    mov rax, Sum

    ret


texts:
I am writing a node.js inspired C++ library for asynchronous function calls.

How efficient and stable does my code look?

If you want, you can see some WIP code and demonstration code here.
(net.hpp is for POSIX sockets and is far from done. It does not have any IO functions written)

/* ASYNC.HPP
 * Defines some functions for calling other functions in the background
 * This gives the ability to create callback based functions easily,
 * similar to node.js (But I hate javascript so I wrote this library for c++)
 */

#ifndef ASYNC_H
#define ASYNC_H
#include <thread>
#include <vector>

std::vector<std::thread> asyncCalls; // Don't have to deal with threads leaving scope since this vector is global
#define asyncCall asyncCalls.emplace_back // Whenever someone calls asyncCall this constructs a new std::thread which calls their function

void finishAsync(){ //Call to block until all running asyncronous functions return
while(!asyncCalls.empty()){ //Loop until the vector is empty
        asyncCalls.back().join(); //Get the thread from the back and join it to block
                //^ I feel like this line might throw an exception, but in my testing it hasn't thrown anything.
        asyncCalls.pop_back(); //Pop it and get a new one
}
} // Infinite running threads will block forever

#ifdef _GLIBCXX_CHRONO //Include <chrono> before this header for this function

void sleep(uint32_t millis){ //I just realized while adding comments that I could do this with a define. Oh well
    std::this_thread::sleep_for(std::chrono::milliseconds(millis));
}

#endif // End chrono function

#endif //End header guard