texts: RadixSet - a growing-only radix/patricia tree

texts:
I'm looking for a structure to store large amounts of strings (5k to 100k) and then test for existence of new strings against the previous inserted data, in the least possible amount of time (memory is mostly irrelevant). The structure would first be fully loaded at the program start, without any queries. After the building process, it would receive many many queries (about 200 million), then the program exists (no mid-execution destruction). Also, there are about 150-200 simultaneous independent structures in-memory.

Initially I though about a HashSet of string keys. This approach is amortized \$O(1)\$ with the data set size and \$O(K)\$ with the the query string size. However, the cost includes some collision handling and bucketing. I learned about Radix Trees, which perform the insert and query operations in the same time complexity as a hash set of strings, but with less overhead.

When I went to search the web for a good implementation, most implementations offer more functionality than needed, bringing some additional overhead. Some build the structure as a map instead of a set, or have operations like removing items and checking for prefixes, that are not needed at all and may incur some performance penalty on the two needed operations. Or worse, they do not deal with non-ASCII strings.

Since there are only two operations and the Radix Tree is not that complex, I thought I could roll it on my own. Even though I'm not proficient in C++, the project runs it (not to mention the performance needs).

Here is my current implementation:

#ifndef radixset_hpp
#define radixset_hpp

#include <string>

class radixset {
public:

   radixset() : isword(false), children(nullptr) { }

   ~radixset() {
      if (children != nullptr) {
         for(auto i = 0; i < 256; i++) {
            delete children[i];
         }
         delete children;
      }
   }

   void insert(std::string str) {
      radixset* node = this;
      for (unsigned char c : str) {
         if (node->children == nullptr) {
            node->children = new radixset*[256];
         }
         node->children[c] = new radixset;
         node = node->children[c];
      }
      node->isword = true;
   }

   bool contains(std::string str) {
      radixset* node = this;
      for (unsigned char c : str) {
         if (node == nullptr || node->children == nullptr) {
            return false;
         }
         node = node->children[c];
      }
      return node->isword;
   }

private:
   bool isword;
   radixset** children;
};

#endif

And a basic set of tests:

#include "radixset.hpp"
#include <cassert>

int main() {
   radixset r = radixset{};

   assert(!r.contains(""));
   assert(!r.contains("abc"));
   assert(!r.contains("def"));

   r.insert("abc");
   r.insert("def");
   r.insert("");

   assert(r.contains("abc"));
   assert(r.contains("def"));
   assert(r.contains(""));
   assert(!r.contains("ab"));
   assert(!r.contains("defg"));

   assert(!r.contains("áý"));
   r.insert("áý");
   assert(r.contains("áý"));
}

The assertions all work as intended. Although every critic is welcome, I'm mostly looking for 1) performance increase, 2) the pointers here are really ugly (radixset** children, really?), a less headache-y/more modern version would be nice.

If it matters, my make runs the line:

g++ -Wall -std=c++11 radixset.hpp test.cpp -o output/test`

I'm on a Linux/Debian 8 system. I haven't yet spent time choosing compiler flags, don't bother with that. Also, I know the documentation is missing.

Side question: is the contains operation thread-safe? Since it only reads (not writing) members I'm inclined to guess so, but I find the C++ world so confusing...


texts:
I got tasked with writing a page that will add as many profile entries as the user wants, and web programming is not at all my field. There are multiple input groups but I'm just using the "age" one as an example. Currently I'm using a function to create DOM elements, then I assemble them together and return the completed outer HTML code. Is this the correct way to do this? Here's my code:
function addInputGroup(userID, userAge) {
                let ageCol = document.createElement('div');
                ageCol.setAttribute('class', 'col-4');

                let ageLabel = document.createElement('label');
                ageLabel.setAttribute('class', 'sr-only');
                ageLabel.innerHTML = "Age";

                let ageInputGroup = document.createElement('div');
                ageInputGroup.setAttribute('class', 'input-group');

                let ageInputGroupPrepend = document.createElement('div');
                ageInputGroupPrepend.setAttribute('class', 'input-group-prepend');

                let ageInputGroupText = document.createElement('div');
                ageInputGroupText.setAttribute('class', 'input-group-text');
                ageInputGroupText.innerHTML = "Age";

                let ageInput = document.createElement('input');
                ageInput.setAttribute('id', 'fldAge'+userID);
                ageInput.setAttribute('type', 'text');
                ageInput.setAttribute('class', 'form-control');
                ageInput.setAttribute('placeholder', userAge);
                ageInput.setAttribute('value', userAge);

                //assemble age column
                ageInputGroupPrepend.appendChild(ageInputGroupText);
                ageInputGroup.appendChild(ageInputGroupPrepend);
                ageInputGroup.appendChild(ageInput);
                ageCol.appendChild(ageLabel);
                ageCol.appendChild(ageInputGroup);

                return(ageCol.outerHTML);
            }

Then I call document.write(addInputGroup("12345", "18")); when I need to create an "age" input group.
Does this look correct?


texts: Coding Practice - Float* -> Vector3* cast

texts:
If you were given the following:

#include <cassert>

struct vec {
    float x,y,z;
    vec(float x, float y, float z) : x(x), y(y), z(z) {}
};

int main() {
    float verts[] = {1,2,3,4,5,6,7,8,9}; // length guaranteed to be a multiple of 3
    assert(sizeof(vec) == sizeof(float) * 3);

    // Option 1
    for (int i = 0; i < 3; ++i) {
        auto a = reinterpret_cast<vec*>(verts)[i];
        // ...
    }

    // Option 2
    for (int i = 0; i < 9; i += 3) {
        vec a(verts[i], verts[i+1], verts[i+2]); // -O3 averts the copy, so d/w
        // ...
    }

    return 0;
}

Which is considered better practice?

The advantage to the latter option is of course far more explicit, and carries all the advantages/disadvantages that contains; but may not be portable depending on the assertions you can make.


texts: Inserting strings in middle of a text file using streams

texts:
I have a text file in a specific format that I pass as the input of my program.  I then want to write the output back to that same file.  The format is as follows:

Input1:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7
-----------------------------------------
Input2:
1 2 3 8 5 6 7

1 2 3 9 5 6 7

1 2 3 10 5 6 7
-----------------------------------------
Input3:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7

If I want to process Input2 and add the output, the resulting file should be:

Input1:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7
-----------------------------------------
Input2:
1 2 3 8 5 6 7

1 2 3 9 5 6 7

1 2 3 10 5 6 7
    output: 1 2 3 4 5 6 7
-----------------------------------------
Input3:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7

I am looking for a way to insert lines into that section.  For that I wrote the following routine:

//string fileName: Filename on which read and write operation are being done
//int outputNumber: Number of output to be written
//int nInputLine: How many lines each input is taking
//int nOuputLine: How many lines each output is taking. For now it is not
//being used
//string outpur: Output to be Written
void CFirstIO::WriteOutPut(string fileName, int outPutNumber, int
 nInputLine, int nOutPutLine, string outPut)
{
  ifstream fileSt(fileName.c_str(),ios::binary);
      if(fileSt.good() && fileSt.is_open())
  {
    //Storing the content of the file in a string
    fileSt.seekg(0,ios::end);
    int nLength=fileSt.tellg();
    fileSt.seekg(0,ios::beg);
    char *buff = new char[nLength];
    fileSt.read(buff,nLength);
    string strFileContent(buff);
    delete []buff;

    string strToFind;
    char formatinput[256];
    sprintf(formatinput,"Input%d:",outPutNumber);
    strToFind+=formatinput;

    fileSt.seekg(0,ios::beg);
    int nPos= strFileContent.find(strToFind,0);
    fileSt.seekg(nPos);

    //Trying to reach at the bytes Number where I want to insert the
    //output
    string sLine;
    for(int i=0; i<nInputLine+1;i++)
    {
        if(!fileSt.eof() && fileSt.good())
        getline(fileSt,sLine);
    }

    nPos=fileSt.tellg();
    strFileContent.insert(nPos,outPut);
    fileSt.close();

    ofstream fileOut(fileName.c_str(),ios::out|ios::trunc);
    fileOut<<strFileContent;

    fileOut.close();

    }
}

This function works, but adds some unintended characters at the end of the file when reading the whole file in the buffer.

All in all, this function does not look nice to me as I feel like I'm not using the full potential of the standard library.  How could my code be improved?


texts:
I wrote this code, as a novice a to Prolog, for a challenge posted on /r/DailyProgrammer. The formal description of this challenge, as presented in the prompt reads:

  Input description

  On console input you will be given a variable number of 0's and 1's
  that correspond to letters in the alphabet [a-z] and whitespace ' '.
  These will be integers coming in, it's your job to cast them however
  you need.

  Output description

  The program should output the english translation (or other languages
  if you feel so inclined!) of the binary phrase

This is a fairly simple task so, even as a novice to Prolog, it didn't take me long to complete.

main(Words):-
    open('text.txt',read,Stream),
    readAll(Stream,Codes),
    close(Stream),
    atom_codes(Words,Codes).

readAll(Stream,[]):-
    at_end_of_stream(Stream).
readAll(Stream,Out):-
    readBinary(Stream,8,Out2),
    readAll(Stream,Out3),
    Out = .(Out2,Out3).

readBinary(_,0,0).
readBinary(Stream,Digits,Out):-
    get_code(Stream,A),
    B is (A-48) * 2 ^ (Digits-1),
    Digits2 is Digits - 1,
    readBinary(Stream,Digits2,Out2),
    Out is B + Out2.

text.txt is a text file containing the flowing binary digits encoded as characters in UTF-8:

0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100

Running the code results in the correct output:

  Hello World

The code undoubtedly works, and I even find that I like how it looks. My greatest concern, however, is that this somehow does not maintain style and format standards of Prolog programs. Reading through the code, it reads as a completely imperative program, but I know that Prolog is built off the logic programming paradigm. Is this because of a fault in how I wrote the program, or is the problem that this challenge does not lend itself to logic programming? If the former is correct, how could this be written to better reflect the full capabilities of Prolog?


texts:
I'm newbie in VBA world. I have recently work with a spreadsheet with over 25000 rows and about 50 columns. Every time I calculate this sheet, it takes about 30 minutes to 1 hour to perform the calculation. Basically I have a row with basic formulas and the following rows just differs data from this row (i.e. the same formulas).

For example, I have a data in sheet Cal from A to N, and range from M to AR is calculated based on those data. Row 1 is "master" formulas, and traditionally I fill down this row to the end and press Save to calculate. It takes me 30mins - 1h. Then I build a macro but the problem about time has not been solved yet. The Macro is also attached in Module 1 of the file. Also the main code is:

Here is my code:

Dim n As Long, i As Long
ThisWorkbook.Activate
Sheet9.Cells(3,1).Select
n = Range(Selection, Selection.End(xlDown)).Rows.Count
With ThisWorkbook.Worksheets(9)
Range(Cells(3, 13), Cells(3, 44)).Select
Selection.Calculate
Selection.Copy
For i = 4 To n + 2
With Range(Cells(i, 13), Cells(i, 44))
.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.Calculate
.Value = .Value2
End With
Next i
End With

I hope someone could review and adjust my code or suggest any ideas to perform the calculation faster. I have heard that if code is optimized properly, it just takes about 10 mins to calculation 350.000-row data.

Please help me. Any help would be appreciated.

Thank you.


texts: Passing JSON files through an API - node async

texts:
I am writing a small program which reads some JSON files, passes the content to an API, then saves the response in some more JSON files. A pretty simple task, and the code works fine, but I have been away from node for a few years and wanted to make sure I'm using all this new async stuff right! Any comments welcome.

Node version 10.16.3

'use strict'

require('dotenv').config()
const fs = require("fs")
const util = require("util")
const request = require("request-promise-native")
const pLimit = require("p-limit")

const inputPath = "./input-files/"
const outputPath = "./output-files/"
const limit = pLimit(2) // api limits to 2 concurrent requests on free account

const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)

async function readInputFile(filePath) {
  return JSON.parse(await readFile(filePath))
}

async function callApi(content) {
  const options = {
    uri: "https://api.example.com",
    headers: {
      "key": process.env.API_KEY,
      "Content-Type": "application/x-www-form-urlencoded"
    },
    form: {
      "field": content
    }
  }

  return await request(options)
}

async function processFile(fileName) {
  return readInputFile(inputPath + fileName)
    .then(data => callApi(data))
    .then(response => writeFile(outputPath + fileName, response))
}

const fileNames = fs.readdirSync(inputPath, {
  withFileTypes: true
}).map(item => item.name)

const promises = fileNames.map(fileName => {
  return limit(() => {
    return processFile(fileName)
  })
})

(async() => {
  const result = await Promise.all(promises)
  console.log(`${result.length} files transferred`)
})()


texts:
Upon visiting my website, I check if a cookie is set into the user's browser and proceed to logging him into his account. Currently, I do the cookie check in my init.php file and I am asking where I should put it instead because I don't feel like this is the ideal place to be.

Here is my init.php file:

<?php
session_start();
error_reporting(E_ALL);

require_once "config.php";
require_once "functions/functions.php";
require_once __DIR__ . '/../vendor/autoload.php';

use \App\Core as App;
use \App\Models\Auth\Login as Login;
use \App\Core\Database as Database;

$app = new App\App();

/**
 * Checks if login cookie exists and log in the user
 */
if(isset($_COOKIE['cookie_hash']) && isset($_SESSION['cookie_hash']))
{
    $login = new Login(Database::getInstance());
    $login->cookieLogin($_COOKIE['cookie_hash'], $_SESSION['cookie_hash']);
}

App\FlashMessage::clear();

And yeah this App\FlashMessage::clear(); seems out of place too. Its only purpose is to unset the flash_message session. If you have a suggestion where to move it, I'd appreciate it too. If I get rid of the cookie check, I can then remove these 2 lines:

use \App\Models\Auth\Login as Login;
use \App\Core\Database as Database;

and my code will be much cleaner.

This is how my file structure looks like:

I was thinking about moving it into Public/index.php which only requires the init.php file but I am not sure.


texts: Return sum of three values, excluding values within a specified range

texts:
Is there a way to make my code simpler?

  Given three int values, (a, b, c) return their sum. However, if any of the
  values is a teen -- in the range 13..19 inclusive -- then that value
  counts as 0, except 15 and 16 do not count as a teens. Write a
  separate helper (def fix_teen(n)) that takes in an int value and
  returns that value fixed for the teen rule. In this way, you avoid
  repeating the teen code three times (i.e. "decomposition"). Define the
  helper below and at the same indent level as the main no_teen_sum().

  no_teen_sum(1, 2, 3) → \$6\$
  no_teen_sum(2, 13, 1) → \$3\$
  no_teen_sum(2, 1, 14) → \$3\$

def no_teen_sum(a, b, c):
    if fix_teen(a) == 0 and fix_teen(b) == 0 and fix_teen(c) == 0:
        return 0
    elif fix_teen(a) != 0 and fix_teen(b) != 0 and fix_teen(c) != 0:
        return a + b + c
    elif (fix_teen(a) and fix_teen(b)) != 0:
        return a + b
    elif (fix_teen(b) and fix_teen(c)) != 0:
        return b + c
    elif (fix_teen(a) and fix_teen(c)) != 0:
        return a + c
    elif fix_teen(a) != 0:
        return a
    elif fix_teen(b) != 0:
        return b
    elif fix_teen(c) != 0:
        return c

def fix_teen(n):
    if n in [13, 14, 17, 18, 19]:
        return 0
    else:
        return n


texts:
I'm trying to speed up the following code for summing doubles with full precision, based on a Python recipe from Raymond Hettinger.  Any thoughts on how to make this go faster?

-- Full precision summation based on http://code.activestate.com/recipes/393090/
msum :: [Double] -> Double
msum [] = 0
msum (x:xs) = sum $ foldl' (\ps x' -> reverse (partials x' ps)) [x] xs

partials :: Double -> [Double] -> [Double]
partials x = foldl' (\acc p -> case hilo x p of (hi, 0) -> hi:acc
                                                (hi, lo) -> hi:lo:acc) []

hilo :: Double -> Double -> (Double, Double)
hilo x y | abs x < abs y = hilo y x
         | otherwise = (hi, lo) where hi = x + y
                                      lo = y - (hi - x)

This is already a second draft; you can see a previous version of the code in this gist.


texts: Executing an operator in an RPN evaluator

texts:
Is there any way to take this chunk of an else if and make it its own method? I would need the values of valid and throwLine() to be done in the method containing this if else statement, but I'm around 45 lines in my method which is 15 more than I'm allowed to have for simplicity.

 else if(isOperator(readIn))
         {
            System.out.print(readIn);
            if(myStack.isEmpty())
               valid = false;
            else
               op2 = (Fraction)myStack.pop();

            if(myStack.isEmpty())
            {
               throwLine(readIn);
               valid = false;
            }
            else
            {
               runTheOperator(op2, op1, readIn);
               readIn = stdin.next();
            }


texts:
I have something roughly like this:

# define a function to operate on `Post` queries
Post.defineStatic "postListing", (options) ->
  query = @

  query = query.orderBy args

  if options.condition
    query = query.filter args

  query = query.splice args
  query = query.getJoin args

  # return the in-progress query
  query

I wanted to do it like this, but the library I'm using won't let me:

Post.defineStatic "postListing", (options) ->
  @orderBy args

  if options.condition
    @filter args

  @splice args
  @getJoin args
  # the above line would implicitly return the query

Is there a way to write the first snippet in a cleaner way, maybe with es6 generators? I've tried using a shorter variable name like q but that just makes it messy.


texts:
I tried to solve the Unfriendly Number problem on InterviewStreet:

  There is one friendly number, K, and N unfriendly numbers. We want to find
  how many numbers are there which exactly divide the friendly number,
  but does not divide any of the unfriendly numbers.

  \$1 \le N \le 10^6\$

  \$1 \le K \le 10^13\$

  \$1 \le\$ unfriendly numbers \$\le 10^{18}\$

The algorithm is quite simple:

Find the set S. The set of gcd's of each unfriendly number with the friendly
number.
Find the set of divisors of the friendly number.
Check if a divisor of the friendly number is a divisor of any element in S.

My code, where u is the list of unfriendly numbers, k is the friendly number. nubOrd is the O(n log n) time version of nub.

test u k = length $ filter (not) $ map try divisors
  where try t = or $ map (t `divides` ) (nubOrd $ map (gcd k) u)
        divisors = concat [ [i,div k i] | i<-[1..floor $ sqrt $ fromIntegral k],
                                          i `divides` k]
d `divides` n = n `mod` d == 0

This code exceeds the time limit. The Java version of this algorithm solves the problem fine. Are there any ways to improve this code or is Haskell too slow for solving this problem?


texts: Shell function to convert .png to .svg file

texts:
I needed to convert some custom icons that were in .png format to .svg format and did not want to use an online converter for it.

I could not find an out-of-the-box solution online so I created my own with what I could find.

Out of curiosity and a willingness to learn, as well as to maybe serve the needs of others trying to accomplish the same task I am uploading it here as my first post.

My knowledge on image formats is very minimum at best. My knowledge of shell scripting is at a beginner's stage. My knowledge of coding overall is at hobby level.

I am hoping any comments will help to:

Improve on the overall code quality & readability (also to benefit future maintenance)
Improve on the quality of the actual conversion, make it less lossy.
If possible remove any unneccessary dependencies, as currently potrace is used which wasn't installed by default on my arch system.

My current working setup:

function png_to_svg() {

    ### First use convert to convert to .pnm format ###

    number_of_dots_in_filepath=$(echo "$1" | grep -o "\." | wc -l)
    pnm_filepath=""
    for i in $(seq 1 $number_of_dots_in_filepath); do
        pnm_filepath="$pnm_filepath.$(echo "$1" | cut -f $i -d '.')"
    done

    remove_leading_space=${pnm_filepath#?}
    pnm_filepath="$remove_leading_space.pnm"
    command="convert \"$1\" \"$pnm_filepath\""

    eval "$command"

    ### Second use potrace to convert .pnm to .svg file ###

    svg_filepath="$remove_leading_space.svg"
    command="potrace \"$pnm_filepath\" -s -o \"$svg_filepath\""
    eval "$final_command"

    ### Third and last: remove temporary .pnm file ###

    eval "rm \"$pnm_filepath\""

}

Edited setup after first reply:

function png_to_svg() {

    ### First use convert to convert to .pnm format ###

    pnm_filepath=${1%.*}.pnm
    convert "$1" "$pnm_filepath"

    ### Second use potrace to convert .pnm to .svg file ###

    svg_filepath=${1%.*}.svg
    potrace "$pnm_filepath" -s -o "$svg_filepath"

    ### Third and last: remove temporary .pnm file ###

    rm "$pnm_filepath"

}


texts: unpack a nested dataclass and named tuple

texts:
I want to create a function that unpacks nested dataclasses and namedtuples (or a combination of both)

my attempt

I found this answer about how to unpack a named tuple, and i am simply extending it:

the unpack function

def unpack(obj):
    if isinstance(obj, dict):
        return {key: unpack(value) for key, value in obj.items()}
    elif isinstance(obj, list):
        return [unpack(value) for value in obj]
    elif is_named_tuple_instance(obj):
        return {key: unpack(value) for key, value in obj._asdict().items()}
    elif is_data_class_instance(obj):
        return {key: unpack(getattr(obj, key)) for key in obj.__dataclass_fields__.keys()}
    elif isinstance(obj, tuple):
        return tuple(unpack(value) for value in obj)
    else:
        return obj

the is_data_class_instance function:

def is_data_class_instance(obj):
    data_class_attrs = {'__dataclass_fields__', '__dataclass_params__'}
    return set(dir(obj)).intersection(data_class_attrs) == data_class_attrs

side note, would this be acceptable type hints ?

from typing import NamedTuple, Any, NewType, Union

DataClass = NewType('DataClass', Any)
def unpack(obj: Union[DataClass, NamedTuple, Any]) -> Union[tuple, list, dict, Any]:
    ...


texts: Best way to store the sum of all node depths?

texts:
To sum up all the nodes' depths in any given binary tree, I've written the following recursive algorithm:
def nodeDepths(root):
    final=[0]
    helper(root,0, final)
    return final[0]

def helper(node,d, final):
    if not node:
        return
    final[0]+= d
    helper(node.left,d+1, final)
    helper(node.right,d+1, final)

class BinaryTree:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

My thinking was: as I see each node, add the depth of that node to the final sum, then recursively call on the left and right with final list as an argument. At the end of the recursive call stack, final[0] should have the right value.
Is there a better way to do this? I have concerns about thread safety in general with global variables but is it a better practice to use global variables in this case?


texts: A program to tell you if there are 2 numbers in an array that add to a given sum

texts:
there is a video on life at google about what an interview would be like and so i watched it and decided to go along and come up with a solution to the problem myself and i found it really easy this is the solution i came up with

the question is to make a program to find 2 numbers in an array that add up to a sum return true if two such numbers exists return false if they do not

var gotPair = function(arr, sum) {
  this.data = arr;
  this.sum = sum
  this.check = [];
  this.num = null;
  this.out = false;
  for (var i = 0; i < this.data.length; i++) {
    this.num = this.sum - this.data[i];
    if (check.includes(this.num)) {
      this.out = true;
    }
    this.check.push(data[i]);
  }
  return this.out;
}

did i do a good job?
i made sure it always worked so tell me if its good.
i currently want to work for google and i am 14 so anyone who can help me get there i would be very grateful


texts: Find Todos by Line Number (or any other reference) in Python - Revised as functions

texts:
A new function based version of the code from this question as suggested by @Hlib Babii

I write a lot of TODO's but I never keep track of where they are.

This program will search through files (and recursively through folders if needed) and find any TODO comments and their line number.

The details will be printed to the screen and a file will be generated in the folder which is a csv of the files and TODO details.  This means there is always a local list of TODOs in the folder and this can be stroed in git..

You can choose different filetypes, comments and TODO phrases to suit , so it is not just for python.

GitHub

from os.path import exists
import sys
from glob import glob

def _get_files(path, ext, recursive=False):
    # return a list of files
    return glob(path + f"/**/*{ext}", recursive=recursive)

def _find_todos_in_file(fn, todo_token, comment_start):
    # return a list of todos in the file
    temp_todos = []
    with open(fn, "r") as input_:
        for line_no, line in enumerate(input_):
            if comment_start in line and todo_token in line:
                # check to make sure that it is a true comment and not a variable name.
                # Avoid false positives like :: `TODOs.append(todo) # there are no todos in this line`
                comment_index = line.find(comment_start)
                todo_index = line.find(todo_token)
                if todo_index > comment_index:
                    temp_todos.append([fn, f"Line - {line_no+1}  ::  {line.strip()}"])
    return temp_todos

def find_todos(path, ext, todo_token = 'TODO', comment_start = '#', recursive=False):
    # returns a dictionary of todos
    todos = {}
    files = _get_files(path, ext,recursive=recursive)
    if exists(path):
        for x in files:
            try:
                print(f"Searching  ::  {x}")
                result = _find_todos_in_file(x, todo_token, comment_start)
                if result:
                    todos[x] = result
            except PermissionError:
                pass # not a ext file (possible a folder)
    else:
        raise OSError("Path does not exist.")
    return todos

def show_todos(todos: dict):
    # show todos
    line = "-" * 100
    for k, v in todos.items():
        print(f"\n{line}\n\n{k}")
        for x in v:
            print(f">>>{x[1]}")

def save_csv(todos, ext):
    # save todos to a csv file
    import csv
    for k, v in todos.items():
        k = k.split(ext)[0][:-1]
        with open(f"{k}-TODOS.csv", "w", newline="") as csvfile:
            w = csv.writer(csvfile, delimiter=",", quoting=csv.QUOTE_MINIMAL)
            for row in v:
                w.writerow(row)

if __name__ == "__main__":
    todos = find_todos('.', ext='py', comment_start='#', recursive=True)
    show_todos(todos)
    save_csv(todos, 'py')


texts:
I wrote this below script which basically replaces the one of the column in the df with another column with incremental IDs. The script works perfectly fine but I was wondering if there is a better/efficient way to write this one.

import sys

fh_in = open(sys.argv[1], 'r')
fh_out = open(sys.argv[2], 'w')

count = 1
dict = {}
final = list()

for line in fh_in:
    line = line.strip()
    line = line.split()
    if count < 10:
        dict[line[3]] = "Bra100000" + str(count)
        count = count + 1
    else:
        dict[line[3]] = "Bra10000" + str(count)
        count = count + 1
    test = "{:10s}" .format(dict[line[3]])
    fh_out.write(line[0])
    fh_out.write("\t")
    fh_out.write(line[1])
    fh_out.write("\t")
    fh_out.write(line[2])
    fh_out.write("\t")
    fh_out.write(line[1])
    fh_out.write("\t")
    fh_out.write(test)
    fh_out.write("\t")
    fh_out.write(line[4])
    fh_out.write("\t")
    fh_out.write(line[5])
    fh_out.write("\t")
    fh_out.write(line[6])
    fh_out.write("\t")
    fh_out.write(line[7])
    fh_out.write("\t")
    fh_out.write(line[8])
    fh_out.write("\t")
    fh_out.write(line[9])
    fh_out.write("\t")
    fh_out.write(line[10])
    fh_out.write("\t")
    fh_out.write(line[11])
    fh_out.write("\n")

Input:

A01     158188  158533  Contig545|m.1503        228     +       158188  158533  255,0,0 1       345     0
A01     272139  272465  comp285432_c0_seq1|m.9436       230     -       272139  272465  255,0,0 1       326     0
A01     339617  340806  TCONS_00003584|m.11226  157     -       339617  340806  255,0,0 5       95,127,68,50,432        0,190,467,619,757
A01     888838  889347  Contig1477|m.3679       92      -       888838  889347  255,0,0 1       509     0
A01     1165488 1165761 comp3043338_c0_seq1|m.9546      228     -       1165488 1165761 255,0,0 1       273     0
A01     1167009 1167386 Contig1598|m.4011       238     -       1167009 1167386 255,0,0 1       377     0
A01     1234347 1234827 comp260850_c0_seq1|m.10201      85      +       1234347 1234827 255,0,0 1       480     0

Output:

A01     158188  158533  158188  Bra1000001      228     +       158188  158533  255,0,0 1       345     0
A01     272139  272465  272139  Bra1000002      230     -       272139  272465  255,0,0 1       326     0
A01     339617  340806  339617  Bra1000003      157     -       339617  340806  255,0,0 5       95,127,68,50,432        0,190,467,619,757
A01     888838  889347  888838  Bra1000004      92      -       888838  889347  255,0,0 1       509     0
A01     1165488 1165761 1165488 Bra1000005      228     -       1165488 1165761 255,0,0 1       273     0
A01     1167009 1167386 1167009 Bra1000006      238     -       1167009 1167386 255,0,0 1       377     0
A01     1234347 1234827 1234347 Bra1000007      85      +       1234347 1234827 255,0,0 1       480     0


texts: Optimizing C++ equivalent of Matlab `filter` function

texts:
Minimum working example below. The Matlab filter function filters the input data x using a rational transfer function defined by the numerator and denominator coefficients b and a and initial conditions z. My C++ version of the code is way slower than the Matlab one. My signal x is a huge valarray, a and b are three elements long each and the initial conditions z is just three zeros.

#include <iostream>
#include<ctime>
#include <cstdlib>
using std::rand;
#include <valarray>
using std::valarray;
#include <ctime>

#define D_SCL_SECURE_NO_WARNINGS 1

struct FilterResults
{
    valarray<double> filteredSignal;
    valarray<double> finalConditions;
};

FilterResults Filter(const valarray<double> &b,
    const valarray<double> &a, const valarray<double> &x, const valarray<double> &z)
{
    valarray<double> y(x.size());
    // Pad z
    valarray<double> zOut(a.size());
    std::copy(std::begin(z), std::end(z), std::begin(zOut));

    double Xm, Ym;
    size_t i, n = a.size();
    for (size_t m = 0; m < y.size(); m++)
    {
        Xm = x[m];
        y[m] = b[0] * Xm + zOut[0];
        Ym = y[m];
        for (i = 1; i < n; i++)
        {
            zOut[i - 1] = b[i] * Xm + zOut[i] - a[i] * Ym;
        }
    }
    valarray<double> s = zOut[std::slice(0, zOut.size() - 1, 1)];
    FilterResults r;
    r.filteredSignal = std::move(y);
    r.finalConditions = std::move(s);
    return r;
}

int main() {
    std::srand(std::time(0));
    valarray<double> b{ { (double)rand(), (double)rand(), (double)rand() } };
    valarray<double> a{ { (double)rand(), (double)rand(), (double)rand() } };
    valarray<double> z{ { 0, 0, 0 } };
    valarray<double> x( 500000 );
    for (size_t i = 0; i < 500000; i++)
    {
        x[i] = (double)rand();
    }

    clock_t begin = clock();
    auto r = Filter(b, a, x, z);
    clock_t end = clock();
    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
    std::cout << "elapsed_secs: " << elapsed_secs << std::endl;
    system("pause"); // C++ is 0.184 seconds on my computer, Matlab is 0.006060.
}

Any idea on how to speed it up?


texts:
I have the following enum extension method:

public static IList<SelectListItem> SelectListFor<T>()
{
  Type enumType = typeof(T);

  if (enumType.IsEnum)
  {
    return Enum.GetValues(enumType)
    .Cast<int>()
    .Where(i => !i.Equals(0))
    .Select(e => new SelectListItem()
            {
            Value = e.ToString(),
      Text = GetDisplayName(enumType, Enum.GetName(enumType, e))
    })
    .ToList();
  }

  return null;
}

I can call this by doing

EnumExtensions.SelectListFor<BrochureTypes>()

And it will allow me to create a drop down list for the values in my BrochureTypes enum

However, when I compile the code, I get the following warning:

  CA1004    Consider a design where 'EnumExtensions.SelectListFor()' doesn't require explicit type parameter 'T' in any call to it.

Can I somehow change the above code to overcome this warning? Or should I just suppress the warning?


texts:
I've written a reimplementation of the redis-benchmark in Go and part of that is parsing options from the command line. I evaluated several libraries but nothing I found seem to do what I had in mind.

Here is the code:

// ParseArguments parses a string array and returns a populated Options struct
func ParseArguments(arguments []string) Options {
    options := defaultOptions

    args := arguments[1:]
    var errOptions Options
    for i := 0; i < len(args); i++ {
        if args[i] == "--help" || args[i] == "-h" {
            return Options{ShowHelp: true, HelpText: helpText}
        } else if args[i] == "--host" || args[i] == "-H" {
            i++
            if i >= len(args) {
                return buildHelp("Error: Incorrect parameters specified")
            }
            options.Host = args[i]
        } else if args[i] == "--requests" || args[i] == "-n" {
            options.Requests, errOptions = parseNumber(args, &i)
            if errOptions.ShowHelp {
                return errOptions
            }
        } else if args[i] == "--clients" || args[i] == "-c" {
            options.Connections, errOptions = parseNumber(args, &i)
            if errOptions.ShowHelp {
                return errOptions
            }
        } else if args[i] == "--tests" || args[i] == "-t" {
            i++
            if i >= len(args) {
                return buildHelp("Error: Incorrect parameters specified")
            }
            options.Tests = strings.Split(args[i], ",")
            for i := range options.Tests {
                options.Tests[i] = strings.ToUpper(options.Tests[i])
            }
        } else if args[i] == "--port" || args[i] == "-p" {
            options.Port, errOptions = parseNumber(args, &i)
            if errOptions.ShowHelp {
                return errOptions
            }
        } else {
            return buildHelp(fmt.Sprintf("Error: Invalid parameter: %v", args[i]))
        }
    }

    return options
}

(For more context, the rest of the file is on github).

When gocyclo is run over the code the function gets a complexity of 20. I'm interested in suggestions that could reduce this to below the threshold of 10.


texts: Composing QGIS expression based on a QGIS layer tree

texts:
I am developing a plugin for a GIS (Geographic Information Systems) software which uses Python. I have been using Python for over a year (on-off) and have the following code which works. It basically reads the names of files loaded into the GIS software to compose a QGIS expression for every group of files. Finally it deletes the list, ready for the next group.

The script is quite chunky and uses repetition. I am wondering how would one improve it to make it more compact and run more efficiently?

root = QgsProject.instance().layerTreeRoot()
policy_group = root.findGroup('Names')
formula_score4 = []
formula_score3a = []
formula_score3 = []
formula_score2a = []
formula_score2 = []
formula_score1 = []
for group in policy_group.children():
    for layer in group.children():
        score4 = '"' + layer.layerName() + '_Score' + '"' + ' = 4 OR '
        formula_score4.append(score4)
    for layer in group.children():
        score3a = 'coalesce(' + layer.layerName() + ' = 3, 0.00)*3 OR '
        formula_score3a.append(score3a)
    for layer in group.children():
        score3 = '"' + layer.layerName() + '_Score' + '"' + ' = 3 OR '
        formula_score3.append(score3)
    for layer in group.children():
        score2a = 'coalesce(' + layer.layerName() + ' = 2, 0.00)*2 OR '
        formula_score2a.append(score2a)
    for layer in group.children():
        score2 = '"' + layer.layerName() + '_Score' + '"' + ' = 2 OR '
        formula_score2.append(score2)
    for layer in group.children():
        score1 = '"' + layer.layerName() + '_Score' + '"' + ' = 1 OR '
        formula_score1.append(score1)
    formula1 = "CASE WHEN " + "".join(str(x) for x in formula_score4) + "".join(str(x) for x in formula_score3a) + ">=9 THEN 4 " + "WHEN " + "".join(str(x) for x in formula_score3) + "".join(str(x) for x in formula_score2a) + ">=6 THEN 3 " + "WHEN " + "".join(str(x) for x in formula_score2) + "THEN 2 " + "WHEN " + "".join(str(x) for x in formula_score1) + "THEN 1 ELSE 1 END"
    formula2 = formula1.replace("OR >=9 THEN 4 ", ">=9 THEN 4 ")
    formula3 = formula2.replace("OR >=6 THEN 3 ", ">=6 THEN 3 ")
    formula4 = formula3.replace("OR THEN 2 ", "THEN 2 ")
    final_formula = formula4.replace("OR THEN 1 ELSE 1 END", "THEN 1 ELSE 1 END")
    del formula_score4[:]
    del formula_score3a[:]
    del formula_score3[:]
    del formula_score2a[:]
    del formula_score2[:]
    del formula_score1[:]

I have included a screenshot of running the above code in the Python Console of QGIS. I believe the result is what I was wanting from the code as it matches the same sql expression I wrote manually which is stored in a text file (instead of hardcoding the names of layers and reading the textfile, I wanted a more dynamic approach). Here is the image:

And here is the output for the first group (formatted for readability):

'CASE WHEN "Layer_1a_Score" = 4 OR
"Layer_1b_Score" = 4 OR
"Layer_1c_Score" = 4 OR
"Layer_1d_Score" = 4 OR
"Layer_1e_Score" = 4 OR
"Layer_1f_Score" = 4 OR
coalesce(Layer_1a = 3, 0.00)*3 OR
coalesce(Layer_1b = 3, 0.00)*3 OR
coalesce(Layer_1c = 3, 0.00)*3 OR
coalesce(Layer_1d = 3, 0.00)*3 OR
coalesce(Layer_1e = 3, 0.00)*3 OR
coalesce(Layer_1f = 3, 0.00)*3 >=9
THEN 4 WHEN
"Layer_1a_Score" = 3 OR
"Layer_1b_Score" = 3 OR
"Layer_1c_Score" = 3 OR
"Layer_1d_Score" = 3 OR
"Layer_1e_Score" = 3 OR
"Layer_1f_Score" = 3 OR
coalesce(Layer_1a = 2, 0.00)*2 OR
coalesce(Layer_1b = 2, 0.00)*2 OR
coalesce(Layer_1c = 2, 0.00)*2 OR
coalesce(Layer_1d = 2, 0.00)*2 OR
coalesce(Layer_1e = 2, 0.00)*2 OR
coalesce(Layer_1f = 2, 0.00)*2 >=6
THEN 3 WHEN
"Layer_1a_Score" = 2 OR
"Layer_1b_Score" = 2 OR
"Layer_1c_Score" = 2 OR
"Layer_1d_Score" = 2 OR
"Layer_1e_Score" = 2 OR
"Layer_1f_Score" = 2
THEN 2 WHEN
"Layer_1a_Score" = 1 OR
"Layer_1b_Score" = 1 OR
"Layer_1c_Score" = 1 OR
"Layer_1d_Score" = 1 OR
"Layer_1e_Score" = 1 OR
"Layer_1f_Score" = 1
THEN 1 ELSE 1 END'
...


texts: C++17 Recursive Fibonacci calculation with memoization

texts:
Compiler is g++ 4.2. I'm new to C++, but I've done a lot of data science, web scraping, and some socketing stuff in Python. This code generates the nth Fibonacci number, either with a naive implementation or with caching.
#include <iostream>
#include <string>
#include <unordered_map>
#define BIG unsigned long long int

std::unordered_map<int, BIG> umap;

int fib(int n) {
    if (n < 2) {
        return n;
    }
    return fib(n-1) + fib(n-2);
}

BIG fib_with_memo(int n) {
    if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it
        BIG val = fib_with_memo(n-1) + fib_with_memo(n-2);
        umap[n] = val;
        return val;
    }
    return umap[n]; // otherwise return the cached value
}

int main(int argc, char** argv) {
    umap[0] = 0;
    umap[1] = 1;

    int input = std::stoi( std::string(argv[1]) );

    std::cout << fib_with_memo(input) << std::endl;
    return 0;
}

I used a std::unordered_map (hash table) because its lookup/insertion times are \$O(1)\$ (compared to the std::map, which has \$O(log(n))\$ for both.)


texts: Create CSV file of domain groups and their users

texts:
I'm fairly new to scripting in Python. I'm looking for suggestions on improving any of the following in the below script: my coding style, performance, readability, commenting, or anything else.

"""
META
Author: James Nicholson
Date: 8/16/2013

DESCRIPTION
This script takes a list of groups from a text file and creates a new text file
in CSV format that contains group members in the below format:

group_name1,user_name1
group_name1,user_name2
etc...

VARIABLES
server = 'domain name'
glist = 'path to text file containing desired groups'
"""

# Import the win32 module needed for accessing groups and members
import win32net

# Set server name and group_list text file variables
server = # enter server name here
group_list = 'groups.txt'
grps = []

# Loop over lines in group_list and store group names in a list
with open(group_list, 'rb') as my_groups:
    for line in my_groups:
        grps.append(line.rstrip('\r\n'))

# Loop over groups and store members in desired format in new text file 'groups_members_output.txt'
with open('groups_members_output.txt', 'wb') as blank_file:
    for group in grps:
        usrs = win32net.NetGroupGetUsers(server,group,0)
        for user in usrs[0]:
            blank_file.write('{},{}\r\n'.format(group,user['name']))


texts: Checking if two strings are permutations (anagrams) in Python

texts:
Practicing for my interview, I am working on some problems in Python.

This problem is to decide two strings are permutation (or anagrams) of each each other.

def is_permutation(first, second):
    if len(first) != len(second):
        return False
    first_arr = [0 for i in range(256)] # ASCII size
    second_arr = [0 for i in range(256)] # ASCII size
    for i in range(len(first)):
        first_arr[ord(first[i])] += 1
        second_arr[ord(second[i])] += 1
    if first_arr != second_arr:
        return False
    else:
        return True

I feel this code can be more efficient, but I cannot make it. Can anybody give me advice or tip so that I can improve please?


texts: Asynchronous JavaScript to fetch remote JSON data with promises and generators

texts:
I am trying to figure out how to do async calls using promises and generators (without 3rd party libraries). Most of the examples I found on the Internet are either incomplete or confusing (at least to me), so I decided to try and write the code myself.

I would really appreciate it if someone could review the code and provide comments and suggestions for improving it.

function getJSON(url) {
    return new Promise((resolve, reject) => {
        const https = require("https");
        try {
            https.get(url, (response) => {
                let data = "";
                response.on("data", (part) => {
                    data += part;
                });
                response.on("end", () => {
                    try {
                        resolve(JSON.parse(data));
                    }
                    catch(e) {
                        reject("Error parsing data");
                    }
                });
            }).on("error", () => {
                reject("Error downloading data");
            });
        }
        catch(e) {
            reject("Error: " + e.message);
        }
    });
}

function request(generator) {
    var iterator = generator();
    function process(result) {
        if (result.done) {
            return;
        }
        const value = result.value;
        if (value instanceof Promise) {
            value.then(
                (data) => {
                    console.log(data);
                    process(iterator.next());
                }
            )
            .catch(
                err => {
                    iterator.throw(err);
                }
            );
        }
    }
    try {
        process(iterator.next());
    }
    catch(e) {
        iterator.throw(e);
    }
}

function *DataGenerator() {
    try {
        yield getJSON("https://jsonplaceholder.typicode.com/posts/1");
        yield getJSON("https://jsonplaceholder.typicode.com/posts/2");
        // yield getJSON("https://jsonplaceholder.typicode.com/"); // Parsing error
        // yield getJSON(""); // Domain name error
    }
    catch (e) {
        console.log(e);
    }
}

// Run

console.log("Before");
request(DataGenerator);
console.log("After");

This is also available as a repo.


texts:
Please review my implementation of a Circular Singly Linked List.

public class NodeS {

    public int num;
    public NodeS next;

    public NodeS(int n){
        this.num = n;
    }
}

public class SinglyCircularList {

    private static NodeS head = null;
    private static NodeS tail = null;
    private static int size = 0;

    public static int getSize() {
        return size;
    }

    public static void insert(int n) {
        NodeS node = new NodeS(n);
        node.next = tail;
        if (tail == null) {
            tail = node;
        } else {
            head.next = node;
        }
        head = node;
        size++;
    }

    public static int delete() {
        if (!isEmpty()) {
            NodeS deq = tail;
            tail = deq.next;
            size--;
            if (size == 0) {
                tail = null;
            }
            head.next = tail;
            return deq.num;
        } else {
            System.out.println("List Empty !!");
        }
        return -1;
    }

    public static boolean isEmpty() {
        return size == 0;
    }

    public void printList() {
        NodeS temp = tail;
        for (int i = 0; i <= size; i++) {
            if (temp != null) {
                System.out.print(temp.num);
                temp = temp.next;
            }
        }
        System.out.println();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        SinglyCircularList scl = new SinglyCircularList();
        scl.insert(1);
        scl.insert(2);
        scl.insert(3);
        scl.insert(4);
        scl.insert(5);
        scl.insert(6);
        scl.insert(7);
        scl.printList();
        System.out.println("Del->" + scl.delete());
        scl.insert(8);
        scl.printList();
        System.out.println("Del->" + scl.delete());
        System.out.println("Del->" + scl.delete());
        System.out.println("Del->" + scl.delete());
        System.out.println("Del->" + scl.delete());
        System.out.println("Del->" + scl.delete());
        System.out.println("Del->" + scl.delete());
        System.out.println("Del->" + scl.delete());
        System.out.println("Del->" + scl.delete());
        scl.printList();
        scl.insert(9);
        scl.insert(10);
        scl.printList();

    }

}


texts:
I have these 2 functions that are almost the same:

def handle_keywords(self, scan_id):
    keywords = Keyword.objects.all()
    for kwrd in keywords:
        self.process_rss_url(kwrd.rss, SourceType.GOOGLE_ALERTS, kwrd.id, kwrd.last_scan_time, scan_id)
        kwrd.last_scan_time = timezone.now()
        kwrd.save()

def handle_rss(self, scan_id):
    all_rss = RSS.objects.all()
    for rss in all_rss:
        self.process_rss_url(rss.feed_url, SourceType.RSS, rss.id, rss.last_scan_time, scan_id)
        rss.last_scan_time = timezone.now()
        rss.save()

What is a good way to reduce the code duplication?


texts:
I have an application with a recent addition that requires the removal of a struct pointer from a slice that is itself an element of another struct. A summary of the usage.

I am wondering if this is idiomatic and okay usage of the go languages. Things appear to work and this appears to be inline with the golang recommendations for slice element deletion.

package main

import (
    "fmt"
    "strconv"
)

const ARBITRARY= 5

type myData struct {
    det detailSlicePtr
}

type detail struct {
    id   int
    name string
}

// Slice of pointers to details
type detailSlicePtr []*detail

// Returns true if item removed succesfully,
// false all other cases
func(s *myData ) remove(d *detail) bool {
    for i:= range s.det {
        if s.det[i].name == d.name && s.det[i].id == d.id {
            s.det[i] = new(detail)
            s.det = append(s.det[:i],s.det[i+1:]...)
            return true
        }
    }

    return false
}

// Find and remove a struct element from a slice of struct pointers within a     struct
func main() {

    var d myData
    details := make(detailSlicePtr , ARBITRARY)

    for j := 0; j < ARBITRARY; j++ {
        details [j] = &detail{
            id:   j,
            name: strconv.Itoa(j),
        }
    }

    d.det = details

    // Print out what we have so far
    for index := range d.det {
        fmt.Printf("Item %d is %s\n", index, d.det[index].name)
    }

    findMe := ARBITRARY / 2
    middle := &detail{id: findMe ,name:strconv.Itoa(findMe)}

    if ok := d.remove(middle); !ok {

        fmt.Printf("Unable to find element: %v\n", middle)

    } else {

        fmt.Printf("Found and removed element: %v\n", middle)

        // Print what is left
         for index := range d.det {
            fmt.Printf("Item %d is %s\n", index, d.det[index].name)
        }
    }
}


texts:
The following method is designed to return true if it passes all of the rules for a password. Does anyone see a way to improve it? Performance improvements are welcome for sake of education.

I already know password rules beside length are counter-productive.  It's not my choice.  Also, I know that performance is absolutely trivial here.  I only care about performance by way of educating myself.  The stuff I learn on non-critical optimization often helps me when I do have a bottleneck.  I will not be implementing something just because it is faster.

/**
 * Returns true if and only if a password passes the rules:
 *  - Must be at least 8 characters.
 *  - Must contain two of the following types:
 *    - Letters
 *    - Numbers
 *    - Symbols (includes whitespace)
 *
 * @param string $password The raw, unencrypted password.
 * @return bool
 */
public function isValidPassword($password) {
    $length = strlen($password);

    if ($length < 8) {
        return false;
    }

    $foundLetter = false;
    $foundNumber = false;
    $foundSymbol = false;

    for ($i = 0; $i < $length; $i++) {
        $char = $length[$i];

        if (ctype_alpha($char)) {
            $foundLetter = true;
        }
        else if (ctype_digit($char)) {
            $foundNumber = true;
        }
        else if (ctype_punct($char) || ctype_space($char)) {
            $foundSymbol = true;
        }
    }

    return ($foundLetter && $foundNumber)
        || ($foundLetter && $foundSymbol)
        || ($foundNumber && $foundSymbol);
}


texts: Converting HEX values to Unicode characters

texts:
I have a small bot for social network, which accepts message "unicode XXXX XXXX XXXX ...", where XXXX - HEX values which I should convert to Unicode characters. Initially command accepted only one HEX value, and it worked fine and fast. After I modified code to accept multiple values, process slowed down (1-2 seconds response vs. 4-5 seconds).

Here is my code:

def unic(msg):
    if type(msg) == list:
        msg.pop(0) # removing "unicode" word
        try:
            sym = '' # final result
            correct = [] # correct HEX values to be converted
            for code in msg:
                try:
                    chr(int(code, 16))
                    correct.append(code)
                except:
                    pass
            if correct != []:
                for code in correct:
                    sym = sym + chr(int(code, 16))
            elif correct == []:
                return c_s.get('incorrect') # returning error message from common strings list
            if sym != '':
                return sym
        except:
            return c_s.get('incorrect')

What should I change here to accelerate process? Any suggestions are welcome.


texts:
I have a collection (Child Collection) on which I am performing some operation to make another collection (Parent Collection). But that I do in a dirty foreach loop. I want to do it in an elegant way.

GroupInfo grpInfo;
List<GroupInfo> lstGroupInfo = new List<GroupInfo>();
foreach (AddressInfo addressInfo in subDetails)
{
 if (lstGroupInfo.Where(u => u.Addres1 == addressInfo.Address1).Count() > 0)
    {
        grpInfo = lstGroupInfo.Where(u => u.Addres1 == addressInfo.Address1).SingleOrDefault();

        if (addressInfo.Rural)
            grpInfo.Rural = true;
        else if (addressInfo.Urban)
            grpInfo.Urban = true;

        grpInfo.SubDetails.Add(addressInfo);
    }
    else
    {
        grpInfo = new GroupInfo();
        grpInfo.AddressID = addressInfo.AddressID;
        grpInfo.LocationID = addressInfo.NamedLocationID;

        if (addressInfo.Rural)
            grpInfo.Rural = true;
        else if (addressInfo.Urban)
            grpInfo.Urban = true;

    }
}

GroupInfo class is:

public class GroupInfo
{
    public string Address1
    {
        get;
        set;
    }

    public int AddressID
    {
        get;
        set;
    }

    public int? LocationID
    {
        get;
        set;
    }
}

I want to do it in LINQ lambda way.


texts:
I'm now developing an instant messaging system but I'm a little confused: I can't decide which approach I have to choose!

I want you to tell me what is good/bad with this programming approach.  One friend of mine said it's difficult to read, but it works.

/*! | (c) 2012, 2013 by Bellashh*/
 /// <reference path="jquery-2.0.0-vsdoc.js" />
$(document).ready(function () {
  var ChatProvider = {
    "Friends": [],
    "People": [],
    "Conferences": [],
    "UI": {},
    "Utils": {
      "functions": {
        "alert": function (str) {
          alert(str);
        } /*ChatProvider.Utils.functions.alert*/ ,

        "addFriend": function (friend) {
          ChatProvider.Friends.push(friend);
          alert(ChatProvider.Friends.pop().Names);
        } /*ChatProvider.Utils.functions.addFriend*/ ,

      } /*ChatProvider.Utils.functions*/ ,

      "events": {} /*ChatProvider.Utils.events*/ ,

      "settings": {

      } /*ChatProvider.Utils.settings*/
    }
  } //var ChatProvider

  ChatProvider.Utils.functions.addFriend({
    "Names": "bellash"
  });

}); //$(document).ready

P.S: for visibility sake, I added some space between line separating objects' properties.


texts: Finding a word ladder using Breadth First Search

texts:
This is a LeetCode problem called Word Ladder:

  Given two words (start and end), and a dictionary, find the length of
  shortest transformation sequence from start to end, where only one letter can be
  changed at a time. Each intermediate word must
  exist in the dictionary For example,

  Given: start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"]

  As one shortest transformation is
  "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5.

  Note:

  Return 0 if there is no such transformation sequence. All words
  have the same length. All words contain only lowercase alphabetic
  characters.

My solution:

#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>

using namespace std;

class Solution
{
    //! O(n)
    bool is_changeable(const string& lhs, const string& rhs)
    {
        size_t count = 0;
        for(auto l = lhs.cbegin(), r = rhs.cbegin();    l != lhs.cend();    ++l,++r)
            if(*l != *r)    ++count;
        return count == 1;
    }

public:
    using Level = vector<string>;

    int ladderLength(string start, string end, unordered_set<string> &dict)
    {
        if(dict.empty())    return 0;

        auto d = dict;
        d.erase(start);
        d.erase(end);
        if(d.empty())       return 2;

        //! lambda to make next level
        auto next_level = [&](const Level& curr) -> Level
        {
            Level ret;
            for(const auto& s : curr)
                for(const auto& attempt : d)
                    if(is_changeable(s,attempt))    ret.push_back(attempt);
            return ret;
        };

        //! lambda to check if end reached
        auto if_found = [&](const Level& lvl) -> bool
        {
            for(const auto& s : lvl)
                if(is_changeable(s,end))    return true;
            return false;
        };

        /**
         * @brief top abstraction layer
         */
        size_t count = 0;
        for(auto curr = Level{start}; !if_found(curr);   curr = next_level(curr))
        {
            if(curr.empty())    return 0;
            for(const auto& s : curr)   d.erase(s);
            ++count;
        }

        return count + 2;
    }
};

This solution caused "Time Limit Exceeded" when tested with a reasonably big dict. It's so big that I'm not not allowed to paste here, so get it here.

How can I optimize this code to AC? Am I doing BFS right? What is the bottleneck?


texts:
I have this simple code and it is working fine it is self explanatory: the user will choose a random number 10 times and based on the random number the array will be filled by fruits.

var fruit =[];

for( x=0; x<10,x++){
    var r = Math.floor(Math.random() * 100 + 1);
    choose(r);
}

function choose(num){

  if(num <30){

      fruit.push("apple");

   }else if(num <70){
   fruit.push("kiwi");

    }else if(num< 90){

    fruit.push("banana");

    }else{

    fruit.push("grapes");
};

}

However in the code above, requirement is not restrictive; so below the number of available fruit is limited, and even if the random number choose a fruit, i have first to check if it is available in store or not. if the fruit is not available I should fall through to the next available fruit. The code below is working fine; but I had to do it via recursion in case fruit is not available.

var apple = 2;
var kiwi = 1;
var banana = 5;
var grapes = 2;

var fruit =[];

for( x=0; x<10,x++){
    var r = Math.floor(Math.random() * 100 + 1);
    choose(r);
}

function choose(num){

  if(num <30){
     if(apple>0){
     fruit.push("apple");
     apple--;
     }else{
     num = 31;
     choose(num);
     };

  }else if(num <70){

      if(kiwi>0){
         fruit.push("kiwi");
         kiwi--;
         }else{
        num = 71;
        choose(num);
        };

  }else if(num< 90){
       if(banana>0){
         fruit.push("banana");
         banana--;
        }else{
          num = 91;
          choose(num);
        };
}else{
      if(grapes>0){
        fruit.push("grapes");
        grapes--;
      }else{
         num = 1;
         choose(num);
      };
};

}

This code is working and my question is:

Since this selection of food is happening many times in the page, and it involves recursion, I am worried that this will degrade the performance.

Is there any advice in this regard? or any change suggested to the code or algorithm?


texts:
I'm creating a class to wrap a list of Mask and I'd like to know if I'm overriding the GetHashCode() and Equals() correctly.

Mask is a wrapper for a List of Points. It does implement IEnumerable<Point>.

public class MaskCollection : IEnumerable<Mask>
    {
        #region Variables

        private List<Mask> masks;

        public int Count { get { return masks.Count; } }

        #endregion

        #region Overrides

        public override int GetHashCode()
        {
            int hash = 0;

            foreach(Mask mask in masks)
            {
                hash ^= mask.Center.GetHashCode();
            }

            return hash;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;

            if (!(obj is MaskCollection)) return false;

            MaskCollection other = (MaskCollection)obj;
            if (this.Count != other.Count) return false;

            HashSet<Mask> uniqueMasks = new HashSet<Mask>(masks);
            foreach(Mask mask in other)
            {
                if (!uniqueMasks.Contains(mask)) return false;
            }

            return true;
        }

        #endregion
    }

And if I am overloading them correctly, can this code be improved? My Equals() looks really slow, if they actually are equal.


texts:
Magic numbers are bad... I totally agree. But there's one magic number I find hard to fix:

  '100' is a magic number.

Consider this code:

public double getPercent(double rate) {
    return rate * 100;
}

public double getRate(double percent) {
    return percent / 100;
}

SonarQube will raise 2 violations, one for each use of 100. I could replace 100 with a constant variable, but what would be a good name for it? Is that really a good idea? If somebody ever changes its value that will be a disaster. I could also just add // NOSONAR to all the lines that use 100.

What is the best practice for dealing with the magic number 100?

UPDATE

From the answers, the most useful bit for me was this:

  Practical Magic Number rule: A literal is a not a magic number if the most meaningful variable name for it is the same as the spoken name of the literal.

So by this logic, 100 is NOT a magic number.

However, to make the violation go away, I decided to replace the 100 with a constant:

public static final double HUNDRED = 100;  // change it and I'll kill you

In my real project there are many lines using 100, and if I put // NOSONAR on all those lines that might cover up other potential problems that other developers might inadvertently add later.

Not sure if there will be any real benefits using this constant. A small one may be that when I do git grep 100 I see a lot of matches from resource files in the project, while git grep HUNDRED turns up just the the Java code that uses this.


texts:
Given a natural number \$n\$ (\$1 \le n \le 500000\$), please output the
  summation of all its proper divisors.

  Definition: A proper divisor of a natural number is the divisor that is strictly less than the number.

  e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor
  summation is: 1 + 2 + 4 + 5 + 10 = 22.

  Input

  An integer stating the number of test cases (equal to about 200000),
  and that many lines follow, each containing one integer between 1 and
  500000 inclusive.

  Output

  One integer each line: the divisor summation of the integer given
  respectively.

My solution:

It solved the problem in 1.63 seconds, which seems suboptimal considering its 3-second limit.

import java.util.ArrayList;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int testcases = reader.nextInt();
        reader.nextLine();
        ArrayList<Integer> values = new ArrayList<Integer>();
        for(int i = 0; i<testcases; i++){
            values.add(reader.nextInt());
            reader.nextLine();
        }
        reader.close();
        for(int i = 0; i<testcases; i++){
            int sum = 1;
            int testcase = values.get(i);
            double lim = Math.sqrt(testcase);
            for(int k = 2; k<=lim; k++){
                if(testcase%k==0){
                    sum+=k;
                    int z = testcase/k;
                    if(k != z)
                        sum+=z;
                }
            }
            if(testcase==1)
                sum=0;
            if(i<testcases-1)
                System.out.println(sum);
            else
                System.out.print(sum);
        }
    }
}

EDIT: Updated code, which ran in a more respectable 0.22 seconds.

Taking out reader.nextLine(); improved the runtime by around 0.2 seconds.

Adding a special treatment to perfect squares seemed to have no noticable impact on speed (might depend on test cases?).

It turned out using BufferedReader and BufferedWriter had an immense impact on IO speed, reducing runtime to 0.22 seconds.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main
{
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
        int testcases = Integer.parseInt(in.readLine());
        int[] values = new int[testcases];
        for(int i = 0; i<testcases; i++){
            values[i]=Integer.parseInt(in.readLine());
            }
        for(int i = 0; i<testcases; i++){
            int sum = 1;
            int testcase = values[i];
            double lim = Math.sqrt(testcase);
            for(int k = 2; k<lim; k++){
                if(testcase % k == 0){
                    sum += k + testcase / k;
                }
            }
            int intLim = (int) lim;
            if (intLim * intLim == testcase) {
                sum += lim;
            }
            if(testcase == 1)
                sum=0;
            out.write(sum + "\n");
        }
        out.flush();
    }
}


texts:
Given an array arr of distinct integers
  and a nonnegative integer k, write a function
  findPairsWithGivenDifference that returns an array of all pairs [x,y]
  in arr, such that x - y = k. If no such pairs exist, return an empty
  array.

  In your solution, try to reduce the memory usage while maintaining
  time efficiency. Prove the correctness of your solution and analyze
  its time and space complexities.

  Note: the order of the pairs in the output array should maintain the
  order of the y element in the original array.

  Examples:

  input:  arr = [0, -1, -2, 2, 1], k = 1 output: [[1, 0], [0, -1], [-1,
  -2], [2, 1]]

  input:  arr = [1, 7, 5, 3, 32, 17, 12], k = 17

  output: []

  Constraints:

  [time limit] 5000ms

  [input] array.integer arr

  0 ≤ arr.length ≤ 100 [input]integer k

  k ≥ 0 [output] array.array.integer

def find_pairs_with_given_difference(arr, k):
    numbers = set()
    output = []
    # insert arr element into set
    for i in range(len(arr)):
        numbers.add(arr[i])

    # loop through the entire array
    for i in range(len(arr)):
        difference = arr[i]
        if difference - k in numbers:
            output.append([difference,(difference - k)])
    return output

Test case #1
Input: [4,1], 3
Expected: [[4,1]]
Actual: [[4, 1]]

Test Case #2
Input: [1,5,11,7], 4
Expected: [[5,1],[11,7]]


texts:
I've been fiddling with Unity, trying to make nice walking/running animations. So, i found the Stealth tutorial and I used pretty much the same animator as the AI, only I only use Speed and AngularSpeed and, of course, added a control script. The controls work as intended but the whole script is laggy. I know, my Update function is really loaded, but I'm out of ideas. Any input appreciated even if it is totally irrelevant :)

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    public float speed = 0f;        //used public just to check the values

    public float angularSpeed = 0f; //same

    public float accTime = 1f;
    public float decTime = 1f;
    public float turnTime = 2.5f;

    public float speedOffset = 0f;      //offsets set to let lerp "go faster" when approaching the target value
    public float angularSpeedOffset = 0f;   //same

    private float axisX = 0f;
    private float axisY = 0f;

    private int speedHash = Animator.StringToHash ("Speed");
    private int angularSpeedHash = Animator.StringToHash ("AngularSpeed");

    private Animator anim;

    void Awake () {
        anim = GetComponent<Animator>();
    }

    void Update () {
        SpeedCalc ();
        AngularSpeedCalc ();

        anim.SetFloat (speedHash, speed);
        anim.SetFloat (angularSpeedHash, angularSpeed);
    }

    void SpeedCalc () {
        axisY = Input.GetAxis ("Vertical");

        if (axisY > 0)
            speed = Mathf.Lerp (speed, 5.7f * axisY + speedOffset, accTime * Time.deltaTime);       // targets multiplied by axis input for analogue sticks to be... analogue..
        else
            speed = Mathf.Lerp (speed, 0f - speedOffset * 0.5f , decTime * Time.deltaTime);

        if (speed >= 5.7f) speed = 5.7f
        else if (speed <= 0f) speed = 0f;
    }

    void AngularSpeedCalc () {
        axisX = Input.GetAxis ("Horizontal");

        if (axisX > 0 && angularSpeed >= 0f)
            angularSpeed = Mathf.Lerp (angularSpeed, 2.5f * axisX + angularSpeedOffset, turnTime * Time.deltaTime);
        else if (axisX < 0 && angularSpeed <= 0f)
            angularSpeed = Mathf.Lerp (angularSpeed, 2.5f * axisX - angularSpeedOffset, turnTime * Time.deltaTime);
        else {
            if (Mathf.Abs (angularSpeed) > 0.2f)
                angularSpeed = Mathf.Lerp (angularSpeed, 0f, turnTime * Time.deltaTime);
            else
                angularSpeed = 0f;
        }

        if (angularSpeed >= 2.5f) angularSpeed = 2.5f;
        else if (angularSpeed <= -2.5f) angularSpeed = -2.5f;
    }
}


texts:
I have an HTML table representing a database table and a sidebar which holds different anchors ready to perform CRUD operations on click.

Because the hrefs in the anchors aren't in general valid for all columns I have written a script which automatically inserts the id of a selected column into the hrefs:

/localhost/image/var/edit => /localhost/image/4/edit

The code I have written works but it isn't very clean and smart :( Could somebody take a look and say where I have space of improvement?

How could I improve the td:nth-child(2) selector and the long line modifying the link?

EDIT:

    {% if image is defined %}

Bilder verwalten

Bild betrachten

Bild hinzufügen

Bild bearbeiten

Bild löschen

    {% else %}

Bilder verwalten

Bild betrachten

Bild hinzufügen

Bild bearbeiten

Bild löschen

    {% endif %}

As you see when having an available singe object (while editing, showing, deleting) the server side renders the right id/name into the href. Under circumstances when I only have a collection of objects or none object available, jquery has to do the rendering of the right urls. Also some URLs don't require an id (new, index)


texts:
Based on the many other number guessing games people tend to post as first questions, https://www.xkcd.com/221/, and a crypto class I'm taking, I've decided to implement a number guessing game using the best python style I can, and the best random number generator I can create. Any advice is appreciated.

#!/usr/bin/env python3

"""
This is a simple guessing game. It is very difficult.
"""

from time import time

class Random():
    '''
        Class for generating cryptographically secure random 4s
        4 is random and was chosen by dice roll.
    '''

    def __init__(self, seed=0):
        self.seed = seed

    def set_seed(self, seed):
        '''
            Sets the rng's seed.
            This method should be called before the first use if a seed is not
            passed to the constructor
        '''
        self.seed = seed

    def get_random_int(self, low, high):
        '''
            Generates a random integer
            between low and high as long as low <= 4 <= high.
        '''
        return self._restrict_to_bounds(4, low, high)

    def get_random_float(self, low, high):
        '''
            Generates a random float
            between low and high as long as low <= 4.0 <= high.
        '''
        return self._restrict_to_bounds(4.0, low, high)

    def _restrict_to_bounds(self, val, low, high):
        ''' returns val clamped between low and high'''
        if low <= val <= high:
            return val
        if val == 4:
            return val
        return 4

def game(low=0, high=1_000_000):
    ''' Runs the game '''

    rand_source = Random(time())
    secret_number = rand_source.get_random_int(low, high)

    print(f'''Welcome to the Guessing Game.
I have generated a random integer between {low}, and {high}.
Your job is to guess it in as few guesses as possible.\n''')

    guess_num = 1
    guess = None
    while True:
        guess = input('Enter your guess: ')
        try:
            guess = int(guess)
        except ValueError:
            print("You didn't guess an integer, try again.")
            continue

        if guess == secret_number:
            break
        elif guess > secret_number:
            print('Your guess was too high, try again')
        elif guess < secret_number:
            print('Your guess was too low, try again')
        guess_num += 1

    print()
    if guess_num == 1:
        print(f''''You got the right answer in {guess_num} guess!
Are you cheating?''')
    else:
        print(f'You got the right answer in {guess_num} guesses!')

    play_again = input('Do you want to play again? (enter y or n)\n')
    if play_again == 'y':
        game()

if __name__ == '__main__':
    game()


texts:
In my example, I have four models: User, Company, Project, and Plant (though my project technically has more: Plant, Job, Team, etc.).

Model User: name, role, company: { id, role }, projects: [ { id, role } ], plants: [ { id, role } ]
Model Company: name, members [ ], projects [ ]
Model Project: title, members [ ], company, plants [ ]
Model Plant: title, members [ ], project, jobs [ ]

First, I wrote a simple script to check the role of a given user (middleware.js):

const isAdmin = (user) => {
    return user.role === "admin"
}

const isCompanyMember = (user, companyId) => {
    return user.company.id && user.company.id.equals(companyId)
}

To check multiple permissions, I wrote a function that always gets used in the middleware.

const checkPermit = (...checks) => {
    let permit = 0
    for (let i = 0; i < checks.length; i++) {
        if (checks[i]) permit = 1
    }
    return permit
}

Afterwards, I wrote this function to get a list of users by project ID (controller.js):

const getListUsersByProjectId = async (req, res, next) => {
    const { projectId } = req.params
    try {
        const project = await Project.findById(projectId)
            .select("members")
            .populate("members", "name")
        if (!project) return next("Project not found")
        res.json({
            result: 'ok',
            message: "Find list of users successfully",
            data: project
        })
    } catch (error) {
        next(error)
    }
}

To more easily find a given project by its ID, I wrote this helper function:

const findProject = (projectId) => {
    return Project.findById(projectId)
}

Finally, I wrote the router (router.js):

router.get('/get-list-users/:projectId',
    authentication.required,
    // I set signed user to req.user in function authentication.required
    async (req, res, next) => {
        try {
            let { user } = req
            let project = await findProject(req.params.projectId)
            if (!project) return next("Can not find project")
            let permit = checkPermit(
                isAdmin(user)
                isCompanyMember(user, project.company)
            )
            if (permit) return next()
            else return next("You don't have authorization to do this action!")
        } catch (error) {
            next(error)
        }
    },
    getListUsersByProjectId
)

It's working well and as intended, but the code isn't particularly fun to work with! How can I improve the code and make it more clean?


texts: Travelling Salesmen Problem - Dynamic Programming

texts:
I wanted to review my TSP program for correctness in my approach, although I have not implemented one function subset which would be simple.

public class TravellingSalesmanProblem {
    private int[][] dist;
    private Map<String,Integer> C;
    private int n;

    public int tsp(int start) {
        Set<Integer> s = new HashSet<Integer>();
        s.add(1);
        C.put(generateKey(s,1), 0);

        for(int subsetSize = 2;subsetSize<=n;subsetSize++) {
            List<Set<Integer>> subsetList = subset(subsetSize);
            for(Set<Integer> subset:subsetList) {
                for(Integer j:subset) {
                    if(j==1)
                        continue;
                    C.put(generateKey(subset,j), Integer.MAX_VALUE);
                    for(Integer i:subset) {
                        // C(S,j) = Min{C(S-{j},i) + D[i,j]}
                        Set<Integer> temp = new HashSet<Integer>();
                        temp.addAll(subset);
                        temp.remove(j);
                        C.put(generateKey(subset,j), Math.min(C.get(generateKey(subset,j)),C.get(generateKey(temp,i)) + dist[i][j]));
                    }
                }
            }
        }

        int min = Integer.MAX_VALUE;
        for(int i=1;i<=n;i++)
            s.add(i);
        for(int i = 1;i<=n;i++) {
            min = Math.min(min,C.get(generateKey(s,i)));
        }
        return min;
    }

    public String generateKey(Set<Integer> set,int n) {
        int[] unsorted = new int[set.size()];
        int i=0;
        for(Integer element:set) {
            unsorted[i++] = element;
        }

        Arrays.sort(unsorted);
        StringBuilder sb = new StringBuilder();
        for(int element:unsorted)
            sb.append(element);
        return sb.toString() + n;
    }

    private List<Set<Integer>> subset(int s) {
        return null;
    }
}


texts: Project Euler Problem #5 Solution in C++

texts:
Project Euler #5: Smallest multiple
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"

And I'm wondering if my code to solve this problem is good and if there are ways to make it better.
#include "stdafx.h"
#include <iostream>
int main(){
int smallestMultiple = 40;
int i = 10;

while (i<20){
    if (smallestMultiple%i == 0){
        i++;
        continue;
    }
    else{
        i = 10;
        smallestMultiple += 20;
    }
    }
std::cout << smallestMultiple;
}


texts:
I'm sorry, maybe this question is really stupid but I have really been thinking a lot about it recently, thinking of which type of <prev | next> web navigation approach is better. FYI the stack is React + Redux.

With using name properties (or also we can use something like custom boolean field forward="ture" and check it)

HTML:

      <button name="prev" onClick={this.onYearChange.bind(this)}>Prev</button>

{this.state.year}

      <button name="next" onClick={this.onYearChange.bind(this)}>Next</button>

JS handler:

 onYearChange(e){
        let dir = (e.target.name === 'prev') ? -1 : 1,
            year = this.props.selectedYear + dir;

        this.props.onYearChangeHandler(year);
  }

With passing custom property dir with inc/dec value

HTML:

   <button dir={-1} onClick={this.onYearChange.bind(this)}>Prev</button>

{this.state.year}

   <button  dir={1} onClick={this.onYearChange.bind(this)}>Next</button>

JS:

onYearChange(e){
        let dir = e.target.dir,
            year = this.props.selectedYear + dir;

        this.props.onYearChangeHandler(year);
}

Or with two separate binded functions

HTML:

     <button onClick={this.toPrevYear.bind(this)}>Prev</button>

{this.state.year}

     <button onClick={this.toNextYear.bind(this)}>Next</button>

JS:

    toPrevYear(e) {
        this.onYearChange(-1);
    };

    toNextYear(e) {
        this.onYearChange(1);
    };

    onYearChange(val) {
        let year = this.props.selectedYear + val;

        this.props.onYearChangeHandler(year);
    }

Or is there some better solution for this scenario?


texts: Searching through a huge set with threads

texts:
I wrote a class that finds values in a huge search volume. I have a pretty strong feeling that my code is not good and would like to get your opinion on it. My experience with C++11 threading is very limited and I think I use the wrong features for my task.

#include <iostream>
#include <vector>
#include <utility>
#include <future>

class Searcher
{
public:
    std::future<bool> Find(int x) {
        m_searches.emplace_back();
        m_searches.rbegin()->first = x;
        return m_searches.rbegin()->second.get_future();
    }

    void Search()
    {
        // very large search data
        static const std::vector<int> haystack = { 4, 5, 1, 3, 9, 8, 7, 6, 11, 42, 13 };

        std::vector<int> foundIndices;

        // find values
        for (auto h : haystack) {
            for (size_t i = 0; i < m_searches.size(); i++) {
                if (m_searches[i].first == h) {
                    foundIndices.push_back(i);
                    m_searches[i].second.set_value(true);
                }
            }
        }

        // resolve promises, where no value was found
        for (size_t i = 0; i < m_searches.size(); i++) {
            bool found = false;
            for (auto j : foundIndices)
                if (j == i)
                    found = true;

            if (!found)
                m_searches[i].second.set_value(false);
        }
    }

private:
    std::vector<std::pair<int, std::promise<bool>>> m_searches;
};

int main()
{
    Searcher s;
    auto s1 = s.Find(1);
    auto s2 = s.Find(2);
    auto s3 = s.Find(3);

    s.Search();

    std::cout << s1.get() << std::endl;
    std::cout << s2.get() << std::endl;
    std::cout << s3.get() << std::endl;

    return 0;
}

There should be one search running for many Finds, because the set that is searched is very large. It could however run concurrently to split the search up to multiple threads. For example with two threads: The first thread searches the first half, the second thread searches the second half.

The futures are not really guaranteed to be valid, because the user has to call the Search function. Would it be possible to start the search, once the first .get was called?

My "algorithm" to fulfil the promises looks very ugly and complicated, but I can't think of a better way.


texts: JavaScript Recursive Filtering With AND and OR

texts:
I am doing the #JavaScript30 challenge and challenge 06 is to write a "type ahead" application for searching for cities/states. The basic challenge of filtering based on a simple string was rather trivial, so I wanted to add AND and OR functionality using + and ,.

I came up with a recursive solution, but when handling the ANDs I have a feeling that the way I accomplished it is inefficient and has a higher-than-necessary Big O complexity. Below is the code in question, and I will also post a link to a working demo to play around with.

If anyone can show me a more efficient way to do this, or let me know if this is as efficient as it can get, it would be greatly appreciated!

Working DEMO

Function in question

function handleAnds (andArray, citiesArr) {
  // grab last AND condition to work from left to right, recursively
  var lastAnd = andArray.pop().trim();
  var matches = [];
  if (~lastAnd.indexOf(",")){
    // handle OR conditions
    matches = handleOrs(lastAnd.split(","), citiesArr);
  }
  else {
    matches = citiesArr.filter(function (city) {
      return (
        (checkObjectPropertyValue(city, "city", lastAnd) ||
         checkObjectPropertyValue(city, "state", lastAnd))
      );
    });
  }

  if (andArray.length) {
    /* Code In Question */
    var extras = handleAnds(andArray, citiesArr);
    matches = matches.filter(function (elem) {
      return ~extras.indexOf(elem);
    });
    /* /Code In Question */
    return matches;
  }
  else {
    return matches;
  }
}


texts: Communicating between GUI and controller class using Mediator pattern

texts:
I am writing a program that allows a user to interact with MIDI-connected devices. Upon connecting a MIDI device, interactions with this device will update a GUI. Updates to the GUI include what keys are being pressed, if the volume is turned up/down, etc. In addition, the user can "request" the status of MIDI components through the GUI (how many MIDI devices are available, opening/closing MIDI devices).

All of this is set up using the Mediator pattern, and I would like to ask you all the best way of sending "requests" to each of these classes; MidiController (controls MIDI-related tasks) and GUI (which shows MIDI-related events).

A button exists on the GUI to search for MIDI-connected devices, upon clicking it, the MidiController will get some message (from the Mediator pattern) to find MIDI-connected devices.

My code currently looks like this for this function:

@Override
public void receive(String message) {
    System.out.println("Message from GUI: " + message);

    switch(message){
    case "FIND_ALL_MIDI_DEVICES":

        devices = MidiSystem.getMidiDeviceInfo();
        break;
    default:
        break;
    }
}

I've opted to use a switch statement, but I feel there is a better option. I am expecting this class, MidiController to respond to many different messages. Is there a clean way I might communicate sending data / requests / updates between these two classes?


texts: Understanding the differences: A direct comparison between Cython and C++

texts:
Introduction:

The following two code samples are a direct comparison of performance between Cython and C++. I pieced them together with the help of others-- I barely understand how they work. Their speed in my computer is: 1.225s vs 3.989s (C++ being the faster). The purpose of this comparison is to decide which language I will be using for a series of small but computationally intensive scripts (~200-500 lines).

Question:

As a novice Python programmer dealing with data types, memory (de)allocation, and other low level processes for the very first time, what should I keep in mind when writing Cython modules? Is there anything in the Cython code that can be improved?

Cython script:

import cython
import numpy as np

@cython.boundscheck(False)
@cython.wraparound(False)

cdef class MathObject:
    cdef double a

    def __init__(self, a):
        self.a = a

    # chaotic function (simple math that can't be simplified out by the compiler).
    cpdef double logMap(self):
        self.a = 4.0 * self.a * (1.0 - self.a)
        return 0

    def get_value(self):
        return self.a

def run():
    cdef int i, ii, iii
    cdef int one_thousand = 1000
    cdef double x = 0.2  # logMap has complex behavior at this value

    cdef MathObject objInstance

    objArray = np.empty(one_thousand, dtype=MathObject)
    for i in range(len(objArray)):
        objArray[i] = MathObject(x)

    cdef MathObject[:] objArrayiew = objArray

    for i in range(one_thousand):
        for ii in range(one_thousand):
            for iii in range(one_thousand):
                objInstance = objArrayiew[iii]
                objInstance.logMap()
        print objArray[i].get_value()

    return None

C++ script:

#include <iostream>
using namespace std;

class MathObject {
    public:

    double a;
    MathObject(double b) {
        a=b;
    };

    // simple chaotic function
    double logMap()
    {
        a = 4.0*a*(1.0-a);
    } // logMap
};

int main(int argc, char *argv[])
{
    int ii,jj,kk;

    // create an array of 1000 objects
    int N = 1000;
    MathObject *objArray [N];  // 1000 pointers to objects
    for (ii=0; ii<N; ++ii)  {
        objArray[ii] = new MathObject(0.2);  // construct new objects
    } // for ii

    for (kk=0; kk<1000; ++kk)  {
    for (jj=0; jj<1000; ++jj)  {
    for (ii=0; ii<N; ++ii)  {
        objArray[ii] -> logMap();
    } // for ii
    } // for jj
    } // for kk

    for (ii=0; ii<N; ++ii)  {
        cout << objArray[ii] -> a << "\n";
    } // for ii
}

(Note: I know that this question is a little vague, but most existing tutorials for Cython are written for an audience of C++ programmers. Beginner level information is astoundingly helpful!)

(Second Note: A good explanation of part of the Cython script can be found in the answer to this question.)


texts: Handling Promise that resolves but returns a 404

texts:
This is in a node and express API. I'm trying to figure out the best way to handle Promises that resolve, but return a 404 response. I have a method which uses node-fetch to make a POST call to update a row in a database. If an invalid profileId is provided, the Promise will resolve even though the response is a 404. I want to figure out the best way to make sure that any status other than OK is considered an error and handled as such.
The method is defined as:
async function updateUserProfileSocketId(profileId, socketId) {
    const body = { id: profileId, socketId };
    try {
        const response = await fetch(`${MATCH_API}/updateUserProfile`, {
            method: 'post',
            body: JSON.stringify(body),
            headers: { 'Content-Type': 'application/json' },
        });

        if (response.ok) {
            return response;
        }

        throw new Error(`updateUserProfileSocketId Error: unexpected response ${response.statusText}`);
    } catch (err) {
        console.log(err);
    }
    return null;
}

And it is being called as such:
// this is a class method
onInit(socket) {
    socket.on('init', (profile) => {
        updateUserProfileSocketId(profile.id, socket.id)
            .then((response) => {
                if (response !== null && response.ok) {
                    users.push(profile.id);
                }
            })
            .catch((err) => {
                socket.conn.close();
                console.log(err);
            });
    });
}

This gets the job done but I'm not sure if this is the best way to handle this scenario and I'm not sure if this code has any redundancies. I'm from a Java background so looking for someone to help explain the best methods in dealing with such scenarios. Please let me know if you have any suggestions.


texts:
Any suggestions how to make this code better? I'm novice in coding...))
In this code I'm want to show some hint depending of browser type on semi-transparent overlay. I'm detecting browser type (I'm need - Firefox, Chrome, IE 9 and higher), create all nessesary elements, append this elements to a document.body, and attach events.
To detect "document.ready" I'm use domready.js

// Perform browsers detection;
    var browser = {};
    (function() {
        browser.firefox = false;
        browser.chrome = false;
        browser.msie = false;

        var nAgt = navigator.userAgent;
        var verOffset;

        if ( (verOffset=nAgt.indexOf("MSIE"))!=-1 ) {
            // For IE we also need to check browser version, because hint will be shown only if version is 9 or higher;
            browser.version = parseInt( nAgt.substring(verOffset+5), 10 );
            if (browser.version >= 9 ) {
                browser.msie = true;
                browser.name = "msie";
                browser.hint = {
                    position: "fixed",
                    display: "none",
                    zIndex: "101",
                    bottom: "50px",
                    left: "35%"
                };
            }
        }
        else if ( (verOffset=nAgt.indexOf("Chrome"))!=-1 ) {
            browser.chrome = true;
            browser.name = "chrome";
            browser.hint = {
                position: "fixed",
                display: "none",
                zIndex: "101",
                bottom: "0",
                left: "0"
            };
        }
        else if ( (verOffset=nAgt.indexOf("Firefox"))!=-1 ) {
            browser.firefox = true;
            browser.name = "firefox";
            browser.hint = {
                position: "fixed",
                display: "none",
                zIndex: "101",
                top: "0",
                right: "10px"
            };
        }
    })();

    domready(function() {
        if (browser.firefox || browser.chrome || browser.msie) {
            // Create "overlay" element
            var overlay = document.createElement("div");
            overlay.setAttribute("id", "hintOverlay");
            var overlayStyles = {
              width: "100%",
              height: "100%",
              background: "gray",
              opacity: "0.75",
              zIndex: "100",
              position: "fixed",
              top: "0",
              left: "0",
              display: "none"
            };
            for(var s in overlayStyles){
                if (overlayStyles.hasOwnProperty(s)) {
                    overlay.style[s] = overlayStyles[s];
                }
            }
            overlay.addEventListener("click", function() {
                this.style.display = "none";
                document.getElementById("hintElem").style.display = "none";
            });
            document.body.appendChild(overlay);

            // Create "hint" element
            var hintElem = document.createElement("img");
            hintElem.setAttribute("src", "images/" + browser.name + ".png");
            hintElem.setAttribute("id", "hintElem");
            for(var s in browser.hint) {
                if (browser.hint.hasOwnProperty(s)) {
                    hintElem.style[s] = browser.hint[s];
                }
            }
            document.body.appendChild(hintElem);

            // Attach click event to all links that have "download" in name
            var links = document.getElementsByTagName("a");
            for(var i = 0; i < links.length; i++) {
                if(links[i].getAttribute("id").indexOf('download') == 0) {
                    links[i].addEventListener("click", function() {
                        document.getElementById("hintOverlay").style.display = "block";
                        document.getElementById("hintElem").style.display = "block";
                    });
                }
            }
        }
    });


texts: JavaScript Spiral Matrix Coding Challenge

texts:
A whiteboarding challenge: Given a 2D array (matrix) inputMatrix of integers, create a function spiralCopy that copies inputMatrix's values into a 1D array in a clockwise spiral order. Your function then should return that array.

inputMatrix = [
  [1, 2, 3, 4, 5, 6],
  [7, 8, 9, 10, 11, 12],
  [13, 14, 15, 16, 17, 18],
  [19, 20, 21, 22, 23, 24],
  [25, 26, 27, 28, 29, 30],
  [31, 32, 33, 34, 35, 36]
]

const spiralCopy = (matrix) => {
  const spiralLength = matrix.length * matrix[0].length;
  const spiral = [];

  let iLeftRightStart = 0; // +1
  let iLeftRightEnd = matrix[0].length; // -1
  let leftRightPosition = 0; // +1
  let iTopBottomStart = 1; // +1
  let iTopBottomEnd = matrix.length; // -1
  let topBottomPosition = matrix[0].length - 1; // -1
  let iRightLeftStart = matrix[0].length - 2; // -1
  let iRightLeftEnd = 0; // +1
  let rightLeftPosition = matrix.length - 1; // -1
  let iBottomTopStart = matrix.length - 2; // -1
  let iBottomTopEnd = 1; // +1
  let bottomTopPosition = 0; // +1

  const leftToRight = (iStart, iEnd, position) => {
    for (let i = iStart; i < iEnd; i++) {
      spiral.push(matrix[position][i]);
    }
  }

  const topToBottom = (iStart, iEnd, position) => {
    for (let i = iStart; i < iEnd; i++) {
      spiral.push(matrix[i][position]);
    }
  }

  const rightToLeft = (iStart, iEnd, position) => {
    for (let i = iStart; i >= iEnd; i--) {
      spiral.push(matrix[position][i]);
    }
  }

  const bottomToTop = (iStart, iEnd, position) => {
    for (let i = iStart; i >= iEnd; i--) {
      spiral.push(matrix[i][position]);
    }
  }

  while (spiral.length < spiralLength) {
    leftToRight(iLeftRightStart, iLeftRightEnd, leftRightPosition);
    topToBottom(iTopBottomStart, iTopBottomEnd, topBottomPosition);
    rightToLeft(iRightLeftStart, iRightLeftEnd, rightLeftPosition);
    bottomToTop(iBottomTopStart, iBottomTopEnd, bottomTopPosition);
    iLeftRightStart++;
    iLeftRightEnd--;
    leftRightPosition++;
    iTopBottomStart++;
    iTopBottomEnd--;
    topBottomPosition--;
    iRightLeftStart--;
    iRightLeftEnd++;
    rightLeftPosition--;
    iBottomTopStart--;
    iBottomTopEnd++;
    bottomTopPosition++;
  }
  return spiral;
}
console.log(spiralCopy(inputMatrix));
// prints [1, 2, 3, 4, 5, 6, 12, 18, 24, 30, 36, 35, 34, 33, 32, 31, 25, 19, 13, 7, 8, 9, 10, 11, 17, 23, 29, 28, 27, 26, 20, 14, 15, 16, 22, 21]

So the function works and runs with time complexity of O(N). However, I don't like that I'm using 12 different variables which I then increment/decrement. How can this be consolidated, and is it possible to make the algorithm even faster due to the instant access of JavaScript arrays?


texts: Counting e-mails in a mailbox for each hour

texts:
Pardon if this is silly, but I'm pretty new to coding. I have this code, that works, but I feel like it could be tighter than this, I just can't seem to get it to work any other way. The idea is to read a .txt file find incoming e-mail strings and organize the data by frequency of hour sent.

Here is an example line that I'm looking for in the text:

From email@emailaddress.com Sat Jan 5 09:14:16 2008

Here is my code:

fname = input("Enter file:")
if len(fname) <1 : fname = "filename.txt"
fh = open(fname)
time = list()
hours = list()
hr = dict()

for line in fh:
        if not line.startswith("From "): continue
        words = line.split()
        time.append(words[5])

for i in time:
        i.split(":")
        hours.append(i[:2])

for h in hours:
        hr[h]=hr.get(h, 0)+1

l = list()
for k,v in hr.items():
        l.append((k,v))
l.sort()
for k, v in l:
        print (k,v)