texts: Possible improvements on admin login area?

texts:
I've created an admin login area for an application I am planning to code, and I've used the following login.html page to let the user type in his data (I left out parts like "id", "placeholder" etc. to make it shorter):

<form method="post" action="login.php">
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="submit" value="Login" name="submit">
</form>

The form is processed as is, no JavaScript interfering here.  The login.php then looks like this:

<?php
  if (isset($_POST['password']) && isset($_POST['userName'])) {
    if ($_POST['password'] == "myPassword" && $_POST['userName'] == "myUsername") {
      if (!session_id()) {
        session_start();
        $_SESSION['logon'] = true;
        header('Location: admin_area.php');
        die();
      }
    } else if ($_POST["password"] == "" || $_POST["userName"] == "") {
      echo "Please enter both a username and a password! You are sent back in 3 seconds";
      echo "<meta http-equiv='refresh' content='3;url=login.html'>";
    } else {
      echo "Wrong username and/or password! You are set back in 3 seconds";
      echo "<meta http-equiv='refresh' content='3;url=login.html'>";
    }
  } else {
    echo "This is a restricted area, you have to log in!";
    echo "<meta http-equiv='refresh' content='3;url=login.html'>";
  }
?>

The admin_area.php file, which the user is then being redirected to, has the following short placeholder code:

<?php
  if (!session_id()) session_start();
  if (!$_SESSION['logon']) {
    echo "This is a restricted area, you have to log in!";
    echo "<meta http-equiv='refresh' content='3;url=login.html'>";
  } else {
    echo "<script src='//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js'></script>";
    echo "<script type='text/javascript' src='session_destroy.js'></script>";
    echo "Hello World!";
    echo "<br>";
    echo "<input type='button' id='exit_button' value='Exit' onclick='window.open(\"\", \"_self\", \"\"); window.close();'>";
  }
?>

The essential part of the session_destroy.js file on this page contains this code snippet:

$(window).on("beforeunload", function() {
  $.get("session_destroy.php");
  return "You have left the page. Your session has been terminated.";
});

And finally, the session_destroy.php, which should terminate all session data, contains the following lines (taken from the PHP manual):

<?php
  if (!session_id()) session_start();
  if (!$_SESSION['logon']) {
    echo "This is a restricted area, you have to log in!";
    echo "<meta http-equiv='refresh' content='3;url=login.html'>";
  } else {
    $_SESSION = array();
    if (ini_get("session.use_cookies")) {
      $params = session_get_cookie_params();
      setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
      );
    }
    session_destroy();
    header('Location: login.html');
  }
?>

Now this "construct" seems to be working just fine.  I am wondering if there are some improvements on these lines, as I have researched everything myself and I am not sure how "secure" and correct these methods might be.

I am thinking of possible security improvements to the form-processing and session-handling / destroying. Are there any areas in which I should do more research?


texts: Finding the elements with the most neighbors

texts:
I have a sample list which contains nodes and their neighbors, if they have any. The task is to find the node which have the highest number of neighbors.

neigh = [['A'],['A','B'],['A','C'],['B','D'],['C','A']]

The input is undirected. Meaning that ['A', 'B'] are neighbors. While ['A'] doesn't have any neighbors since it has no other value within its own list. If a sublist has 2 elements, then they are neighbors. Otherwise they are not neighbors.

My solution is below, it has a lot of if-else statements. Is there a more elegant way to solve this?

def find_neighbors(neigh):
    d = {}
    for i in neigh:
        if i:
                if len(i)==2:
                    if i[0] in d.keys():
                        d[i[0]] +=1.0
                    else:
                        d[i[0]] = 1.0

                    if i[1] in d.keys():
                        d[i[1]] +=1.0
                    else:
                        d[i[1]] = 1.0

    max = 0
    for i,j in d.items():
        if j > max:
            max = j
    return [i for i, j in d.items() if j == max]

find_neighbors(neigh)


texts: Using range minimal query for lowest common ancestor (LCA) -- part 2

texts:
Here is my code to use range minimal query to resolve the LCA problem. I applied comments from here.

Any advice on code bugs, performance improvement in terms of algorithm time complexity, code style are appreciated.

Major ideas of my idea are:

Build depth array of each node by in-order traverse
Build MRQ index for depth array built in first step
For any two nodes, their LCA are the lowest depth node between them (in depth array)

from collections import defaultdict
class TreeNode:
    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right
    def in_order_traverse(self, result, depth, node_index_map):
        if self.left:
            self.left.in_order_traverse(result, depth+1, node_index_map)
        result.append((depth, self.value))
        node_index_map[self.value] = len(result) - 1
        if self.right:
            self.right.in_order_traverse(result, depth+1, node_index_map)
class RMQ:
    def __init__(self, raw_array):
        self.rmq_index = defaultdict(tuple)
        step = 0
        for i,v in enumerate(raw_array):
            self.rmq_index[(i, step)] = v
        step += 1
        while 2 ** (step-1) <= len(raw_array):
            for i,v in enumerate(raw_array):
                if i+2**(step-1) < len(raw_array) and self.rmq_index[(i+2**(step-1), step-1)][0] < self.rmq_index[(i, step-1)][0]:
                    self.rmq_index[(i,step)] = self.rmq_index[(i+2**(step-1), step-1)]
                else:
                    self.rmq_index[(i,step)] = self.rmq_index[(i, step-1)]
            step += 1
    def rmq_query(self, i, j):
        step = 0
        while i + 2 ** step - 1 < j:
            step += 1
        step -= 1
        x = self.rmq_index[(i,step)]
        y = self.rmq_index[(j-2**step+1, step)]
        if x[0] < y[0]:
            return x[1]
        else:
            return y[1]
if __name__ == "__main__":
    root = TreeNode(1, TreeNode(2, TreeNode(4, None, None), TreeNode(5, None, None)), TreeNode(3, TreeNode(6, None, None),TreeNode(7,None,None)))
    result = []
    node_index_map = defaultdict(int)
    root.in_order_traverse(result, 0, node_index_map)
    rmq = RMQ(result)
    print rmq.rmq_query(node_index_map[4], node_index_map[5])
    print rmq.rmq_query(node_index_map[4], node_index_map[7])


texts: Project Euler # Triangular, pentagonal and hexagonal in Python

texts:
Triangle, pentagonal, and hexagonal numbers are generated by the
  following formulae:

  Triangle: \$T_n=\frac{n(n+1)}{2}\$ 1, 3, 6, 10, 15, …
  Pentagonal: \$P_n=\frac{n(3n−1)}{2}\$ 1, 5, 12, 22, 35, …
  Hexagonal: \$H_n=n(2n−1)\$ 1, 6, 15, 28, 45, …

  It can be verified that \$T_{285} = P_{165} = H_{143} = 40755\$.

  Find the next triangle number that is also pentagonal and hexagonal.

from time import time

def tri_pent_hex(n):
    """yields triangles that are also pentagons and hexagons in range n."""
    triangles = set((num * (num + 1)) // 2 for num in range(1, n))
    pentagons = set((num * (3 * num - 1)) // 2 for num in range(1, n))
    hexagons = set(num * (2 * num - 1) for num in range(1, n))
    for triangle in triangles:
        if triangle in pentagons and triangle in hexagons:
            yield triangle

if __name__ == '__main__':
    start_time = time()
    print(max(tri_pent_hex(1000000)))
    print(f'Time: {time() - start_time} seconds.')


texts:
What the code does (tested basic, no errors, usecase):

Reads all XML files (ending in .yin) from a directory.
converts each to JSON
store it in another directory, with the same basename as source file
... with .yin replaced by .json

Overt issues:

The code has too many nested functions
walk module's next() method in multiple places
lack of robust error checks and ensuring no uncaught errors left behind

Q. How to refactor the code using Node.js best practices?
(things like):

flatten out the nesting.
avoiding having to remember to call next(), on all if(err) scenarios.
does any other (than those included) module improve readability/efficiency?

Two Node.js files, a module and a main file invoking that module, are attached.

File 1: Main:

// main.js
var path = require ('path');
var yin2json = require ('./yin2json');

console.log ("__dirname: " + __dirname);
var templateDir = path.resolve (__dirname, "resources", "mgmtDataTemplates");
var yinDir = path.resolve (templateDir, "yins");
var jsonDir = path.resolve (templateDir, "jsons");

yin2json.convertYins (yinDir, jsonDir);

File 2: Module:

// yin2json.js

    var fs = require('fs');
    var path = require('path');
    var walk = require('walk');
    var xml2js = require('xml2js');

    var jsonDir ;
    var convertYins = function (yin_dir, json_dir) {
        jsonDir =  json_dir;

        var walker = walk.walk(yin_dir, { followLinks: true });
        walker.on("errors", fDirWalkError);
        walker.on("end", fDirWalkEnd);
        walker.on("file", fDirWalkFile);

    }

    function fDirWalkError (err) {
        console.log ("fDirWalkError: " + err);
        next (err);
    }

    function fDirWalkEnd  () {
        console.log ("======= End of directory walk");
    }

    function fDirWalkFile (root, fileStat, next) {
        if (fileStat.name.indexOf(".yin") < 0) {
            console.log ("skipping file " + fileStat.name + " (does not end in .yin)");
            return;
        } else {
            var yin_file = path.resolve(root, fileStat.name);
            console.log ("yin file: " + yin_file);

            fs.readFile(yin_file, function (err, data) {
                if (err) {
                    console.log ("error reading file:" + yin_file);
                    next (err);
                }
                xml2js.parseString (data, function (err, json_obj) {
                    if (err) {
                        console.log (err);
                        next (err);
                    }
                    var json_string = JSON.stringify(json_obj, null, 2);
                    var json_file = path.resolve (jsonDir, path.basename(yin_file).replace(/\.yin$/, ".json"));
                    console.log ("json file: ", json_file);

                    fs.writeFile(json_file, json_string, "utf8", function (err) {
                        if (err) {
                            console.log ("error converting yin (%s) to json(%s)", yin_file, json_file);
                            next (new Error ("error converting yin(" + yin_file + ") to json(" + json_file + ")"));
                        }
                        else {
                            console.log ("Converted yin (%s) to json(%s)", yin_file, json_file);
                        }
                    });
                });
            });
        }
        next ();
    }

module.exports.convertYins = convertYins;


texts:
I have all large file of all the order sold in one week. This file gives one line for every order. We have over 5000 orders a day. It read the file line by line and then adds  the sale to a database of sales. to I really need to boost performance.

   static void sold4weeks1()
    {
        string sold, asin;
        string[] lines = System.IO.File.ReadAllLines(@"C:\out\qqqqq.txt");

        inventoryBLL u = new inventoryBLL();
        try
        {
            foreach (string line in lines)
            {

                char[] tabs = { '\t' };
                string[] words = line.Split(tabs);
                asin = words[12];
                sold = words[14];

                if (words[0].Substring(0, 3) == "S01") continue;
                try
                {
                    if (words[4] == "Shipped" || words[4] == "Unshipped")
                    {

                        u.setSoldin28(asin, Convert.ToInt16(sold));
                        Console.WriteLine("Update");
                    }
                }
                catch
                {
                }
            }
        }
        catch
        { }
    }


texts:
This was a question asked to me before setting up an interview.
You are given a game board that contains a four by four (4x4) array of pieces. The pieces can be one of six shapes and can be one of six colors.

If the board contains 4 pieces of the same shape and same color, the board contains a winning pattern.

public enum Color
{
Red,
Blue,
Green,
Yellow,
Black,
Purple
}

public enum Shape
{
Square,
Triangle,
Circle,
Star,
Pentagon,
Octagon
}

public class Piece
{
public Color color;
public Shape shape;

public bool Equals(Piece compareTo) {};
}

public class Board
{
public Piece[,] position = new Piece[4,4];

public void Board(){ /*completely builds the board*/};
public void MakeRandomBoard(){};
public piece GetPiece(int x) {};
public bool IsWinner() {};
}

Write the code to detect when a winning pattern is present in a board.

Answer :

bool isWinner() {
    HashMap <Pair<Color, Enum>, int> pieceCount;
    for(int row = 0; row < 4; row++) {
        for(int col =0; col < 4; col++) {
            Piece p = GetPiece(row, col); // Note: Sig is different than Given.
            Pair <Color, Enum> pair(p.Color, p.Enum);
            if (pieceCount.Contains(pair)) {
                pieceCount[pair]++;
                if (pieceCount[pair] >= 4) return true;
            } else {
                pieceCount[pair] = 1;
            }
        }
    }
    return false;
}

The question was to come up with 3 different ways to solve this and list the pros and cons for each solution. This is one of the solution that I was able to do.
Please give your inputs on the code.


texts:
Could someone kindly have a look at the recursive merge sort below and let me know if there are any improvements? I'm mainly interested in either improving the code speed or making the code shorter.

def mergesort(alist):
    if len(alist) > 1:
        mid = len(alist)/2
        left = alist[:mid]
        right = alist[mid:]

        mergesort(left)
        mergesort(right)

        i = 0
        j = 0
        k = 0

        while i < len(left) and j < len(right):
            if left[i] > right[j]:
                alist[k] = right[j]
                j = j + 1

            elif left[i] < right[j]:
                alist[k] = left[i]
                i = i + 1

            k = k + 1

        while i < len(left):
            alist[k] = left[i]
            i = i + 1
            k = k + 1

        while j < len(right):
            alist[k] = right[j]
            j = j + 1
            k = k + 1

A = [4, 3, 1, 2, 6, 8, 10]

mergesort(A)
print(A)


texts: How to properly call an "upsert" using parameterized raw SQL to Postgresql in ActiveRecord?

texts:
I need to call an upsert to my Category table in PostgreSQL. My current solution uses the exec_query API in ActiveRecord, using binding.

What I got so far looks like this:

VERIFY_CATEGORY_SQL = <<SQL
  WITH sel AS (SELECT id FROM categories WHERE name=$1 AND source=$2),
  ins AS (INSERT INTO categories (name, source, created_at, updated_at) SELECT
    $3, $4, 'now', 'now' WHERE NOT EXISTS (SELECT * from sel) RETURNING id)
  select id from ins union all select id from sel
SQL

VERIFY_CATEGORY_SQL = <<SQL
  WITH sel AS (SELECT id FROM categories WHERE name=$1 AND source=$2),
  ins AS (INSERT INTO categories (name, source, created_at, updated_at) SELECT
    $1, $2, now(), now() WHERE NOT EXISTS (SELECT * from sel) RETURNING id)
  select id from ins union all select id from sel
SQL

def verify_category_existence(name, source)
  ActiveRecord::Base.connection.exec_query(VERIFY_CATEGORY_SQL, 'SQL',
    [[nil, name], [nil, source]]).first['id'].to_i
end

Notes

In order to make this work I needed to add prepared_statements: true attribute to my database.yml file.
Although I need to reuse my name and source parameters, I can't and have to duplicate them as parameters $1, $3 and $2, $4 respectively (Apparently this works fine...)
The method call seems a bit hackish, and I believe maybe it was not meant as a public method, and only intended for internal uses (hence the awkward [[nil, x]...] syntax and the 'SQL' parameter, which apparently is for logging purposes)

What do you think of this solution?

Do you know of a better way to do this?

Edit:

I've received great responses to the SQL/Postgresql side of my solution, but I would love to also hear from our rubyists regarding the Ruby/ActiveRecord part of the solution - is this way correct? is there a better solution?

Edit:

Just found out that using 'now' produced unexpected results - timestamp values were re-used rather than calculated on each insert. Changed it to now(), and it works better.


texts: Linear probing 16 hashmap elements in parallel using SIMD instrinsics

texts:
For my hashmap implementation, I'm caching hashes for each map element in an array of length NBUCKETS, where each element corresponds to an element in the hashmap. Assuming a hash consists of 64-bits, the first 57 bits decide the position(bucket) in the hashmap and the last 7 bits (i.e H2(hash)) are used as control bytes for probing the table. More concretely, while finding an element in the map using linear probing, H2(hash) is compared for 16 elements at a time using SIMD intrinsics before comparing actual keys. Hence, each call to probe_group() probes 16 elements of the map at the same time.
Components of code where I think optimization is needed but don't know how to do so (these have TODO tags in code):

Populating the group array with 16 elements from hash_arr is expensive. I want to avoid the usage of temporary group array and load the last 7 bits of 16 consecutive hash values from hash_arr directly into a __m128i (i.e ctrl).  Is there a way to directly load the last 7 bits of 16 hash values from hash_arr into __m128i instead of using the temporary byte array group?
Checking which indices have bit 1 is expensive because my current implementations applies (match >> i) & 1U for each index i, where i ranges from 0 to 15 inclusive. Is there a more efficient way to do this?

Any suggestions on improving these components as well as others parts of the code will be deeply appreciated.
#include <immintrin.h>
#include <stdint.h>
#include <stdio.h>

#define NBUCKETS 100
#define GROUP_SIZE 16

typedef char h2_t;

// return the lowest byte
static inline h2_t H2(size_t hash)
{
    return hash & 0x7f;
}

// If ith element in `group` is 'hash', then ith bit in `match` will be 1,
// otherwise it will be 0
static inline uint16_t probe_group(h2_t hash, h2_t *group)
{

    __m128i ctrl  = _mm_loadu_si128((__m128i*) group);
    __m128i match = _mm_set1_epi8(hash);
    return _mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl));
}

int main()
{
    // Dummy array of hashes. Each element corresponds to an element at that index in the hashmap.
    size_t hash_arr[NBUCKETS];
    for (int i = 0; i < NBUCKETS; i++)
        hash_arr[i] = i;

    // TODO Optimize this: Avoid using this array. Instead load the last 7 bits of 16 hash values directly into a `__m128i`.
    const int start_pos = 90;
    h2_t group[GROUP_SIZE];
    for (int i = 0; i < GROUP_SIZE; i++)
        group[i] = H2(hash_arr[(start_pos + i) % NBUCKETS]);

    // Element to be searched for in `group`.  ASCII for 'c' is 99
    h2_t find_ele = 'c';

    uint16_t match = probe_group(find_ele, group);

    // TODO Optimize this: Find a better way to check which indices have bit 1
    for (int i = 0; i < GROUP_SIZE; i++) {
        if ((match >> i) & 1U)
            printf("Element at index %d in group is equal to %c\n", i, find_ele);
    }
}
```


texts:
The following is a quick attempt at testing some limits of my computer:
import multiprocessing
import time

def main():
    numbers = tuple(multiprocessing.Value('Q', 0, lock=False) for _ in range(multiprocessing.cpu_count()))
    processes = tuple(multiprocessing.Process(target=count, args=(number,)) for number in numbers)
    for process in processes:
        process.start()
    time.sleep(10)
    for process in processes:
        process.terminate()
    print(sum(number.value for number in numbers))

def count(number):
    while True:
        number.value += 1

if __name__ == '__main__':
    main()

Without changing the overall design (adding one to a variable as many times as possible within a certain time limit), is there a way to improve the performance of the code? In this case, having a higher number printed out on the same computer is better.


texts: A Java class for calculating size of iterable/array v2

texts:
Version 2 of A Java class for calculating size of iterable/array

import java.util.Collection;

/**
 * Created by IDEA on 16/11/14.
 */
public class Size {
    public static int size(Iterable<?> data) {
        if (data instanceof Collection) {
            return ((Collection<?>) data).size();
        }
        int counter = 0;
        for (Object i : data) {
            counter++;
        }
        return counter;
    }

    public static int size(int[] data) {
        return data.length;
    }

    public static int size(double[] data) {
        return data.length;
    }

    public static int size(float[] data) {
        return data.length;
    }

    public static int size(short[] data) {
        return data.length;
    }

    public static int size(boolean[] data) {
        return data.length;
    }

    public static int size(char[] data) {
        return data.length;
    }

    public static <T> int size(T[] data) {
        return data.length;
    }
}


texts:
I just decided to write a unit test, and see how to do it.  This is my unit test:

[TestMethod]
public void TestSearchSort()
{
    System.IO.File.WriteAllText(@"C:\Users\Hosch250\Documents\Visual Studio 2013\Projects\ConsoleApplication14\ConsoleApplication14\TestFile.cs", string.Empty);

    var TestInstance = new Program();
    var titles = new List<string>();
    string[] query = { "main", "menu" };

    Program.Search(ref titles, ref query);

    var expectedTitles = new List<string>();
    string[] expectedTitleStrings = { "The Main Menu", "OneNote", "The Text Menu",
                                    "The Text Block Menu", "The Table Menu", "The Table Cells Menu",
                                    "The Draw Menu", "The Drawn Items Menu", "The Picture Menu",
                                    "The File Menu", "Draw", "Windows Phone Notebooks",
                                    "Windows Phone Sections", "Windows Phone Pages" };
    expectedTitles.AddRange(expectedTitleStrings);

    using (var file = new System.IO.StreamWriter(@"C:\Users\Hosch250\Documents\Visual Studio 2013\Projects\ConsoleApplication14\ConsoleApplication14\TestFile.cs", true))
    {
        file.WriteLine("Expected Count: " + expectedTitles.Count);
        file.WriteLine("Actual Count: " + titles.Count);
    }

    Assert.AreEqual(expectedTitles.Count, titles.Count);
    for (var i = 0; i < titles.Count; i++)
    {
        using (var file = new System.IO.StreamWriter(@"C:\Users\Hosch250\Documents\Visual Studio 2013\Projects\ConsoleApplication14\ConsoleApplication14\TestFile.cs", true))
        {
            file.WriteLine("Expected Title: " + expectedTitles[i]);
            file.WriteLine("Actual Title: " + titles[i]);
        }
        Assert.AreEqual(expectedTitles[i], titles[i]);
    }
}

This is the method it tests:

public static void Search(ref List<string> resultTitles, ref string[] query)
{
    List<int> weight = new List<int>();

    int position = -1;

    foreach (string[] array in SearchKeys.Keys)
    {
        position++;
        int length = array.Length;
        int middle = length / 2;
        char firstCharMidArray = array[middle][0];

        foreach (string s in query)
        {
            int min = array[middle][0] < s[0] ? middle : 0;
            int max = array[middle][0] <= s[0] ? array.Length : middle + 1;

            for (int i = min; i < max; i++)
            {
                weight.Add(0);

                if (array[i] == s)
                {
                    if (weight[position] == 0)
                    {
                        resultTitles.Add(array[0]);
                    }
                    weight[position]++;

                }
            }
        }
    }

    StableSort(ref resultTitles, ref weight);
}

I write to the file in the test method so I can see where/how it failed.  How did I do?  Should I be doing anything different?  Should I have more tests?  I most certainly cannot run every possible combination of search terms.


texts: NodeJS conditional request before the real request

texts:
In my code I have to login a user with username and password. But if the user sends his e-mail instead of his username, I have to resolve it with another request.

This is what the code looks like:

exports.auth = (request, response, next) ->
  username = request.body.username
  if request.body.email
      users.findByEmail request.body.email, (error, result) ->
          return next new InternalServerError(error) if error
          username = result[0].username
          auth.auth username, request.body.password, (error, result) ->
              return next new InternalServerError(error) if error
              response.json responseData
  else
      auth.auth username, request.body.password, (error, result) ->
          return next new InternalServerError(error) if error
          response.json responseData

As you can see there are 3 duplicate lines.

Does anyone know a good code style do make this better? Maybe with Promises? Async Waterfall? Waitfor?


texts:
This code basically makes the dot follow a certain point on the screen. It consumes a significant amount of computing time in my game, so I'd like it to be best optimized. I wrote this code after quickly reading some pages in a high school mathematics book, so it's unlikely to be a computationally efficient solution.

The mj_ prefix is just what I use instead of a namespace in my C code.

Suggest some good possible optimizations.

struct mj_dot {
    double x;
    double y;
    double th;
};

void mj_dot_rotate(struct mj_dot *, double, double);
void mj_dot_move(struct mj_dot *, double, double, double, double);

static double mj_distance(double x, double y, double x2, double y2) {
    return sqrt(pow(x - x2, 2) + pow(y - y2, 2));
}

void mj_dot_rotate(struct mj_dot *this, double x, double y) {
    double dx = x - this->x;
    double dy = y - this->y;
    this->th = atan(dy / dx);
    if (isnan(this->th)) {
        this->th = 0;
        return;
    }
    if (dx < 0) {
        this->th += MJ_MATH_PI;
    }
}

void mj_dot_move(struct mj_dot *this, double x, double y, double speed, double seconds) {
    double d = speed * seconds;
    if (d >= mj_distance(this->x, this->y, x, y)) {
        this->x = x;
        this->y = y;
    } else {
        mj_dot_rotate(this, x, y);
        this->x += d * cos(this->th);
        this->y += d * sin(this->th);
    }
}


texts:
I've got a short algorithm used in my code to multiply two matrices and put them into a destination Matrix. I decided to use the temporary array t_elements, which allows the user to make one of the input matrices the output matrix as well.

Usually I like to save optimization for later, but this code is going to be called often, so I was wondering if anyone could suggest ways to make it faster.

#include <vector>

struct Matrix{
    std::vector<std::vector<float>> elements;
    int height;
    int width;

    Matrix(int w, int h)
    {
        width = w;
        height = h;

        for (int i = 0; i < height; i++) {
            elements.push_back(std::vector<float>());

            for (int j = 0; j < width; j++) {
                elements[i].emplace_back(0.0f);
            }
        }
    }

    float get_element(int x, int y) const { return elements[y][x]; }

    void set_element(int x, int y, float value) { elements[y][x] = value; }
};

void dot(Matrix const& left, Matrix const& right, Matrix& dest)
{
    float t_elements[right.width][left.height];

    for (int i = 0; i < left.height; i++) {
        for (int j = 0; j < right.width; j++) {
            float elementVal = 0;

            for (int k = 0; k < left.width; k++)
                elementVal += (left.get_element(k, i) * right.get_element(j, k));

            t_elements[j][i] = elementVal;
        }
    }

    for (int i = 0; i < dest.width; i++)
        for (int j = 0; j < dest.height; j++)
            dest.set_element(i, j, t_elements[i][j]);
}

int main()
{
    Matrix m1 = Matrix(3,3);
    Matrix m2 = Matrix(3,3);
    Matrix m3 = Matrix(3,3);

    dot(m1, m2, m3);

    return 0;
}


texts: Getting the average score for hotel scores in different countries using pandas

texts:
I am diving into Data Analysis with pandas, and I have just written this Python script to calculate the average of hotel review scores of each country. The dataset contains an individual average score for each customer review, like: 8.86 or 7.95. My goal was to average all these individual scores for a particular country.

For example, if the hotels in United Kingdom got the following hotel review scores: 8.65, 7.89, 4.35, and 6.98, I would average these four scores and create a dataframe where the first column is "Country" and the second column is the "Overall Average Score" for that country.

I tried to write a concise code as much as I could. Would you mind giving your opinions and recommendations about it? I'll be adding this to my portfolio. What should be kept and/or avoided in a professional and real-world setting?

Script:

# Average all scores that belong to a particular country.

import pandas as pd

# Reading original hotel reviews dataset.
df = pd.read_csv(DATASET_PATH)

# Getting a dataframe with two columns: 'Hotel_Address' and 'Average_Score'.
df = df.loc[:, ["Hotel_Address", "Average_Score"]]

# List of tuples.
countries_w_avg_list = []
for _, row in df.iterrows():
    address = row[0].split()
    country_name = address[len(address) - 1]
    countries_w_avg_list.append( (country_name, row[1]) )

# Getting the sum of all 'Average_Score' values for each country.
d = {} # Empty dictionary. It will be a dictionary with list values, like: {"Netherlands": [sum, counter]}
counter = 0
for country, individual_average in countries_w_avg_list:
    if country not in d:
        d[country] = [0, 0]

    d[country][0] += individual_average
    d[country][1] += 1

# Getting the average of all 'Average_Score' values for each country.
for key, value in d.items():
    d[key] = round((d[key][0] / d[key][1]), 2)
# print(d)

# Now, I believe there are two ways to transform this dictionary in the df I want.
# 1 - Transform d in a df, and then transpose it. Then rename the columns.
# 2 - Create a dataframe with the column names "Country" and "Overall Average Score"
# and their values as d's keys as the value for the first column and d's values as the
# values for the second column.
df = pd.DataFrame({"Country": list(d.keys()), "Overall Average Score": list(d.values())})
print(df)


texts:
I'm trying to write universal factory creating objects by name. I've got some working prototype now but there must be a better way than casting construction methods to void pointer.

struct aobject {}; // some base

class factory
{
public:
    template <typename... TArgs>
    static aobject *create_named(const char *name, TArgs... args)
    {
        using constructor_t = aobject *(*)(TArgs...);
        auto citer = bindings_.find(name);
        if (citer == bindings_.end())
            return nullptr;
        return ((constructor_t)citer->second)(std::forward<TArgs>(args)...);
    }

    template <class TObject, typename... TArgs>
    static void bind_named(const char *name)
    {
        auto constructor_ptr = (void*)&constructor<TObject, TArgs...>;
        bindings_.insert(std::make_pair(name, constructor_ptr));
    }

private:
    template <class TObject, typename... TArgs>
    static aobject *constructor(TArgs... args)
    {
        return new TObject(std::forward<TArgs>(args)...);
    }

    using obj_name_binding_t = tmap<std::string, void*>;
    static obj_name_binding_t bindings_;
};
}

// TEST
struct test : public aobject {
    test(const char *text) : text_(text) {}
    void foo() { std::cout << text_ << '\n'; }
    const char *text_;
};

factory::bind_named<test, const char*>("test_name");
auto t = static_cast<test*>(factory::create_named("test_name", "text"));
t->foo();

Any ideas?


texts: Configure AspNet.Identity to allow for either username OR email address on login

texts:
I am wondering if there is a more efficient route to take here.  Using AspNet.Identity I would like to allow the user to sign in to the same text box using either their usernameor email.  I went ahead and addressed this issue in theAccountController Login ActionResult`.

I run the check before calling:

var result = await SignInManager.PasswordSignInAsync(model.Username,
                                                     model.Password,
                                                     model.RememberMe,
                                                     shouldLockout: false);

My method for checking username or email:

// Determine if user has entered their UserName or Email address.
// TODO: research if there is a more efficient way to do this.
using (var db = new ApplicationDbContext())
{
  model.Username = (db.Users.Any(p => p.UserName == model.Username)) ?
  model.Username :
  (db.Users.Any(p => p.Email == model.Username)) ?
  db.Users.SingleOrDefault(p => p.Email == model.Username).UserName :
  model.Username;
}

My concerns here:

Is there a more efficient practical way to do this?
Am I introducing any new security risks or performance risks by doing it this way?

I am including the entire ActionResult below for reference:

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
  if (!ModelState.IsValid)
  {
    return View(model);
  }

  // Determine if user has entered their UserName or Email address.
  // TODO: research if there is a more efficient way to do this.
  using (var db = new ApplicationDbContext())
  {
    model.Username = (db.Users.Any(p => p.UserName == model.Username)) ?
    model.Username :
    (db.Users.Any(p => p.Email == model.Username)) ?
    db.Users.SingleOrDefault(p => p.Email == model.Username).UserName :
    model.Username;
  }

  // This doesn't count login failures towards account lockout
  // To enable password failures to trigger account lockout, change to shouldLockout: true
  var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
  switch (result)
  {
    case SignInStatus.Success:
      return RedirectToLocal(returnUrl);
    case SignInStatus.LockedOut:
      return View("Lockout");
    case SignInStatus.RequiresVerification:
      return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    case SignInStatus.Failure:
    default:
      ModelState.AddModelError("", "Invalid login attempt.");
      return View(model);
  }
 }


texts: Ring Timer Animation with Chasing Tail using CoreAnimation

texts:
After a fair amount of trial and error, I have gotten the animation acting in the manner that I want it, as seen here. However, I always feel like I'm writing way too much and too sloppily when trying to use Core Animation.

The animation is as follows:

The view begins with a point of light at the top of the loop.
When the user initiates the timer, the glowing line takes the prescribed amount of time to fill the loop.
When complete, the loop stays lit until acknowledged by the user.
When acknowledged, the tail of the glowing line chases the head and returns to being a single point at the top of the screen.
Repeat

The code controlling the animation is all wrapped in a subclass of UIView:

class LoopView: UIView {
  //  ...

  lazy var path: UIBezierPath = initializedPath()
  lazy var animationLayer: CAShapeLayer = initializedAnimationLayer()

  override func draw(_ rect: CGRect) {
    layer.addSublayer(animationLayer)
    //  ...
  }

  //  ...
}

Here are the path and animation layer initializations:

  private func intializedPath() -> UIBezierPath {
    return UIBezierPath(ovalIn: bounds)
  }

  private func initializedAnimationLayer() -> CAShapeLayer {
    let layer = CAShapeLayer()
    let transform = CGAffineTransform(rotationAngle: 1.5 * CGFloat.pi).translatedBy(x: -bounds.width, y: 0)

    layer.path = path.cgPath
    layer.setAffineTransform(transform)

    layer.strokeColor = timerColor.cgColor
    layer.fillColor = UIColor.clear.cgColor
    layer.lineCap = kCALineCapRound
    layer.lineWidth = lineWidth

    layer.shadowColor = timerColor.cgColor
    layer.shadowRadius = 5.0
    layer.shadowOpacity = 1
    layer.shadowOffset = CGSize(width: 0, height: 0)

    layer.strokeEnd = CGFloat.leastNormalMagnitude

    return layer
  }

And finally, the meat of the animation:

func animateTimer(over duration: TimeInterval) {
    let head = CABasicAnimation(keyPath: "strokeEnd")
    head.fromValue = CGFloat.leastNormalMagnitude
    head.toValue = 1
    head.duration = duration
    head.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    head.fillMode = kCAFillModeForwards
    head.isRemovedOnCompletion = false

    animationLayer.add(head, forKey: "strokeEnd")
}

func animateTimerReset() {
    UIView.animate(withDuration: 0, animations: { self.animationLayer.strokeStart = 1 }) { (_) in
        self.animationLayer = self.initializedAnimationLayer()
        self.layer.addSublayer(self.animationLayer)
    }
}

Where I spent the most time on figuring it out was that I didn't want to discard the animationLayer every time I wanted to reset the animation. I also had to use different methods of defining the animation for the fill and the collapse, which feels wrong, but trying to use the same strategies wasn't getting the results I wanted.

For reference, the full class code is in this gist


texts: Singly Linked List implementation in Python

texts:
I'm new to Python and thus learning it by implementing a set of commonly used data structures. Here's my implementation of a  LinkedList.
First the Node class.

class Node:

    def __init__(self, value = None, next = None):
        self.value = value;
        self.next = next;

Here's the LinkedList,

from node import Node

class LinkedList:

    def __init__(self):
        self.head = None;
        self.size = 0;

    def insert(self, item):
        curr = Node();
        curr.value = item
        self.size += 1
        if(self.head == None):
            self.head = curr
        else:
            curr.next = self.head
            self.head = curr

    def remove(self, item):
        if(self.head == None):
             raise Exception('Removing from an empty list')
        curr = self.head
        if(curr.value == item):
            self.head = curr.next
            return
        while(curr.next.value != item):
            curr = curr.next
        if(curr.next == None):
            raise Exception('Item not present in list')
        else:
            curr.next = curr.next.next

    def print_list(self):
        curr = self.head;
        while(curr):
            print(curr.value, end=' ')
            curr = curr.next

And finally the calling client,

from linked_list import LinkedList

list = LinkedList()
list.insert(2)
list.insert(5)
list.insert(7)
list.insert(12)
list.insert(13)
list.remove(13)
list.print_list()

My primary language is Java, so I'd invite comments on how pythonic is my implementation and best practices. TIA.


texts: Counting slides shift in javascript object

texts:
Adding Dynamic Slides to a slider used by a client shifts its index, need to account for that so i wrote this simple code, but i think it's pretty lame, is there any way to improve it and accomplish the same output?

var slides = {
  1: {
    content: "",
    group: 1
  },
  2: {
    group: 1
  },
  3: {
    content: "",
    group: 1
  },
  4: {
    content: "",
    group: 2
  },
  5: {
    content: "",
    group: 3
  },
  6: {
    content: "",
    group: 3
  },
  7: {
    content: "",
    group: 3
  },
  8: {
    content: "",
    group: 4
  },
  9: {
    content: "",
    group: 4
  },
  10: {
    content: "",
    group: 4
  },
  11: {
    content: "",
    group: 5
  },
  12: {
    content: "",
    group: 5
  }
};

var shiftCount = [],
  shiftCounter = 0,
  lastgroup, lastcount;
for (var slideIndex in slides) {
  var group = parseInt(slides[slideIndex].group, 10);
  if (group === 1) { //no shift caused by 1st group
    shiftCount.push(0);
  } else {
    if (group !== lastgroup) { //stay on current group.
      lastcount = shiftCount.length;
      lastgroup = group;
      shiftCount.push(shiftCount.length);
    } else { //fill rest of array with repeated count and match length.
      shiftCount.push(lastcount);
    }
  }
}
console.log(shiftCount);

Thanks!


texts:
Is there a way of writing this correctly working query more efficiently? I'm asking only to learn LINQ better:

    var cpuInfo = edgeLPs
        .GroupBy(k => k.CPU.ID, e => e.CPU)
        .ToDictionary(k => k.Key, v => new
        {
            LogicalProcs = v.First().LogicalProcessorsCount,
            Cores = v.First().Cores.Count,
            SMT = v.First().SMT
        });


texts:
I wrote a general purpose library for in-memory cache with custom timeout for each key.

import (
    "strconv"
    "sync"
    "sync/atomic"
    "time"
)

type item struct {
    value   interface{}
    expired bool
    owner   *Cache
    timer   *time.Ticker
}

//Cache of items which can be expired or cancelled (pulled)
type Cache struct {
    generator uint64
    lock      sync.RWMutex
    data      map[string]item
}

//NewCache - create new cache
func NewCache() *Cache {
    return &Cache{data: make(map[string]item)}
}

//Put value to cache with specified time-to-live and return generated unique
// (in terms of one cache) key.
func (cache *Cache) Put(value interface{}, ttl time.Duration) string {
    key := strconv.FormatUint(atomic.AddUint64(&cache.generator, 1), 10)
    it := item{
        value: value,
        owner: cache,
        timer: time.NewTicker(ttl)}
    cache.lock.Lock()
    cache.data[key] = it
    cache.lock.Unlock()
    go func() {
        defer it.timer.Stop()
        <-it.timer.C
        if !it.expired {
            it.owner.Pull(key)
        }
    }()
    return key
}

//Pull key from cache and remove it if it not already expired.
//Returns value and status
func (cache *Cache) Pull(key string) (interface{}, bool) {
    cache.lock.RLock()
    it, ok := cache.data[key]
    cache.lock.RUnlock()
    if !ok {
        return nil, false
    }
    cache.lock.Lock()
    it.expired = true
    it.timer.Stop()
    delete(cache.data, key)
    cache.lock.Unlock()
    return it.value, true
}

General questions:

Could be here a memory leak due to timers channels?
Is a creating new timer for each item a true GOlang way?


texts:
I am wondering if my code is needlessly redundant. I noticed, when looking over my code, that I had a unnecessary variable and if statement. Both Fire() methods achieve the desired result without error (from what I have seen). To me, the redundant Fire() method reads a lot nicer and is my preferable method but I'm just wondering if the alternate Fire() method is still worth the trade-off in readability due to efficiency. I am also wondering if there may be any underlying bugs that may occur in either of my methods that I am unaware of.

Unity version: 4.6.3

Fire()` method result: when the space key is pressed, it spawns a laser that fires upwards towards the enemy at the preset speed and is delayed by the reload time.

Desired result: when the space key is pressed, spawns a laser and has it fire in an upwards direction towards the enemies at the preset speed and than have a delay equal to the preset reload time.

Variables:

public float reloadTime = 0.2f;
public GameObject playerProjectilePrefab;
public float playerProjectileSpeed = 10f;

private bool canShoot = true;
private float reloadCountDown;

Redundant Fire Method:

void Fire (){
    Vector3 startPosition = transform.position + new Vector3(0 ,(renderer.bounds.size.y * 0.5f), 0);

    if (canShoot && Input.GetKey(KeyCode.Space)){
        canShoot = false;
        GameObject playerProjectile = Instantiate(playerProjectilePrefab, startPosition, Quaternion.identity) as GameObject;
        playerProjectile.rigidbody2D.velocity = new Vector3 (0, playerProjectileSpeed, 0);
        reloadCountDown = reloadTime;
    } else if (!canShoot){
        reloadCountDown -= Time.deltaTime;
    }
    if (reloadCountDown <= 0f){
        canShoot = true;
    }
}

Alternate Fire Method:

void Fire (){
    Vector3 startPosition = transform.position + new Vector3(0 ,(renderer.bounds.size.y * 0.5f), 0);

    if (reloadCountDown <= 0f && Input.GetKey(KeyCode.Space)){
        GameObject playerProjectile = Instantiate(playerProjectilePrefab, startPosition, Quaternion.identity) as GameObject;
        playerProjectile.rigidbody2D.velocity = new Vector3 (0, playerProjectileSpeed, 0);
        reloadCountDown = reloadTime;
    } else if (reloadCountDown > 0f){
        reloadCountDown -= Time.deltaTime;
    }
}


texts: ScheduledExecutorService running a couple of scheduleAtFixedRate

texts:
I have created a task that I need to query database for List of String and store it in neededDataList. I will use neededDataList in a scheduled task every 10 minutes to do a simple task.
And I need to retrieve a fresh data of neededDataList every 1 hour. Will the scheduledExecutorService2 pick up the fresh neededDataList?
Can someone review my code if it will cause some problem?
Assuming my code has its main method and it will call the run(Database database):
    public class Handler {

            private static final ScheduledExecutorService scheduledExecutorService1 = MDScheduledExecutorService.wrap(
                        new ScheduledThreadPoolExecutor(1), "ses-1-thread-%d");
            private static final ScheduledExecutorService scheduledExecutorService2 = MDScheduledExecutorService.wrap(
                        new ScheduledThreadPoolExecutor(5), "ses-2-thread-%d");

            private List<String> neededDataList;

            private void run(Database database) {
                scheduledExecutorService1.scheduleAtFixedRate(() -> {
                    neededDataList= database.getNeededData();
                }, 1, 60, TimeUnit.MINUTES);

                scheduledExecutorService2.scheduleAtFixedRate(new HandlerImpl(), 1, 10, TimeUnit.MINUTES);
            }

            private class HandlerImpl implements Runnable {

            @Override
            public void run() {
               executeTask(neededDataList);
            }

            }
}


texts:
I am using below code to write list item to a file. I want only 2 fields from the list. Is there any direct way without looping through all the items to do that? Here serversToshutDown is a SharePoint ListItemCollection.

using (System.IO.StreamWriter file = new System.IO.StreamWriter("F:\test\Test.csv"))
{
    foreach (ListItem item in serversToshutDown)
    {
        context.Load(item);
        context.ExecuteQuery();
        String server = item["Server"].ToString();
        String service = item["Service"].ToString();
        Console.WriteLine(server + "," + service);
        file.WriteLine(server + "," + service);
    }
}


texts: Node.js RethinkDB connection wrapper with built in retries

texts:
I wrote connection logic for a wrapper around RethinkDB in node.js. While it works, I know it can be cleaned up, and done in a better manner. Essentially the logic is start at the first host in config.hosts, if _connect() fails, then try the next host in the array. This continues for three times, or until config.hosts is empty. If __connect() is successful just set rethinkdbConnection to the returned connection object.

var config.hosts = ['10.0.0.1', '10.0.0.2', '10.0.0.3'];
var rethinkdbConnection;

exports.connect = function(config, callback) {
    var rethinkdbConfig = clone(config);
    delete rethinkdbConfig.hosts;

    function _connect(callback) {
        rethinkdbConfig.host = config.hosts.shift();

        r.connect(rethinkdbConfig, function(error, connection) {
            if(error) {
                return callback(error);
            }

            return callback(null, connection);
        });
    }

    _connect(function(error, connection) {
        if(error) {
            if(!config.hosts.length) {
                return callback(error);
            }

            _connect(function(error, connection) {
                if(error) {
                    if(!config.hosts.length) {
                        return callback(error);
                    }

                    _connect(function(error, connection) {
                        if(error) {
                            return callback(error);
                        }
                    });
                }
            });
        } else {
            rethinkdbConnection = connection;
            return callback();
        }
    });
};

What is a better way to write this?

Also it would be great instead of arbitrarily trying _connet() 3 times, to try as many times as the length of config.hosts instead.


texts:
This is the "Popes" problem from UVa Online Judge:

  On the occasion of Pope John Paul II's death, the American weekly magazine Time observed that the largest number of Popes to be selected in a 100-year period was 28, from 867 (Adrian II) to 965 (John XIII). This is a very interesting piece of trivia, but it would be much better to have a program to compute that number for a period of any length, not necessarily 100 years. Furthermore, the Catholic Church being an eternal institution, as far as we can predict it, we want to make sure that our program will remain valid per omnia secula seculorum.

  Write a program that given the list of years in which each Pope was elected and a positive number \$Y\$, computes the largest number of Popes that were in office in a \$Y\$-year period, and the year of election for the first and last Popes in that period. Note that, given a year \$N\$, the \$Y\$-year period that starts in year \$N\$ is the time interval from the first day of year \$N\$ to the last day of year \$N+Y−1\$. In case of a tie, that is, if there is more than one \$Y\$-year period with the same largest number of Popes, your program should report only the most ancient one.

I am a Python beginner. When I submit this code, it says "time limit exceeded". How can I optimize this code?

while True:
    try:
        str=input()
        if len(str):
            Y = int( str )
        else:
            Y = int( input() )
    except:
        break
    N_P = int( input() )
    popes= []
    for i in range (N_P):
        popes.append( int(input()) )
    Y = Y-1
    maximum = 0
    for i in range (N_P):
        j = i
        count = 0
        while(popes[j] <= popes[i] + Y):
            j = j+1
            count = count +1
            if j>= N_P:
                break
            if count>maximum:
                maximum = count
                first = popes[i]
                last = popes[j-1]
    print (maximum,first,last)


texts:
In your opinion, do I need to do all these validations? I thought to do well and stay safe but it seriously raises the question if it isn't slower.

jQuery

$(document).ready(function () {

        // jQuery validate plugin
        $('#login > form').validate({

            rules: {
                username: { required: true },
                password: { required: true }
            },

            submitHandler: function () {

                var credentials = {
                    "username": $('#username').val(),
                    "password": $('#password').val()
                };

                $.post('ajax/tryLogin.php', credentials)
                    .done(function (data) {

                        if (data.hasOwnProperty('success') &&
                            data['success']) {

                            window.location = 'catalog.php';

                        } else if (data.hasOwnProperty('message')) {

                            alert(data['message']);
                        } else {
                            alert('Communication with the server failed.');
                        }
                    })
                    .fail(function () {
                        alert('Communication with the server failed.');
                    })
            }
        });
    });

Ajax PHP

if (empty($_POST['username']) || empty($_POST['password'])) {
    $data['success'] = false;
    $data['message'] = 'Username and password are required.';

} else {

    try {
        $data['success'] = Security::TryLogin($_POST['username'], $_POST['password']);
    } catch (Exception $e) {

        $data['success'] = false;
        $data['message'] = $e->getMessage();
    }
}
header('Content-type: application/json');
echo json_encode($data);

PHP

class Security
{

    //...

    public static function TryLogin($username, $password)
    {
        $username = strtolower($username);
        $password = sha1($password . $username);

        try {
            $user = Users::FindByUsernameAndPassword($username, $password);

            if (session_id() == '') {
                session_start();
            }

            $_SESSION[self::USER_IDENTIFIER] = $user;

            return true;

        } catch (Exception $e) {
            throw new Exception('Username of password incorrect.');
        }
    }

    //...

}


texts: Is usage of friend class appropriate in this case?

texts:
I want to have a class that stores data from an input file, for use in a simulation program. It is like a struct but may require some small functions for accessors.

A seperate class reads all the data from a text input file. I want to store most of this data in the above mentioned object. Therefore this class needs to be able to set the data variables.

My current approach is to give the loader class friend access, so that these variables can be set. No other classes should be able to set the data, therefore I am not using setters.

Is this appropriate friend class usage?

I have included a demonstration example of the situation, as simple as possible:

In reality the data holder I have called "Pod" here, holds 10 to 20 different strongly related variables.

#include <iostream>
class Pod {
 // holds the data that will be used later in simulation
 friend class Loader;
 public:
    double get_angle() {return angle_ * 3 / 180;};
 protected:
    double angle_;
};

class Loader {
 // loads data from text file.
 public:
    bool CheckFile() {
        // checks file:
        return true;
    }
    Pod ReadData() {
        double a = 90; // this line simulates reading from file.
        Pod pod;
        pod.angle_ = a;
        return pod;
    }
};

void DoesThingsWithData(Pod data) {
    std::cout << data.get_angle() << std::endl;
}

int main() {
    Pod my_data;
    {
        Loader loader;

        if (loader.CheckFile()) {
            my_data = loader.ReadData();
        }
    }
    // do things with data
    DoesThingsWithData(my_data);
    return 0;
}


texts:
I am using codeigniter framework in PHP. In signup form I have:

Controller:

$info['csrf_token'] = array('signup'=>$this->csrf_token('signup'));
echo $this->load->view('/signup',$info,TRUE);

// generate token:
public function csrf_token($form_name){
    if (function_exists('mcrypt_create_iv')) {
        $t = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
    } else {
        $t = bin2hex(openssl_random_pseudo_bytes(32));
    }

    $sess_array = array();
    $sess_array[$form_name] = $t;
    $this->session->set_userdata('csrf', $sess_array);

    return $t;
}

View:

<form>
<input type="hidden" name="csrf_token" value="<?=hash_hmac('sha256', 'signup', $csrf_token['signup'])?>" />
</form>

Validation check on form submit:

$csrf_sess = $this->session->userdata('csrf');
if(hash_hmac('sha256', 'signup', $csrf_sess['signup'])==$_POST['csrf_token']){
    return true; // Valid request.
}else{
    return false;
}

Will it prevent website from CSRF (Cross-Site Request Forgery)?


texts:
I was doing a programming question in C++ at HackerRank.  Given a set of up to 500 bitstrings, each up to 500 bits long, the task is to find the pair a and b such that the bitwise OR contains the most 1s.

I solved the question with Time Complexity of O(n3). I can't figure out how i can solve the question with a better time complexity. I looked at Problem-Settlers Code but it was again of the order of O(n3).

#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int n;
    int m;
    cin >> n >> m;
    vector<string> topic(n);
    for(int topic_i = 0;topic_i < n;topic_i++){
        cin >> topic[topic_i];
    }

    int maxSubjects=0, maxTeams=0;

    for(int i=0;i<n;i++){

        for(int j=(i+1);j<n;j++){

            int k=0,sub=0,max=0;

            while(k<m){

                if(topic[i][k] == '1'  || topic[j][k] == '1'){

                    sub++;
                }
                k++;
            }

            if(sub > maxSubjects){

                maxSubjects=sub;
                maxTeams=0;
                maxTeams++;
                continue;
            }

            if(sub == maxSubjects){

                maxTeams++;
            }
        }
    }

    cout<<maxSubjects<<endl;
    cout<<maxTeams<<endl;
    return 0;
}


texts: In React/Redux, fetch a list from a server and create a randomized subset with lifecycle methods

texts:
This is my first React/Redux project. I'm pulling down a list of Google Fonts, then displaying a list of 3 randomly selected ones. I want the list of random fonts to be populated automatically after the data is fetched, but also to be able to be triggered manually.

So, I've decided to put the fetch code in the action creator and the randomizing code in the component. The fetch is activated from componentWillMount() while the randomizing function is called from componentDidUpdate().

This is the only combination I was able to come up with that works without any errors, but it sure looks janky. Is this considered acceptable?

import React, { Component } from 'react';
import Font from './Font';
import PropTypes from 'prop-types';
import { connect } from 'react-redux'
import WebFont from 'webfontloader';

import { fetchFonts, setRandomFonts } from '../actions/fontActions'

export class Fonts extends Component {
  static propTypes = {
    allFonts: PropTypes.array,
    randomFonts: PropTypes.array.isRequired,
    sampleSentence: PropTypes.string.isRequired,
    categoriesWanted: PropTypes.array.isRequired,
    fontCount: PropTypes.number.isRequired,
    fetchFonts: PropTypes.func.isRequired
  }

  componentWillMount() {
    this.props.fetchFonts();
  }

  componentDidUpdate() {
    if (this.props.randomFonts.length === 0) {
      this.randomizeFonts();
    }
  }

  getRandomFont = arr => arr[this.random(arr.length) - 1];
  random = max => Math.floor(Math.random() * max) + 1;

  randomizeFonts = () => {
    const { categoriesWanted, fontCount, allFonts } = this.props;
    const fontList = [];

    if (allFonts.length === 0) return;

    while (fontList.length < fontCount) {
      const font = this.getRandomFont(allFonts);

      // add the font if it's the right category and it's not
      // already in the list
      if (categoriesWanted.includes(font.category)
          && !fontList.includes(font)) {
        fontList.push(font);
      }
    }

    WebFont.load({
      google: {
        families: fontList.map(font => font.family)
      }
    });

    this.props.setRandomFonts(fontList);
  }

  render() {
    return (
      <div className="container">
        {this.props.randomFonts.map(
          font => (<Font
            key={font.family}
            font={font}
            sampleSentence={this.props.sampleSentence}
          />)
        )}
      </div>
    )
  }
}

const mapStateToProps = state => ({
  allFonts: state.fonts.allFonts,
  randomFonts: state.fonts.randomFonts,
  sampleSentence: state.fonts.sampleSentence,
  categoriesWanted: state.fonts.categoriesWanted,
  fontCount: state.fonts.fontCount
});

export default connect(mapStateToProps, { fetchFonts, setRandomFonts })(Fonts);


texts: Determining if the length of LinkedList is even or odd

texts:
Today, I tackled this coding question:
Given a singly-linked list, check whether its length is even or odd in a single pass. An Empty list has 0 nodes which makes the number of nodes in it even.

Would the time complexity of my code be O(n)? Do you guys see any improvements that can be made?

public Boolean isListEven(ListNode head) {

    if(head == null){
        return true;
    }

    if(head.next.next == null){
        return false;
    }

    int count = 1;
    while(head.next != null){
        if(head.next.next != null){
            count = count + 2;
            head = head.next.next;
        }

        count = count + 1;
        head = head.next;
    }

    return (count % 2 == 0);
}


texts: Sierpiński's carpet fractal animation for teaching Python 3

texts:
I am teaching programming (in this case - 1 on 1 tutoring of a teenager interested in programming) and this code will be a final stage of a progression toward program generating a nice image of Sierpiński's triangle.

Any comments how this code can be improved are welcomed! But problems with unclear code that break standard practices are especially welcomed, performance issues are less important here.

from PIL import Image
from PIL import ImageDraw

def save_animated_gif(filename, images, duration):
    # done using https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#saving
    first_image = images[0]
    other_images = images[1:]
    first_image.save(filename, save_all=True, append_images=other_images, duration=duration, loop=0)

def make_pattern(draw, x, y, section_size, remaining_levels):
    if remaining_levels <= 0:
        return
    hole_color = (5, 205, 65)
    corner = (x + section_size / 3, y + section_size / 3)
    # -1 necessary due to https://github.com/python-pillow/Pillow/issues/3597
    opposite_corner = (x + section_size * 2/3 - 1, y + section_size * 2/3 - 1)
    draw.rectangle((corner, opposite_corner), fill=hole_color)
    parts = 3
    for x_index in range(parts):
        for y_index in range(parts):
            x_anchor = x + section_size * x_index / parts
            y_anchor = y + section_size * y_index / parts
            new_size = section_size / 3
            new_levels = remaining_levels - 1
            make_pattern(draw, x_anchor, y_anchor, new_size, new_levels)

def make_carpet(levels, size):
    carpet_color = (5, 60, 20)
    carpet = Image.new("RGBA", (size, size), carpet_color)
    draw = ImageDraw.Draw(carpet)
    make_pattern(draw, 0, 0, size, levels)
    return carpet

levels = 7
size = 3**levels
carpets = []
carpets.append(make_carpet(0, size))
standard_frame_time_in_ms = 1200
durations = [standard_frame_time_in_ms / 2] # first stage visible for a short time
for i in range(levels - 1):
    carpets.append(make_carpet(i + 1, size))
    durations.append(standard_frame_time_in_ms)
durations[-1] *= 4 # final stage of animation visible for a long time

save_animated_gif("Sierpiński's carpet.gif", carpets, durations)

output:

full sized image


texts:
I've written the following custom event system module and I'm planning to use it in production in the future. Before I do that, I'd like to ask for general suggestions on how to improve it. Thanks a lot.
const event = (function() {

  let registry = {};

  function on(event, callback) {
    if(!registry[event]) registry[event] = [];
    registry[event].push(callback);
  }

  function once(event, callback) {
    if(!registry[event]) registry[event] = [];
    registry[event].push(function(message) {
      callback(message);
      off(event, callback);
    });
  }

  function off(event, callback) {
    if(registry[event]) {
      registry[event].splice(registry[event].indexOf(callback), 1);
      if(!registry[event].length) delete registry[event];
    }
  }

  function emit(event, message) {
    if(registry[event]) {
      registry[event].forEach(callback => {
        callback(message);
      });
    }
  }

  function getListeners(event) {
    return registry[event] ? registry[event] : null;
  }

  return {
    on: on,
    once: once,
    off: off,
    emit: emit,
    getListeners: getListeners
  }
})();

export { event };

Usage:
Add event listener:
event.on('someEvent', someEventhandler);

Remove event listener:
event.off('someEvent', someEventhandler);

Add event listener and remove it after first use:
event.once('someEvent', someEventhandler);

Fire the event:
event.emit('someEvent');

Get all eventhandlers for an event:
event.getListeners('someEvent');


texts: Mapping multiple values to an array object

texts:
I've reached a point in an application where I need to initialize some coordinates to an array and I wound up using nested for-in loops to accomplish the task.

Is there is a better way to accomplish this?

class Coord {

    let xVal : Int
    let yVal : Int

    init(x: Int, y: Int) {
        xVal = x
        yVal = y
    }
}

var coord = [Coord]()

for xVal in 0...20 {
    for yVal in 0...20 {
        coord.append(Coord(x: xVal, y: yVal))
    }
}


texts:
Looking for some ideas as to how to improve the below react component.

var JSON_URL = "https://api.example.io/comments.json";
class CommentList extends React.Component {
    constructor() {
        super();
        this.state = { comments: [] }
    }
    componentDidMount() {
        $.ajax({
            url: JSON_URL,
            dataType: 'json',
            success: function(data) {
                this.setState({comments: data.comments});
            }.bind(this)
        });
    };
    render() {
        return <ul> {
            this.state.comments.map((comment) => {
                return <li>{comment.body}—{comment.author}</li>;
            })}
       </ul>;
    }
}
React.render(<CommentList />, document.getElementById('root'));


texts: Brute force passwords in C (CS50 exercise)

texts:
This script attempts to crack passwords by going through all possible 'words', hashing them, and comparing the hash to the input.

It seems to work, but I don't know if I have written 'good' C. I'm looking for advice on what areas would be most important/beneficial to focus on (e.g. efficiency, design, readability, something else?) in the next thing I write and how to improve within those. I also don't feel that comfortable with low level concepts like memory and pointers and I'm not sure if I'm using them right.

I'm not really sure what I want though so please give me whatever advice you think I need.

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

char ALPHABET[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int alphabetSize = 52;

int max_length = 4;

void check(char *guess, char *salt, char *hash)
{
    string hashedGuess = crypt(guess, salt);
    if (!strcmp(hash, hashedGuess))
    {
        printf("%s\n", guess);
        free(guess);
        exit(0);
    }
}

// recursively fill the buffer and check it each time
void brute_force(char *buf, int index, int length, string salt, string hash)
{
    for (int i = 0; i < alphabetSize; i++)
    {
        sprintf(buf + index, "%c", ALPHABET[i]);

        if (index < length)
        {
            brute_force(buf, index + 1, length, salt, hash);
        }
        else
        {
            check(buf, salt, hash);
        }
    }
}

char *crack(string hash, string salt)
{
    // create a buffer big enough to hold the longest possible password
    char *buf = (char *) malloc(max_length + 1);

    // increment guess length starting from 1
    for (int length = 0; length < max_length; length++)
    {
        brute_force(buf, 0, length, salt, hash);
    }
    return "";
}

bool valid_args(int argc, string argv[])
{
    if (argc == 2)
    {
        return true;
    }
    return false;
}

int main(int argc, string argv[])
{
    if (valid_args(argc, argv))
    {
        string hash = argv[1];

        char salt[3];
        strncpy(salt, hash, 2); // salt is first 2 characters of hash

        string password = crack(hash, salt);
    }
    else
    {
        printf("Invalid arguments\n");
        return 1;
    }
    return 0;
}


texts:
The code below simulates a given Newtonian 3 body system. Each row per slice is supposed to represent a Cartesian component for the initial trajectory vector and for the distance vectors to the other two objects.

What are some possible improvements to this? For instance is there any benefit to implement something to cut the redundancy with the duplicate distance vectors? How about using something like NumPy instead of vanilla?

# GRAV_MASS_CONSTANT = 1
# masses = [1, 1, 1]

def updated_trajectory_component(row):
    # a = masses * GRAV_MASS_CONSTANT
    a = 1
    return row[0] + sum([a / i for i in row[1:]])

def updated_distance_component(row):
    return [i - row[0] for i in row[1:]]

def iterate_row(row):
    dist = updated_distance_component(row)
    return [updated_trajectory_component(row)] + dist

def iterate_slice(slice):
    return [iterate_row(i) for i in slice]

def iterate_cube(cube):
    return [iterate_slice(i) for i in cube]

def num_iter(cube, iter):
    print(cube)
    if iter == 1: return iterate_cube(cube)
    else: return num_iter(iterate_cube(cube), iter - 1)

cube = [
    [
        [0, 0.1, 1],
        [0, 1, 0.1],
        [0, 1, 1]
    ],
    [
        [0, 0.1, 1],
        [0, -1, 1],
        [0, -1, 0.1]
    ],
    [
        [0, -1, -1],
        [0, 0.1, -1],
        [0, -1, 0.1]
    ]
]


texts: Group data based on dates to populate a Material Angular table with rowspans

texts:
I have this method that attaches the year and year's rowspan for a TD and Quarter and a Quarter's rowspan for the TD.

Year and Quarter are 2 columns in an Angular Material Table which are calculated from an array of objects one of which property of the object is a date string.

Here is a demo for the code: https://stackblitz.com/edit/angular-ynpmdk

This is my method which works fine, I wanted to review if I can shorten this method, looks very ugly. Open to suggestions.

/**
 * Gets the year/quarter span information and filters what data is to be shown in tabs
 * @param data launch data all
 * @param mode which tab we are on
 */
getGroupData(data: DATA[]) {
  data.sort((a:DATA, b:DATA) =>
    !a.date ? -1
      : !b.date
        ? -1 : (new Date(a.date).getTime() - new Date(b.date).getTime())
  );
  let cYear = data[0];
  let cQuarter = data[0];
  for (let i = 0; i < data.length; i++) {
    if (data[i].date) {
      const curDate = new Date(data[i].date);
      const dateYear = new Date(cYear.date);
      const dateQuarter = new Date(cQuarter.date);

      // Get Year span and Year values
      data[i].year = curDate.getFullYear();
      cYear.year = dateYear.getFullYear();
      if (cYear.year === data[i].year) {
        cYear.yearSpan = (cYear.yearSpan || 0) + 1;
      } else {
        cYear = data[i];
        cYear.yearSpan = 1;
      }
      // Get Quarter span and Quarter values
      data[i].quarter = this.getQuarter(curDate.getMonth());
      cQuarter.quarter = this.getQuarter(dateQuarter.getMonth());
      if (cQuarter.quarter === data[i].quarter) {
        cQuarter.quarterSpan = (cQuarter.quarterSpan || 0) + 1;
      } else {
        cQuarter = data[i];
        cQuarter.quarterSpan = 1;
      }
    } else {
      cYear = cQuarter = data[i];
      cYear.yearSpan = cYear.quarterSpan = 1;
      cYear.year = cYear.quarter = 'TBD';
      if (i === data.length - 1) {
        break;
      } else {
        cYear = cQuarter = data[i + 1];
      }
    }
  }
  return data;
}

/**
 * Get the quarter info from month index
 * @param month month index
 */
private getQuarter(month: number): string {
  return `Q${Math.ceil((month + 1) / 3)}`;
}

A sample data object looks like

{position: 1, name: 'Hydrogen', date: '2016-01-11', symbol: 'H'}

when the method is invoked the record becomes

{
  position: 1,
  name: 'Hydrogen',
  date: '2016-01-11',
  symbol: 'H',
  year: 2016,
  quarter: 'Q1',
  yearSpan: 5, // The other records have 5 entries pertaining to this year
  quarterSpan: 2, // The other records have 2 entries pertaining to this quarter of this year
}

Here is a demo for the code: https://stackblitz.com/edit/angular-ynpmdk?file=src%2Fapp%2Ftable-basic-example.ts


texts: Program that should output nth arrangement of paintings

texts:
I'm currently practicing for the British informatics olympiad by doing past papers.

I'm on question 3 of the 2015 paper and trying to use recursion to solve it. I'm pretty new to using recursion but I'm not sure what I can do to make my recursive function any more efficient.

The program runs fine for the smaller test numbers but for larger ones my program takes upwards of 5 seconds, when it should take 1 second max.

I don't want you to fix my code for me (this is a past question so doing that is pointless), what I want to know is: where I am going wrong with my recursive function and how I can use recursion or similar problem solving techniques in the future more efficiently.

Any help would be much appreciated as I'm going to be doing the test tomorrow!

import java.util.*;

public class Q3_2015 {

    static ArrayList<String> works = new ArrayList<String>();
    //static ArrayList<String> allWorks = new ArrayList<String>(); //used for question 2
    static int counter = 0;
    static String currentFinishedWork;
    static int a;
    static int b;
    static int c;
    static int d;
    static int n;
    static boolean fullwork;

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        a = scan.nextInt();
        b = scan.nextInt();
        c = scan.nextInt();
        d = scan.nextInt();
        n = scan.nextInt();

        for (int aAmount = 0; aAmount < a; aAmount++) {

            works.add("A");
        }

        for (int bAmount = 0; bAmount < b; bAmount++) {

            works.add("B");
        }

        for (int cAmount = 0; cAmount < c; cAmount++) {

            works.add("C");
        }

        for (int dAmount = 0; dAmount < d; dAmount++) {

            works.add("D");
        }

        //System.out.println(works);

        WorksSolver("");

        //System.out.println(allWorks); //used for question 2
        System.out.println(currentFinishedWork);

    }

    public static void WorksSolver (String currentWork) {//, int aWorksLeft, int bWorksLeft, int cWorksLeft, int dWorksLeft) {

        if (counter == n) {//allWorks.size() == n) { //used for question 2

            //System.out.println("hhee");
            return;
        }

        fullwork = true;

        if (currentWork.length() - currentWork.replaceAll("A", "").length() < a) {

            fullwork = false;
            WorksSolver(currentWork + "A");
        }

        if (currentWork.length() - currentWork.replaceAll("B", "").length() < b) {

            fullwork = false;
            WorksSolver(currentWork + "B");
        }

        if (currentWork.length() - currentWork.replaceAll("C", "").length() < c) {

            fullwork = false;
            WorksSolver(currentWork + "C");
        }

        if (currentWork.length() - currentWork.replaceAll("D", "").length() < d) {

            fullwork = false;
            WorksSolver(currentWork + "D");
        }

        if (fullwork) {

            currentFinishedWork = currentWork;
            counter ++;
            //allWorks.add(currentWork); //used for question 2
        }

        //if (aWorksLeft == 0 && bWorksLeft == 0 && cWorksLeft == 0 && dWorksLeft == 0) {
    //}

    }
}


texts: Questions & Responses: Let me tell you about you

texts:
Please review this code.

import java.util.Scanner;
import java.util.* ;
public class LMComplex {
Scanner name  = new Scanner(System.in);
Scanner age  = new Scanner(System.in);
Scanner gender  = new Scanner(System.in);
Scanner height  = new Scanner(System.in);
String usrname;
String usrage;
String usrgender;
Double usrheight;
public void main(){
System.out.println("Enter your name: ");
usrname = name.nextLine();
System.out.println("Enter your age(Numbers): ");
usrage = age.nextLine();
System.out.println("Enter your gender(male/female): ");
usrgender = gender.nextLine();
System.out.println("Enter your height(feet.inches . 5 feet 5 inches = 5.5): ");
usrheight = height.nextDouble();
Double rusrheight = Math.ceil(usrheight);
if(rusrheight > usrheight)
{
rusrheight = rusrheight - 1;
}
else
{

}
Double rusrheightininches = usrheight - rusrheight;
if(rusrheightininches >= 0.10 && rusrheightininches < 0.12)
{
rusrheightininches = rusrheightininches * 100;
} else {
rusrheightininches = rusrheightininches * 10;
}
Double rusrheightinincheschecker = rusrheightininches;
rusrheightininches = Math.ceil(rusrheightininches);
if(rusrheightininches > rusrheightinincheschecker)
{
rusrheightininches = rusrheightininches - 1;
}
else
{

}
System.out.println("Hii " + usrname + ". I am Cartic, a basic textual virtual personal assistant. I do know that you are " + usrage +" years old. You are a " + usrgender + " and are " + rusrheight + " feet " + rusrheightininches + " inch(es) tall");
}
}


texts: Finding a max element in an array in Java

texts:
Created the following method:

public static int max(int[] array) {
    int max = Integer.MIN_VALUE;

    for (int value : array) {
        if (value > max) {
            max = value;
        }
    }
    return max;
}

Question(s):

I believe the Big O Notation for this implementation is O(n), am I right?
Since this is basically a search algorithm, how to make it faster (e.g. should use recursion) and if so what would the Big O Notation be for the optimized version?


texts: Nesting loops on same array but skipping same element

texts:
I'm having a bit of trouble trying to find a more Rubyist way to achieve the following. Essentially, I want to try and iterate over every element e and apply e.method(n) for every \$n \in \text{array}\$, \$n \ne e\$. In order to determine whether or not \$n = e\$, I'll have to use an index comparison (really just test for reference equality as opposed to functional equality).

arr = [413, 321, 654, 23, 11]
(0...arr.length).each do |outer_i|
    (0...arr.length).each do |inner_i|
        next if outer_i == inner_i
        arr[outer_i].apply arr[inner_i]
    end
end

This reeks of Java/C++ and I can tell that this is not the Ruby way, but I can't seem to find an alternative. Any ideas to improve its Ruby-ness? I was thinking of Array#product but I'm not sure where to go from there.


texts: Binary search tree in C++ 17 using iterator pattern

texts:
I am new to C++ and am attempting to write the following binary search tree using the iterator pattern (and std::optional in C++17):

#include <memory>
#include <optional>
#include <stack>

template <typename T>
class BinarySearchTree {
public:
  BinarySearchTree(T key)
  : key_(key),
    left_(nullptr),
    right_(nullptr) {}

  BinarySearchTree(const BinarySearchTree& bst) {
    key_ = bst.key_;
    left_ = std::make_unique<BinarySearchTree>(*bst.left_);
    right_ = std::make_unique<BinarySearchTree>(*bst.right_);
  }

  void insert(T key);

  T key() { return key_; }
  std::unique_ptr<BinarySearchTree> left() { return std::make_unique<BinarySearchTree>(*left_); }
  std::unique_ptr<BinarySearchTree> right() { return std::make_unique<BinarySearchTree>(*right_); }

private:
  T key_;
  std::unique_ptr<BinarySearchTree> left_;
  std::unique_ptr<BinarySearchTree> right_;
};

template <typename T>
void BinarySearchTree<T>::insert(T key) {
  auto insert = [key](auto& node) {
    if (node) {
      node->insert(key);
    } else {
      node = std::make_unique<BinarySearchTree>(key);
    }
  };

  if (key <= key_) {
    insert(left_);
  } else {
    insert(right_);
  }
}

template <typename T>
class BinarySearchTreeIterator {
public:
  BinarySearchTreeIterator(BinarySearchTree<T>& bst, bool forward)
  : bst_(std::make_unique<BinarySearchTree<T>>(bst)),
    forward_(forward) {}

  std::optional<T> operator*() { return current_; }

  void operator++() {
    while (bst_ || !stack_.empty()) {
      if (bst_) {
        stack_.emplace(std::make_unique<BinarySearchTree<T>>(*bst_));
        bst_ = std::make_unique<BinarySearchTree<T>>(*(forward_ ? bst_->left() : bst_->right()));
      } else {
        bst_ = std::make_unique<BinarySearchTree<T>>(*(stack_.top()));
        stack_.pop();
        current_ = bst_->key();
        bst_ = std::make_unique<BinarySearchTree<T>>(*(forward_ ? bst_->right() : bst_->left()));
        break;
      }
    }
  }

private:
  std::unique_ptr<BinarySearchTree<T>> bst_;
  bool forward_;
  std::stack<std::unique_ptr<BinarySearchTree<T>>> stack_;
  std::optional<T> current_;
};

I am not sure if my usage of std::unique_ptr is correct or idiomatic.


texts: Merge Sort Implementation in Java (that seems slow...)

texts:
I decided to write my own implementation of merge sort. Here is the code:

public static int[] mergeSort(int[] array) {
    if (array.length <= 1) {
        return array;
    }
    int half = array.length / 2;
    return merge(mergeSort(Arrays.copyOfRange(array, 0, half)),
            mergeSort(Arrays.copyOfRange(array, half, array.length)));
}

private static int[] merge(int[] array1, int[] array2) {
    int len1 = array1.length, len2 = array2.length;
    int totalLength = len1 + len2;
    int[] result = new int[totalLength];
    for(int i = 0, i1 = 0, i2 = 0; i < totalLength; ) {
        if(i1 >= len1) {
            while(i2 < len2) {
                result[i++] = array2[i2++];
            }
            break;
        } else if(i2 >= len2) {
            while(i1 < len1) {
                result[i++] = array1[i1++];
            }
            break;
        }
        if(array1[i1] > array2[i2]) {
            result[i++] = array2[i2++];
        } else {
            result[i++] = array1[i1++];
        }
    }
    return result;
}

When used like:

public static void main(String[] args) {
    Random random = new Random();
    int[] array = new int[10000];
    for(int i = 0, len = array.length; i < len; i++) {
        array[i] = random.nextInt(25000);
    }
    long before = System.nanoTime();
    System.out.println(toString(array) + "\n\n" + toString(mergeSort(array)) + "\nSorted in: " + (System.nanoTime() - before) + " nanoseconds.");
}

private static String toString(int[] array) {
    StringBuffer sb = new StringBuffer("[ ");
    int len = array.length;
    for(int i = 0; i < len - 1; i++) {
        sb.append(array[i] + ", ");
    }
    sb.append(array[len - 1] + " ]");
    return sb.toString();
}

A sample output would be:

[ 8828, 11730, 24944, 18351, 24154, 12634, ... 18114, 3517, 221, 1808, 10474, 18710, 10050, 505, 11304, 5945, 19927, 652 ]

[ 0, 14, 21, 23, 24, 25, 27, 35, 35, ... 24926, 24928, 24929, 24931, 24932, 24935, 24936, 24937, 24937, 24940, 24940, 24992 ]

Sorted in 79326188 nanoseconds.

Another sample output:

[ 11905, 14630, 17973, 9145, 10181, 20421, 24063, 13459, 5806, 22352, 1880, 24100, ... 14299, 15733, 2189, 16743, 6046, 331, 11915, 4008, 14482, 3785, 921, 13954 ]

[ 3, 5, 8, 9, 9, 14, 17, 17, 18, 19, 21, 23, 26, 27, 28, 28, 30, 35, 36, 39, 44, 46, 47, 48, 50, 54, ... 24982, 24983, 24983, 24987, 24989, 24991, 24993, 24995, 24997 ]

Sorted in 23808700 nanoseconds.

The average time needed to sort each number is ((79326188 / 10000) + (23808700 / 10000)) / 2 = 515.67444 nanoseconds, which to me seems a bit slow. Is this implementation as optimized as it can get, or is there a faster way?


texts:
I have created a mvc application for booking space. In this for booking user can applied coupon for booking.

I have implemented one coupon service and validate coupon.

public class Coupon
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Enum.Enum_DiscountType DiscountType { get; set; }
    public Enum_DiscountTypeAppliedOn DiscountTypeAppliedOn { get; set; }
    public decimal DiscountValue { get; set; }
    public decimal? MaximumDiscountAmount { get; set; }
    public string CouponCode { get; set; }
    public DateTimeOffset StartDate { get; set; }
    public DateTimeOffset EndDate { get; set; }
    public Enum_CouponLimitationType CouponLimitationType { get; set; }
    public int? LimitationTimes { get; set; }
    public bool Status { get; set; }
    public Enum_CouponStatus CouponStatus
    {
        get
        {
            return Status ? Enum_CouponStatus.Active: Enum_CouponStatus.InActive;
        }
    }
    public Enum_CouponAssignedTo CouponAssignedTo { get; set; }
    public string Postcodes { get; set; }
    public bool UseMaximumDiscountAmount { get; set; }
    public virtual ICollection<CouponUsageHistory> CouponUsageHistory { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
}

My coupon service contains below class for validation

 public async Task<bool> IsAppliedCouponValid(Coupon coupon, string userID, Order order, int? categoryID)
    {
        if (coupon == null)
            return false;

        if (coupon.Status == false)
            return false;

        //check date range
        var now = DateTime.UtcNow;
        var startDate = coupon.StartDate;
        if (startDate.CompareTo(now) > 0)
            return false;

        var endDate = coupon.EndDate;
        if (endDate.CompareTo(now) < 0)
            return false;

        //check coupon applied limitations
        var isValid = await CheckCouponLimitations(coupon, userID);
        if (!isValid)
            return false;

        return true;
    }

CheckCouponLimitations method contains

 private async Task<bool> CheckCouponLimitations(Coupon coupon, string userID)
    {
        if (coupon == null)
            throw new ArgumentNullException("coupon");

        switch (coupon.CouponLimitationType)
        {
            case Model.Enum.Enum_CouponLimitationType.Unlimited:
                {
                    return true;
                }
            case Model.Enum.Enum_CouponLimitationType.NTimesOnly:
                {
                    var totalUsage = await GetAllCouponUsageHistory(coupon.ID);
                    return totalUsage.Count < coupon.LimitationTimes.Value;
                }
            case Model.Enum.Enum_CouponLimitationType.NTimesPerCustomer:
                {
                    //registered customer
                    var totalUsage = await GetAllCouponUsageHistory(coupon.ID, userID);
                    return totalUsage.Count < coupon.LimitationTimes.Value;
                }
            default:
                break;
        }
        return false;

    }

I have implemented like above and also calculate order after applied coupon also generate new coupon dynamically.

Please suggest me to best way to design this code and give some feedback for review code.


texts:
Here is a problem I am trying to solve: trying to find missing photographs from a sequence of filenames. The problem boils down to: given an unsorted list of integers, return a sorted list of missing numbers. Below is my code.

What I am looking for are:

Are there more efficient algorithms?
Is there any performance problem if the list is large (tens of thousands)
Corner cases which does not work?

def find_missing_items(int_list):
    '''
    Finds missing integer within an unsorted list and return a list of
    missing items

    >>> find_missing_items([1, 2, 5, 6, 7, 10])
    [3, 4, 8, 9]

    >>> find_missing_items([3, 1, 2])
    []
    '''

    # Put the list in a set, find smallest and largest items
    original_set  = set(int_list)
    smallest_item = min(original_set)
    largest_item  = max(original_set)

    # Create a super set of all items from smallest to largest
    full_set = set(xrange(smallest_item, largest_item + 1))

    # Missing items are the ones that are in the full_set, but not in
    # the original_set
    return sorted(list(full_set - original_set))

if __name__ == '__main__':
    import doctest
    doctest.testmod()


texts:
If a checkbox is clicked, it will be added to the total, if not, it will be deducted or ignored. (The total number of checkboxes I have in real is 25.)

Is there a way to write the code below in a shorter version?

Function

function tblcheckboxes(){
    var a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, total;
    if ($('#tcbx1').is(":checked")) {
         a = parseFloat($("#tcbx1").val(), 10);
    }
    if ($('#tcbx2').is(":checked")) {
         b = parseFloat($("#tcbx2").val(), 10);
    }
    if ($('#tcbx3').is(":checked")) {
         c = parseFloat($("#tcbx3").val(), 10);
    }
    if ($('#tcbx4').is(":checked")) {
         d = parseFloat($("#tcbx4").val(), 10);
    }
    if ($('#tcbx5').is(":checked")) {
         e = parseFloat($("#tcbx5").val(), 10);
    }

jQuery

$(document).ready(function(){
    $('#tcbx1').click(function(){
            tblcheckboxes();
    });
    $('#tcbx2').click(function(){
            tblcheckboxes();
    });
    $('#tcbx3').click(function(){
            tblcheckboxes();
    });
    $('#tcbx4').click(function(){
            tblcheckboxes();
    });
    $('#tcbx5').click(function(){
            tblcheckboxes();
    });
   });


texts:
Here's a followup to Minimal entity component system. Please see that question for background.

-- ecs.lua

local unpack = table.unpack or _G.unpack

local function addComponent(entity, component, instance)
  entity[component] = setmetatable(instance or {}, { __index = component })
  return entity
end

local function getComponentsTable(entity, components)
  local values = {}
  for i, component in ipairs(components) do
    local value = entity[component]
    if value == nil then return end
    table.insert(values, value)
  end
  return values
end

local function getComponents(...)
  return unpack(getComponentsTable(...) or {})
end

local entityPrototype = {
  addComponent = addComponent,
  getComponents = getComponents,
  getComponentsTable = getComponentsTable,
}

local function createEntity(instance)
  return setmetatable(instance or {}, { __index = entityPrototype })
end

local function createSystem(components, process)
  local function handle(entity)
    local values = getComponentsTable(entity, components)
    if values then
      process(entity, unpack(values))
    end
  end

  return function(entities)
    for i, entity in ipairs(entities) do
      handle(entity)
    end
  end
end

local function each(entities, components)
  local i = 0
  return function()
    while true do
      i = i + 1
      local entity = entities[i]
      if not entity then return end
      local values = getComponentsTable(entity, components or {})
      if values then return entity, unpack(values) end
    end
  end
end

return {
  createEntity = createEntity,
  addComponent = addComponent,
  getComponents = getComponents,
  getComponentsTable = getComponentsTable,
  createSystem = createSystem,
  each = each,
}

This version adds the following features:

System callbacks now receive not only the entity, but also any components listed in the first argument to createSystem. In other words you can do this now:

local rectangleRenderingSystem = ecs.createSystem(
  { 'position', 'rectangle' },
  function (entity, pos, rect)
    ui.drawRect(pos, rect)
  end)

This is nice, because if you switch from string-keyed components to table-keyed components (using addComponent), nothing in the function body needs to change.
There is a new function getComponents which does something similar.

local foo, bar = ecs:getComponents(someEntity, { 'foo', 'bar' })
-- or
local foo, bar = someEntity:getComponents({ FooComponent, BarComponent })

There is a new function each which is pretty useful. It takes an array of entities as its first argument, and an array of components as the second argument. It returns a function which iterates over all of the entities having matching components, returning the entity followed by each component in the list, just like the argument lists the systems callbacks receive. In other words you can do something like this:

     -- stop all the monsters
     -- we don't care about the value of the monster component, only that it exists
     for entity, vel in ecs.each(entities, { 'velocity', 'monster' }) do
       vel.vx = 0
       vel.vy = 0
     end

For a usage example, see Pong game built on a minimal entity component system.


texts:
Use Case

Creating a generic and reusable predicate with closures that supports Float, Double, Integer, float, double, and integer.

Problem

Extending "Number" doesn't allow for the modulo operator.

Code

Below is the form I'd like the code to be. However, Number doesn't support the modulo function.

public <T extends Number> Predicate<T> isDivisibleBy(T divisor) {
    return (T dividend) -> dividend % divisor == 0;
}

Current Solution

The current solution I have uses method overloading, but just doesn't seem DRY. How can I improve this code?

public Predicate<Integer> isDivisibleBy(Integer divisor) {
    return dividend -> dividend % divisor == 0;
}

public Predicate<Float> isDivisibleBy(Float divisor) {
    return dividend -> dividend % divisor == 0;
}

public Predicate<Double> isDivisibleBy(Double divisor) {
    return dividend -> dividend % divisor == 0;
}


texts:
The code is just to check user session.

'use strict';

import Cookie from 'js-cookie';
import  _ from '../helpers';

module.exports = (event) => {
  const spCookieName = 'sp';
  const suCookieName = 'su';
  try {
    const e = event || {};

    let sp = Cookie.get(spCookieName);
    let isNewDevice = 1;
    if (sp) {
      Cookie.set(spCookieName, sp);
      isNewDevice = 0;
    } else {
      sp = _.uuid();
      Cookie.set(spCookieName, sp);
      isNewDevice = 1;
    }

    let su = Cookie.get(suCookieName);
    let isUserNewIn30Days = 0;
    if (!su) {
      Cookie.set(suCookieName, _.uuid(), { expires: 30 });
      isUserNewIn30Days = 1;
    }

    let pID = Cookie.get('pID'); // page session ID
    if (!pID) {
      pID = _.uuid();
      Cookie.set('pID', pID);
    }

    return {
      uID: sp,
      uNw: isNewDevice,
      uUq: isUserNewIn30Days,
      sID: Cookie.get('sID'),
      pID: pID
    };
  } catch (e) {
    return {};
  }
};


texts:
I'm using this pattern for the first time and wanted to check if this is the correct implementation.

class.validator.strategy.php

abstract class ValidatorStrategy
{
    abstract public function check( $name, $val );

}

class.text.validator.php

class TextValidator extends ValidatorStrategy
{

    public function check( $name, $val )
    {
         //logic here
    }
}

class.number.validator.php

class NumberValidator extends ValidatorStrategy
{

    public function check( $name, $val )
    {
         //logic here
    }
}

class.validator.php

include('validator.strategy.php');
include('class.text.validator.php');
include('class.number.validator.php');
include('class.email.validator.php');

class Validator
{

    //holds strategy object
    protected $validatorStrategy = array();

    //holds form field
    protected $fields = array();

    public function __construct()
    {
        $this->validatorStrategy[ 'text' ] = new TextValidator();
        $this->validatorStrategy[ 'number' ] = new NumberValidator();
        $this->validatorStrategy[ 'email' ] = new EmailValidator();
    }

    public function ruleForTextField( $name, $value )
    {
        $this->fields[ $name ][ 'value' ] = $value;
        $this->fields[ $name ][ 'type' ] = 'text';
    }

    public function ruleForNumbertField( $name, $value )
    {
        $this->fields[ $name ][ 'value' ] = $value;
        $this->fields[ $name ][ 'type' ] = 'number';
    }

    public function ruleForEmailField( $name, $value )
    {
        $this->fields[ $name ][ 'value' ] = $value;
        $this->fields[ $name ][ 'type' ] = 'email';

    }

    public function isValidate()
    {
        $status = 0;

        foreach ( $this->fields as $key => $val )
        {
            if ( !$this->validatorStrategy[ $val[ 'type' ] ]->check( $key, $val ) )
            {
                $status++;
            }

        if ( $status == 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

Uses:

$validator = new Validator();
$validator->ruleForTextField('username', $_POST['username'] );
$validator->ruleForNumberField('age', $_POST['age'] );
$validator->ruleForEmailField('email', $_POST['email'] );

if($validator->isValidate())
{
    echo 'validated';
}
else
{
   echo 'fail validation';
}

Inside the isValidate() method, it iterate against all validator strategy and perform appropriate logic.

Is this is the correct way to use this pattern?