texts: Use DOM and XPath to make some changes in HTML document

texts:
I intend to make some changes in an HTML document, like remove, replace, append some nodes.

I have several arrays with same structure like the following example

$patterns[] = array(
    'xpath'   => '/html/body/div/p',
    'insert'  => $new_a,
    'task'    => 'replace'
);

...

$patterns[] = array(
    'xpath'   => '/html/body/header',
    'insert'  => $new_b,
    'task'    => 'remove'
);

and I use the following snippet

$dom = new DOMDocument();

if ((empty($html) !== true) && ($dom->loadHTML($html) === true))
{
    $dom->formatOutput = true;

    // Use DomXPath
    $xpath = new DomXPath($dom);

    // Process Dom changes
    foreach ($patterns as $key => $value)
    {
        $xpath_results = $xpath->query($patterns[$key]['xpath']);

        if ($xpath_results->length)
        {
            // Assign some values
            $xpath_results = $xpath_results->item(0);
            $task          = $patterns[$key]['task'];
            $replacement   = $patterns[$key]['insert'];

            if ($task != 'remove')
            {
                // Create the replacement
                $newNode = $dom->createDocumentFragment();
                $newNode->appendXML($replacement);
            }

            switch ($task)
            {
                case 'remove':
                    $xpath_results->parentNode->removeChild($xpath_results);
                    break;
                case 'replace':
                    $xpath_results->parentNode->replaceChild($newNode, $xpath_results);
                    break;
                case 'append':
                    $xpath_results->appendChild($newNode);
                    break;
                case 'prepend':
                    $xpath_results->parentNode->insertBefore($newNode, $xpath_results);
                    break;
            }
        }
    }

    // Save Dom
    $html = $dom->saveXML($dom->documentElement);
}

I would like your expert comments about if this is done the right way. The foreach to loop through the array elements, the switch to choose what will be done and if the use of createDocumentFragment is appropriate in this case.


texts: extract all textcontent in htmlcollection to array with javascript

texts:
Here is the raw data
anycasestr = "

refinement

decent

elegant

";

to extract all the textcontent to an array like ["refinement", "decent", "elegant"]
I wrote this code (jquery has been included)
htmlObject = $(anycasestr);
arr = Array.prototype.slice.call(htmlObject[0].getElementsByTagName("div"));
arr_page = [];
for (i = 0; i < 3; i++) {
    arr_page.push(arr[i].textContent);
}

It produces what I want.
I'm just concerned if it is implemented in an elegant way. Could someone take a look at it?
For example, should I have used xpath or something, in terms of computational concerns?


texts: Sorting an array to match the order of values of another array

texts:
I'm running hundreds of curl operations in parallel to my own API, the response array that I get is out of order (the reason being that the first one to finish gets added to the response array first). I need to sort these back so they correspond to the input array, in order to do that I have already written a function as shown below.

I'm interested if there is a more efficient way to do this or not.

Note: The sample shows what I mean, however the input array is usually more than 100 elements long.

Sample input:

$input = array (
   'http://www.yandex.ru',
   'http://www.mail.ru',
   'http://www.google.com'
)

Response:

$response = array (
    array('http://www.mail.ru', 200, 'some other string'),
    array('http://www.yandex.ru', 200, 'some string'),
    array('http://www.google.com', 200, 'yet another string')
)

Function:

function re_order($original, $scrambled) {
    foreach ($scrambled as $url_response) {
       $key = array_search($url_response[0],$original);
       $result[$key] = $url_response;
    }
    ksort($result);
    return $result;
}

Resulting array after calling the function (i.e. desired result):

$result = array (
    array('http://www.yandex.ru', 200, 'some string'),
    array('http://www.mail.ru', 200, 'some other string'),
    array('http://www.google.com', 200, 'yet another string')
)


texts: Segmenting brain images (Dicom format) using region-growing algorithm

texts:
I have a list of images in a folder where num denotes the index of image and I used num to run the iterations in a "for loop". The code is supposed to segment brain part from the brain CT images. Here is the link for region growing algorithm.

How do I increase the performance of my region-growing algorithm?

% CORD_XY(1),CORD_XY(2) is the seed point
% LEN Denotes the number of images in a folder
% num is used to iterate in "for loop"
% "img" here is single image from the folder in DICOM format

for num= 1:LEN
    img = dicomread(files(num,1).name);
    [row, col] = size(img);
    th = 20;
    diff = 10;

    J = regiongrowing(img, CORD_XY(1), CORD_XY(2), th);
    value1 = sum(sum(J > 0));

    if num > 10)
        th = 55;
    elseif num <= 10
        while diff < 0.2 * value1 && diff ~= 0 && th < 60
            value1 = sum(sum(J > 0));
            th = th + 10;
            J = regiongrowing(double(img), CORD_XY(1), CORD_XY(2), th);
            value2 = sum(sum(J > 0));
            diff = value2 - value1;
        end
    end
end

J = regiongrowing(img, CORD_XY(1), CORD_XY(2), th-10);


texts: User php class. Should I connect to DB in this class?

texts:
I have small Class which handles user's information. (name, surname, login, hash of password). Also this class can activate, register and login the user. This means I should connect to DB. Is it normal? I'm using Pear MDB2 to connect to DB.

Does it mean that every instance of User will have MDB2 object initialised?

class User {
    private $login;
    private $hash;
    private $name;

    /* some getters and setters */
    //
    // public function get_name() { return $this->name }
    // ..
    //

    private $connect; // MDB2 connection
    private $dsn = ""; // connection config

    public function exists() { // return true if User exists
        require ('MDB2.php');
        $this->connect = MDB2::connect($this->dsn);
        // check
    }
}

Should I make $connect and $dsn variables static? Or may be I should use some pattern for this idea?

Update: (kind of decision)

I store database connection in static variable:

class DataBase {
    // connections options
    static public $connect = NULL;      // MDB2 connection variable
    static public $dsn = "pgsql://user:pass@IP/database";
    static public $connected = false;

    static function reportError() {
        if (PEAR::isError(self::$connect)) {
            $res["success"]=false;
            $res["errors"][] = self::$connect->getMessage();
            echo json_encode($res);
            exit;
        }
    } //: reportError

} //: Class DataBase

So If I want to connect to DB I write:

// connect only if it's not connected
if (!DataBase::$connected) {
    require_once('MDB2.php'); // Pear MDB2 class
    DataBase::$connect = MDB2::factory(DataBase::$dsn); // connection
    DataBase::$connected = true; // Flag that we're already connected
}

It's normal? Or I should make it another way?


texts: Optimization on Sieve of Eratosthenes using vector

texts:
I am solving this prime generator problem from SPOJ:

Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

I’m using the Sieve of Eratosthenes. Whenever I submit the following code it gives Time Limit Exceeded. Can anyone please give me some optimizations that can make my code run faster?
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
using ll = long long;

int main() {

    ios_base::sync_with_stdio(false);

    int t = 0;
    cin >> t;

    while (t--) {
        ll first = 0, n = 0;
        cin >> first >> n;
        vector<bool> primes(n+1, 0);

        for (ll i = 2; i <= sqrt(n); ++i) {
            if (primes[i] == 0) {
                for (ll j = 2; (i*j) <= n; ++j) {
                    primes[i*j] = 1;
                }
            }
        }

        for (ll i = 2; i <= n; ++i) {
            if (primes[i] == 0 && i >= first) {
                cout << i << '\n';
            }
        }

    }

    return 0;
}


texts: Find a better logic to remove duplicated code from two different methods

texts:
I have to update a class property with the method name and then call a method that executes some code based on this property. The code is the same in both methods, but I am not seeing a way to remove this code duplication. I am trying to avoid using a parameter.

public function register(){
    $this->operation = __FUNCTION__;
    $this->handleOperation();
}

public function unregister(){
    $this->operation = __FUNCTION__;
    $this->handleOperation();
}

Update 1

As Yoda suggested, here is a more complete code. It is a class to manipulate multiple functions for PHP autoloading. Now I am using parameters in handleOperation(). Example of use:

$Autoloader = new Autoloader();
$Autoloader->setFunctions(array('controllers', 'commons'));
$Autoloader->setModule('default');
$Autoloader->register();

Class code:

class Autoloader {

    private $functions_to_handle = array();
    private $module;
    private $function;
    private $paths = array();

    public function setFunctions($functions){
        $this->functions_to_handle = is_array($functions) ? $functions : array($functions);
    }

    public function setModule($module){
        $this->module = $module;
    }

    public function register(){
        $this->handleOperation(__FUNCTION__);
    }

    public function unregister(){
        $this->handleOperation(__FUNCTION__);
    }

    private function handleOperation($operation){
        $built_in_function = $this->mountBuiltInFunctionName($operation);

        foreach($this->functions_to_handle as $function){
            $built_in_function(array($this, $function));
        }
    }

    private function mountBuiltInFunctionName($operation){
        return 'spl_autoload_' . $operation;
    }

    private function controllers($classe) {
        $this->function = __FUNCTION__;

        $this->refreshPaths($classe);
        $this->loadClass();
    }

    private function commons($classe) {
        $this->function = __FUNCTION__;

        $this->refreshPaths($classe);
        $this->loadClass();
    }

    private function refreshPaths($classe){
        switch ($this->function) {

            case 'commons' :
                $this->paths = array(
                    '/usr/share/evokernel/core/common/' . $classe . '.php',
                );
            break;

            case 'controllers':
                $this->paths = array(
                    'core/controllers/' . $classe . '.php',
                    'modules/' . $this->module . '/controllers/' . $classe . '.php',
                    'shared/modules/' . $this->module . '/controllers/' . $classe . '.php'
                );
            break;

            default:
                throw new Exception('Invalid function: ' . $this->function);
        }
    }

    private function loadClass(){
        foreach ($this->paths as $path) {
            if (is_file($path)) {
                require_once($path);
                break;
            }
        }
    }
}


texts:
I am following CIS 194: Introduction to Haskell (Spring 2013) online to teach myself Haskell. Following is my response to third exercise of Homework 3, namely Histogram.

In which ways I could improve this, without getting too much into advanced topics of Haskell?

{-
For this task, write a function
histogram :: [Integer] -> String
which takes as input a list of Integers between 0 and 9 (inclusive),
and outputs a vertical histogram showing how many of each number
were in the input list. You may assume that the input list does not
contain any numbers less than zero or greater than 9 (that is, it does
not matter what your function does if the input does contain such
numbers). Your output must exactly match the output shown in the
examples below.

-}
histogram :: [Integer] -> String
histogram numbers =
    let initialcounts = take 10 (repeat 0)
        calculatedcounts = histogramcount numbers initialcounts
        maxheight = maximum calculatedcounts
        linefunctions = map drawline [maxheight,maxheight-1..1]
    in unlines ((map ($ calculatedcounts) linefunctions) ++ ["==========","0123456789"])

histogramcount :: [Integer] -> [Int] -> [Int]
histogramcount [] counts = counts
histogramcount (x:xs) counts =
    let
        xint = fromIntegral x
        newcount = (counts !! xint) + 1
    in histogramcount xs (take xint counts ++ [newcount] ++ drop (xint+1) counts)

drawline :: Int -> [Int] -> String
drawline level = map (\x -> if x >= level then '*' else ' ')

main = do
    putStr $ histogram [1,1,1,5]
    putStr $ histogram [1,4,5,4,6,6,3,4,2,4,9]


texts: Count "Word Order" with further optimization

texts:
Question:
You are given n words. Some words may repeat. For each word, print its number of occurrences. The output order should correspond with the input order of appearance of the word.

Sample Input:

4
bcdef
abcdefg
bcde
bcdef

Sample Output

3
2 1 1

Here's what I came up with:

n = int(input())
array = []
elements = {}
for index in range(n):
    value = input()
    if value not in array:
        array.append(value)
        elements[value] = 1
    else:
        elements[value] += 1

print(len(elements))
print(*(i for i in elements.values()), end=' ')

I stress tested it on Try it Online with the random string generator and found the runtime to be around 1.98s. But I'm getting TLE on the coding platform. How do I improve the speed (bit offtopic - is there any other approach)?


texts:
Using base R, I've conducted a simple profit sensitivity analysis, i.e. measuring the impact on profit if there is a change in price, variable cost per sale, unit sales or fixed costs assuming that there are no interaction effects between the dependent variables, e.g. a change in price does not change unit sales.

I'd like to have feedback on my code, which is 'just for fun'. Particularly I'm interested in:

Making the loops slicker
Assigning the matrices full of zeroes with fewer bytes if I can

# Aim: conduct a profit sensitivity analysis

# Define parameters

Param   = c(10,5,100000,10000) # I.e. a business with a price, variable cost, unit sales and fixed cost of these values

Max_Change  = 0.1
Changes     = seq(-Max_Change, Max_Change, by=0.01)

# Define profit function

Profit  = function(Price, Var_Cost, Units, Fixed_Cost){
Profit  = (Price - Var_Cost)*Units - Fixed_Cost
return(Profit)
}

# Calculating base and updated profit

Start_Profit = do.call("Profit", as.list(Param))

New_Price       = matrix(0,length(Changes),4)
New_Var_Cost    = matrix(0,length(Changes),4)
New_Unit_Sales  = matrix(0,length(Changes),4)
New_Fixed_Costs     = matrix(0,length(Changes),4)

for(i in 1:length(Changes))
{
New_Price[i,]       = c((1+Changes[i])*Param[1], Param[2], Param[3], Param[4])
New_Var_Cost[i,]        = c(Param[1], (1+Changes[i])*Param[2], Param[3], Param[4])
New_Unit_Sales[i,]  = c(Param[1], Param[2], (1+Changes[i])*Param[3], Param[4])
New_Fixed_Costs[i,]     = c(Param[1], Param[2], Param[3], (1+Changes[i])*Param[4])
}

Profit_New_Price        = matrix(0,length(Changes),1)
Profit_New_Var_Cost     = matrix(0,length(Changes),1)
Profit_New_Unit_Sales   = matrix(0,length(Changes),1)
Profit_New_Fixed_Costs  = matrix(0,length(Changes),1)

for(i in 1:length(Changes))
{
Profit_New_Price[i,]        = do.call("Profit", as.list(New_Price[i,]))
Profit_New_Var_Cost[i,]     = do.call("Profit", as.list(New_Var_Cost[i,]))
Profit_New_Unit_Sales[i,]   = do.call("Profit", as.list(New_Unit_Sales[i,]))
Profit_New_Fixed_Costs[i,]  = do.call("Profit", as.list(New_Fixed_Costs[i,]))
}

Diff_Profit_New_Price       = Profit_New_Price-Start_Profit
Diff_Profit_New_Var_Cost    = Profit_New_Var_Cost-Start_Profit
Diff_Profit_New_Unit_Sales  = Profit_New_Unit_Sales-Start_Profit
Diff_Profit_New_Fixed_Costs     = Profit_New_Fixed_Costs-Start_Profit

# Plot the profit sensitivities

options(scipen=999) # Remove scientific notation from the chart axes

msg=paste("Starting Business Conditions: Price = £",
    format(Param[1],big.mark=",",scientific=FALSE),
    ", Variable Cost = £",
    format(Param[2],big.mark=",",scientific=FALSE),
    ", Unit Sales = ",
    format(Param[3],big.mark=",",scientific=FALSE),
    ", Fixed Costs = £",
    format(Param[4],big.mark=",",scientific=FALSE),
    ", Giving a Profit of £",
    format(Start_Profit,big.mark=",",scientific=FALSE))

plot(100*Changes,Diff_Profit_New_Price,
    xlab="Change in Dependent Variable (%)",
    ylab="Change in Profit (£)",
    main="Profit Sensitivity Analysis of Changing One Variable at a Time, Assuming no Interaction Among Dependent Variables",
    type="l",
    sub=msg)

lines(100*Changes, Diff_Profit_New_Var_Cost, col="red")
lines(100*Changes, Diff_Profit_New_Unit_Sales, col="blue")
lines(100*Changes, Diff_Profit_New_Fixed_Costs, col="green")

# Building legend

Leg_Names = c("Price Change", "Variable Cost Change", "Unit Sales Change", "Fixed Costs Change")
legend("bottomright",
    legend=Leg_Names,
    col=c("black","red","blue","green"),
    pch=15,
    bty="n")


texts:
The aim of the program is to find those points which comes under the intersection of at least 2 circles.(space is a 1000x1000 matrix)

n=input()
mat=[[0 for i in range(1005)] for i in range(1005)]
circles=[]

for i in range(n):
    circles.append(map(int,raw_input().split()))

ans=0
for circle in circles:
    minx=circle[0]-circle[2]
    maxx=circle[0]+circle[2]
    miny=circle[1]-circle[2]
    maxy=circle[1]+circle[2]
    for i in range(minx,maxx+1):
        for j in range(miny,maxy+1):
            if mat[i][j]<=1:
                if ((i-circle[0])**2+(j-circle[1])**2)<=(circle[2]**2):
                    mat[i][j]+=1
                    if mat[i][j]>1:
                        ans+=1
print ans

n denoted the number of circle circles contain circle center and radius in the format [x,y,r]. For example, let circles = [[3,2,4],[2,5,2]]. Then it contains two circles centered at (3,2) and (2,5) with radius 4 and 2 respectively.

Is the logic correct? Will it trigger any exceptions?


texts: Custom sorting function implemented as a jQuery plugin

texts:
I was asked to create a jQuery plugin that would sort homogeneous DOM elements in a given DOM container element.

I came up with the idea to attach data-priority attribute to the elements that are to be sorted, e.g.:

..

, and later use that attribute in a jQuery plugin.

The algorithm that I came up with works like this:

Iterate over all elements that are to be sorted to find the element with the highest data-priority;
Append that element to the container;
Iterate over the remaining elements of the collection and find the element with the highest data-priority;
Append the element to the container;
...continue like this recursively until the collection of elements is empty.

My plugin is initiated like this: $('.col-sm-6').sortItemsInContainer('.offer-item'); (it essentially says "sort all .offer-item items in .col-sm-6 container").

This is the code:

(function($) {
    $.fn.sortItemsInContainer = function(itemsSelector) {

        // Recursively sort DOM elements - highest priority on top
        var positionElements = function($items, $container) {
            if (0 === $items.length) {
                return;
            }
            var $highestEle = findHighestElement($items);

            $container.append($highestEle);
            $items = $items.not($highestEle);

            return positionElements($items, $container); // Recursive call

        };

        // Find DOM element with highest priority
        var findHighestElement = function($items) {

            var firstItem = $items.get(0);
            var $highest = $(firstItem);

            $.each($items, function() {
                var $current = $(this);
                if ($current.data('priority') > $highest.data('priority')) {
                    $highest = $current;
                }
            });

            return $highest;
        };

        return this.each(function() {
            var $container = $(this);
            var $itemsToSort = $container.children(itemsSelector);
            positionElements($itemsToSort, $container);
        });
    };
})(jQuery);

Now my questions are:

Is my algorithm is optimal in terms of performance, or is it just terrible?
Is there any other obvious and substantially more efficient way to accomplish this?

and lastly,

I'd like to create some automated tests for this feature. Is this code testable? What would be the best way/technology to use in order to test it?


texts: Ternary operation in Java - isn't this abuse?

texts:
I think the below code is difficult to understand.  I also feel it abuses Java's ternary operator.

String name = ((this.getAllNamesAsDelimitedString().contains(incomingName) ?
               incomingName:
               (CollectionsUtils.isEmptyCollection(this.getEntityOperationMap()) ?
               null :
               this.getEntityOperationMap.get(incomingName))));

Above getAllNamesAsDelimitedString will return a comma (,) delimited String.

I'd prefer something instead of such a nested ternary operator, if it looks cleaner and easier to understand.  It would also be easy to sort out merge issue in, say, SVN.

N.B: There are even more nested ternary conditions in the code that I just have taken over.

Is there any general guideline which suggests the number of levels a ternary operator should be allowed?  In other words, any guideline suggesting when you should break your ternary operator for better code readability?


texts: Fun crypto problem: Exploiting a vulnerable encryption scheme with Python

texts:
I came across a question asked here and here on the Crypto Stack Exchange site, and decided to analyze it as a kind of case study. To demonstrate the concept, I wrote a short python script depicting the proposed encryption scheme. It's mostly list comprehensions or generator expressions and bitwise operations.

$$C=E_k(m)$$
$$C_\alpha = C\oplus m$$
$$C_\beta = \overline{C}$$
$$C_\Omega = C_\alpha\ ^\frown\ C_\beta$$

#!/usr/bin/env python3

from Crypto.Cipher import DES

m = b'secret!!'
k = b'qwerty!!'
E = DES.new(k, DES.MODE_ECB)
C = E.encrypt(m)

C_alpha = int('0b'+''.join([f"{x:08b}" for x in C]), 2) ^ \
          int('0b'+''.join([f"{x:08b}" for x in m]), 2)

C_beta  = int('0b'+''.join([f"{x:08b}" for x in C]), 2) ^ \
          int('0b' + '1' * len(''.join([f"{x:08b}" for x in C])), 2)

C_omega = f"{C_alpha:064b}" + f"{C_beta:064b}"

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

Then I ended up with this alternative version. If you want to try it out, save it as bad_scheme.py so it can work properly with the next script:

#!/usr/bin/env python3

from Crypto.Cipher import DES

m = b'secret!!'
k = b'qwerty!!'
E = DES.new(k, DES.MODE_ECB)
C = E.encrypt(m)

def bitwise_xor(bits_a, bits_b):
    bits_out = ''.join([str(int(x)^int(y)) for x, y in zip(bits_a, bits_b)])
    return(bits_out)

def bitwise_complement(bits_in):
    bits_out = ''.join([str(~int(x)+2) for x in bits_in])
    return(bits_out)

def C_alpha():
    bits_out = bitwise_xor(''.join([f"{x:08b}" for x in C]),
                           ''.join([f"{x:08b}" for x in m]))
    return(bits_out)

def C_beta():
    bits_out = bitwise_complement(''.join([f"{x:08b}" for x in C]))
    return(bits_out)

def C_omega():
    bits_out = C_alpha() + C_beta()
    return(bits_out)

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

And here's what is essentially a working exploit of the (hypothetical) proposed encryption scheme's vulnerability; demonstrating the plaintext can be revealed without the key. It imports the final ciphertext and the bitwise functions from the first script, and works backwards, and complements \$C_\beta\$ to get \$C\$ (because \$C_\beta\$ is essentially just \$\overline{C}\$), then \$C \oplus C_\alpha\$ to reveal \$m\$ without requiring \$k\$. So:

$$\overline{C_\beta}=C$$
$$C_\alpha \oplus C=m$$

#!/usr/bin/env python3

from bad_scheme import C_omega, bitwise_xor, bitwise_complement

def C_alpha():
    bits_out = C_omega()[:int(len(C_omega())/2)]
    return(bits_out)

def C_beta:
    bits_out = C_omega()[int(len(C_omega())/2):]
    return(bits_out)

def C():
    bits_out = bitwise_complement(C_beta())
    return(bits_out)

def m():
    bits_out = bitwise_xor(C_alpha(), C_beta())
    return(bits_out)

if __name__ == '__main__':
    print(''.join([chr(int(m()[i:i+8],2)) for i in range(0,len(m()),8)]))

So, there it is. Just thought I'd put it out there and see what everyone thinks, which style is better, what's good about it, what's bad about it, and what I can do to improve it. It's not a real encryption scheme or anything, I'm mainly interested in feedback regarding design and execution, the handling of bitwise operations, and the general layout and structure of the code. I tried implementing a class and a few things to make it more robust and useful, but I couldn't pull it off. Also, is it better organized as functions? Or doing the same thing in fewer lines, just defining and operating on variables, and declaring no functions at all.


texts: Async function to write products to file

texts:
I'm currently trying to learn how to use await/async functions. Could anyone offer any thoughts on how to improve this function which uses await inside a for loop?

I think the task would run in parallel if I could figure out how to write each row asynchronously, but haven't been able to make it work with Promise.all.

//Using Sequelize && Node v7.10
async function writeToFile(wfile,rtext) {
  const wstream = await fs.createWriteStream(wfile);
  for (row of rtext) {
    const srow = row.trim().split(',');
    const company = srow[0].split(' ')[0];
    const sku = srow[1];
    const cdescription = srow[2] || '';
    try {
      let cproduct = await CModal.findOne({
        where: {
          sku: sku,
          company: {
            $iLike: `%${company}%`
          }
        },
        include: [ Product ]
      });
      if(cproduct == null) {
        let product = null;
        let csvrow = '';
        if(cdescription.length > 1) {
          product = await Product.findOne({ where: { description: { $ilike : `%${cdescription}%`} } });
        }
        await wstream.write(csvrow);
        continue;
      }
      if( cproduct.Products.length < 1) {
        const csvrow = `${company},="${sku}"\n`;
        await wstream.write(csvrow);
        continue;
      }
      for (product of cproduct.Products) {
        const description = product.description.replace(',|;|\Q|\E','');
        const csvrow = `${company},="${sku}"\n`;
        await wstream.write(csvrow);
      }
    } catch (err) {
      console.error(err);
    }
  }
  let location = await uploadToS3(wfile);
  await fileInfo.update({
    status: "FINISHED",
  });
}


texts: Creating a menu as nested unordered lists from JSON data

texts:
I have a JSON input using which I have written below function to recursively create an unordered list.

Is there more precise way to achieve it?

$(document).ready(function () {
        var htmlTxt = "";
        var cat = [];
        var htmlStrTxt = "";
        var url = "#";

        function recurseMenu(parent, level) {
            htmlStrTxt = '
';
            for (var x in menuItems) {
                if (menuItems[x].parentId == parent) {
                    htmlStrTxt += '
' + menuItems[x].title + '';

                    if (menuItems[x].childCount > 0) {
                        htmlStrTxt += recurseMenu(menuItems[x].id, level + 1);
                    }
                    htmlStrTxt += '
';
                }
            }
            return htmlStrTxt + '
';
        }

        var htmlTxt = recurseMenu(null, 0);
        $("#listContainer").html(htmlTxt);
     });


texts: A Decorator that turns Function Annotations into Type Checks

texts:
Answering a question on S/O about type annotations led to me writing a little decorator that adds type checking to functions with annotated arguments. It supports the meta types Any, Optional[], and Union[], as well as combinations such as Optional[Union[...]]. It takes no arguments itself, for ease of use.

I'm fairly new to non-SQL programming in general so I'd love feedback. There's a short README in its Github repo.

from typing import Callable, Union, Optional
from functools import wraps
from itertools import zip_longest
import re

def enforce_types(func: Callable) -> Callable:
    """Adds run-time type checking to a fully-annotated function"""

    @wraps(func)
    def wrapper(*args, **kwargs):

        for argument, annotation, value in zip_longest(
            *zip(*func.__annotations__.items()), args,
            fillvalue=""
        ):
            # If we have Optional args, we could have more annotations than supplied arguments
            if value == "":
                break
            # Type Any can take... any type, so continue
            elif annotation == "Any":
                continue

            value_type = type(value).__name__

            # Check for meta types
            is_optional: bool = "Optional" in str(annotation)
            is_union: bool = "Union" in str(annotation)

            # If Optional[], get the optional type
            if is_optional:
                annotation = re.search("Optional\[(.*)\]", str(annotation)).group(1)

            # If Union[], get the list of types
            if is_union:
                annotation = re.search("Union\[(.*)\]", str(annotation)).group(1)

            # If there's just one type allowed, check against it
            if not is_union and value_type != annotation.__name__:
                raise TypeError(
                    f"Argument {argument} supplied wrong type: expected {annotation.__name__}, got {value_type}."
                )
            # If it's not a Union and it passed the last check,
            # or if it's a Union and a valid type was passed in, continue
            elif (not is_union) or (is_union and value_type in annotation):
                continue
            # If there's a type Union, check against the possible types
            elif is_union and value_type in annotation:
                continue
            # If we get here, the argument isn't any of the appropriate values
            else:
                raise TypeError(
                    f"Argument {argument} supplied wrong type: expected one of [{annotation}], got {value_type}"
                )

        return func(*args, **kwargs)

    return wrapper

Example of usage:

>>> from type_enforcer import enforce_types
>>> from typing import Union, Optional

>>> @enforce_types
... def foo(x: Union[int, float], y: Optional[int] = 1) -> int:
...     return int(x * y)

>>> foo(5, 2)
10

>>> foo(5)
5

>>> foo(5.)
5

>>> foo(5., 2)
10

>>> foo('5')
Traceback (most recent call last):
  ...
TypeError: Argument x supplied wrong type: expected one of [int, float], got str

>>> foo(5, 2.)
Traceback (most recent call last):
  ...
TypeError: Argument y supplied wrong type: expected one of [int, NoneType], got float


texts: Linked list delete a node with a particular value

texts:
I am trying to search a single linked list with a particular value and delete it. Only the first occurrence of the value.

typedef struct node {
int val;
struct node * next;
} node_t;

So my code is:

int remove_by_value(node_t ** head, int val) {
    /* TODO: fill in your code here */
    node_t *temp = *head;
    if(*head == NULL)
        return -1;

    if((*head)->next == NULL && (*head)->val == val)
    {
        *head = NULL;
        return 0;
    }

    while(temp->next->val != val)
    {
        temp = temp->next;
    }

    temp->next=temp->next->next;
    return 0;
}

The above solution works fine.
My question is:

Is this correct way of doing it? Because when I searched online, there are different solutions.
Am I missing any corner cases? I check for empty list and whether the head node contains the first occurrence.

Please help me improve my code.
Thanks


texts:
I made a simple program in Python

stores tasks in the file
allows the user to manage them.

I'm interested if my implementation is efficient and could I do something better. I'm not sure whether loading all data from file to memory and again saving it in the file is a good way to implement list saving tasks.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os

CHOICE_LIST_TASKS = 1
CHOICE_ADD_TASK = 2
CHOICE_REMOVE_TASK = 3
CHOICE_QUIT = 4

def read_int(prompt='> ', errmsg='Invalid number!'):
    num = None
    while num is None:
        try:
            num = int(input(prompt))
        except ValueError:
            print(errmsg)
    return num

def display_menu():
    print('What do you want to do?')
    print('[1] List all tasks')
    print('[2] Add a new task')
    print('[3] Delete task')
    print('[4] Quit')

choice = None
file = None
if not os.path.exists('tasks'):
    file = open('tasks', 'w+')
else:
    file = open('tasks', 'r+')
tasks = []

for line in file.readlines():
    tasks.append(line.strip())

while choice != CHOICE_QUIT:
    display_menu()
    choice = read_int()
    if choice == CHOICE_LIST_TASKS:
        if len(tasks) == 0:
            print('Task list is empty!')
        else:
            print('Tasks:')
            for x in tasks:
                print(x)
    elif choice == CHOICE_ADD_TASK:
        desc = input('Which task do you want to do? ')
        index = tasks.append(desc)
        print('Successfully added a new task!')
    elif choice == CHOICE_REMOVE_TASK:
        if len(tasks) == 0:
            print('Task list is empty!')
        else:
            for x in tasks:
                print(tasks.index(x), x)
            index = read_int('Which task do you want to delete? ')
            try:
                tasks.pop(index)
                print('Successfully deleted task!')
            except IndexError:
                print('Please enter proper task number')
    elif choice == CHOICE_QUIT:
        print('Good bye!')
    else:
        print('Invalid choice!')

file = open('tasks', 'w+')
for x in tasks:
    file.write(x + '\n')


texts:
Most of my experience is in Python, Java and embedded C, and I need to learn Scala and Play for a new job. As an exercise, I decided to create a very simple API for looking up area by postal code, backed by Redis. It's just a single controller with a couple of routes.

I'm hoping for feedback from experienced Scala or Play users. Please suggest any improvements to make the code more readable, maintainable, idiomatic, performant, secure etc. As a starting point, I enabled several static analysis tools in my build and fixed the issues reported.

controllers/JPI.scala

package controllers

// Scala imports
import util.control.Breaks._

// Play imports
import play.api.mvc._
import play.api.Play.current
import play.api.cache.Cache
import play.api.libs.json._
import com.typesafe.plugin.RedisPlugin

// Java imports
import java.io.{BufferedReader, InputStreamReader}
import java.net.URL
import java.util.zip.ZipInputStream

object JPI extends Controller {

  final val JapaneseURI = "http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip"
  final val TestURI = "http://localhost:9000/assets/ken_all.zip"
  final val CSVEncoding = "SJIS"

  final val PostalCodeMin = 0
  final val PostalCodeMax = 9999999
  final val PostalCodeFmt = "%07d"

  final val CSVFields = List(
    ("prefecture_kana", 3),
    ("municipality_kana", 4),
    ("neighbourhood_kana", 5),
    ("prefecture_kanji", 6),
    ("municipality_kanji", 7),
    ("neighbourhood_kanji", 8)
  )

  /**
   Lookup a numeric postal code in the Redis cache
  */
  def lookup(postalCode: Integer) = Action {
    if (postalCode < PostalCodeMin || postalCode > PostalCodeMax) {
      NotFound(
        "Postal code outside valid range (%s to %s)".format(
          fmt(PostalCodeMin), fmt(PostalCodeMax)
        )
      )
    } else {
      val json: Option[String] = Cache.getAs[String](postalCode.toString)
      json match {
        case None => NotFound("Postal code not found")
        case Some(j) => Ok(j).as("application/json; charset=utf-8")
      }
    }
  }

  /**
    Imports postal codes from a zipped CSV reference as follows:
    - Download the complete code directory from the specified URL
    - Unzips the first file and parses the CSV rows
    - Serializes CSV rows into JSON
    - Inserts JSON objects into Redis hash
   */
  def buildCache() = Action {
    val inStream = new ZipInputStream(new URL(TestURI).openStream)
    val csvFile = Option(inStream.getNextEntry)
    csvFile match {
      case Some(f) => {
        val reader = new BufferedReader(new InputStreamReader(inStream, CSVEncoding))
        for (line <- Iterator.continually(Option(reader.readLine)).takeWhile(!_.isEmpty)) {
          breakable {
            val elements = line.getOrElse(break).split(",")
            val code = stripQuotes(elements(2))
            Cache.set(code, Json.stringify(parseCSVRow(elements)))
          }
        }
        Ok("Cache rebuilt")
      }
      case None => InternalServerError("Cache rebuild failed")
    }
  }

  /**
    Format a numeric postal code as a String
  */
  private def fmt(postalCode: Integer) : String = {
    PostalCodeFmt.format(postalCode)
  }

  /**
    Strip trailing and leading quotes from a String
  */
  private def stripQuotes(s : String) : String = {
    s.stripPrefix("\"").stripSuffix("\"")
  }

  /**
    Parse and convert a CSV row into a JSON object according to mapping in CSVFields
  */
  private def parseCSVRow(row : Array[String]) : JsObject = {
    val strippedRow = row map { stripQuotes(_) }
    val fields = CSVFields map {
      f => f._1 -> Json.toJsFieldJsValueWrapper(strippedRow(f._2))
    }
    Json.obj( fields: _* )
  }

}

Building and running this code is as simple as:

git clone https://github.com/bsutherland/jpi.git
cd jpi
sbt compile
sbt run


texts: Simple way to loop through a JavaScript object array?

texts:
I have an object array and i am using gulp 4.
libs:
    {
        a: {
          js: [
            {
              src: 'path/from/a1.js',
              dest: 'path/to/a1.js',,
            },
            {
              src: 'path/from/a2.js',
              dest: 'path/to/a2.js',,
            },
          ],
          css: [
            {
              src: 'path/from/a1.css',
              dest: 'path/to/b1.css',,
            },
          ],
        },
        b: {
          js: [
            {
              src: 'path/from/b.js',
              dest: 'path/to/b.js',,
            },
          ],
        },
      }

I need to know all the src and dest values so that I can move files from src to dest.
const moveLibs = (done) => {
  Object.entries(libs).forEach(([key, value]) => {
    const types = value;

    Object.entries(types).forEach(([key, value]) => {
      const srcAndDest = value;

      Object.entries(srcAndDest).forEach(([key, value]) => {
        return gulp
          .src(value.src)
          .pipe(gulp.dest(value.dest));
      });
    });
  });

  done();
};

This method is successful, but I feel that it is not simple enough, please tell me a simpler method, thank you.


texts: Improving readability of enabling method

texts:
There doesn't seem to be anything really wrong with this method. But it has a little smell to me. Does the name make sense (do what you think it would do). Is there some logic I could use to make the enabler a bit more elegant?

private void tryEnableCRUD(bool tryEnable = true)
{
    bool enable = false;
    if (_securityLevel < 3)
    {
        enable = tryEnable;
    }
    else
    {
        enable = tryEnable;
    }

    tsbDelete.Enabled = enable;
    tsbReplace.Enabled = enable;
    tsbUpload.Enabled = enable;
}

UPDATE

private void tryEnableCRUD(bool tryEnable = true)
{
    bool enable = false;
    if (_securityLevel < 3)
    {
        enable = tryEnable;
    }
    tsbDelete.Enabled = enable;
    tsbReplace.Enabled = enable;
    tsbUpload.Enabled = enable;
}


texts: Exponential growth calculator for COVID-19

texts:
I've been listening to some programmers and they use terms like good and bad code. I am not really sure what they mean by that. I mean I went on r/badcode and saw some stuff I knew was definitely bad code. But I don't really understand if bad code is repeatedly typing the same code instead of looping or just bad layouts.
    import java.io.IOException;
    import java.util.Scanner;
    class Covid19ExpoGrowth {
    public static void main(String[] args) throws IOException {
    // I will use the formula y = a(1 + r)^x
    // a = initial value
    // r = growth rate
    // x = time interval
    int a;
    double r;
    int x;

    // Workout exponential growth
    System.out.println("Let us see the Exponential growth of Covid-19.");
    System.in.read();
    System.out.println("We will set the initial value of Covid as 88,000 as that was the amount of cases in february");
    a = 88000;
    System.in.read();

    System.out.println("We need to find the growth rate of Covid-19, we can use the growthRate method");
    System.in.read();
    r = growthRate(14000, 88000);
    r = Math.round(r * 10.0) / 10;
    System.out.println("Using the growthRate method, we worked out the growth rate is: " + r + " rounded to no d.p");
    System.in.read();

    System.out.println("The time interval will be from February 01 2020 - April 16 2020, 45 days");
    x = 45;
    System.in.read();

    System.out.println("Now we have all the values let us use the method calculateExpoGrowth");
    System.in.read();
    double roundedExpo;
    roundedExpo = Math.round(calculateExpoGrowth(a, r, x) * 100) /10;
    System.out.println("The Exponential growth of Covid 19 is: " + roundedExpo + " rounded to 2 d.p");

    System.out.println("You can now work out your own Exponential Growth");

    // User works out chosen exponential growth
    while (true) {
        System.out.println("Please enter the initial value");
        Scanner scan = new Scanner(System.in);
        a = scan.nextInt();

        Scanner scan_gr = new Scanner(System.in);System.out.println("Enter WORKOUT GROWTH RATE if you would like to workout the growth rate," +
                "if you already know it press enter");
        String gr = scan_gr.nextLine();
        if (gr.equals("WORKOUT GROWTH RATE")) {
            int pastValue;
            int presentValue;

            System.out.println("Please enter the past value");
            pastValue = scan.nextInt();

            System.out.println("Please enter the present value");
            presentValue = scan.nextInt();

            r = growthRate(pastValue, presentValue);
        } else {
            System.out.println("Please type in the growth rate");
            r = scan.nextDouble();
        }
        System.out.println("Now finally, type in the time interval");
        x = scan.nextInt();
        double roundedExpo2;

        roundedExpo2 = Math.round(calculateExpoGrowth(a, r, x) * 100) / 10;

        System.out.println("The program has calculated the Exponential growth is: " + roundedExpo2 + " rounded to 2 d.p");
    }
}
public static double growthRate(int pastVal, int presentVal){
    // To work out growth rate you:

    double newVal = presentVal - pastVal;
    // Subtract the past value from the present value

    return newVal / pastVal;
    // Divide the new value by the past value

}
public static double calculateExpoGrowth(int a, double r, int x){
    // Exponential growth formula
    return (a * Math.pow((1 + r), x));

}
}


texts: Project Euler 35: Circular primes below 1 million

texts:
I'm doing another Project Euler problem, number 35:

  The number, 197, is called a circular prime because all rotations of
  the digits: 197, 971, and 719, are themselves prime.

  There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31,
  37, 71, 73, 79, and 97.

  How many circular primes are there below one million?

import math
num = 0
primeList = []

def isprime(test):
    if test == 2:
        primeList.append(2)
        return True
    elif test < 2:
        return False
    else:
        for i in primeList:
            if i > math.sqrt(test):
                break
            elif test % i == 0:
                return False
        primeList.append(test)
        return True

def rotations(n):
    answer = []
    rotation = n
    while not rotation in answer:
        answer.append(rotation)
        rotation = int(str(rotation)[1:] + str(rotation)[0])
    return answer

for i in range(2,1000000):
    numList = rotations(i)
    valid = True
    for j in numList:
        if not isprime(j):
            valid = False
    if valid:
        num += 1

    print(num)

I need help improving my code speed.  What I really think is happening is the rotations() function is slowing the whole thing down.


texts: Function to log arguments and return value of any function in Clojure

texts:
I have implemented a function, which logs the inputs and outputs of any function, indenting the log based on the depth of the call stack:

(def depth (atom 0))

(defn logfun [fun]
       (fn [& args]
           (do
               (swap! depth inc)
               (println (str (apply str (repeat @depth " ")) ">>> (" fun " " args ")"))
               (let [result (apply fun args)]
                    (do
                         (swap! depth dec)
                         (println (str (apply str (repeat @depth " ")) " <<< " result))
                         result)))))

Usage example:

(defn fact [n] (if (> n 1) (* n (fact (dec n))) n))
(def fact (logfun fact))
(fact 5)

Output:

 >>> (lang.core$fact@5eb14bce (5))
  >>> (lang.core$fact@5eb14bce (4))
   >>> (lang.core$fact@5eb14bce (3))
    >>> (lang.core$fact@5eb14bce (2))
     >>> (lang.core$fact@5eb14bce (1))
     <<< 1
    <<< 2
   <<< 6
  <<< 24
 <<< 120

Main questions:

Is there a way to improve this function so that it is not dependent on global variables? (I have already attempted a solution based on with-local-vars / var-set -- see below, but it seems to me that they do not work as I wish they did).
Are there any edge cases, for which the above function does not work?
Are there any modifications by which this function can be made better adhering to Clojure best practices (besides somehow getting rid of the global state)?
Is there a way to improve the output of the function names (e.g., instead of lang.core$fact@5eb14bce I would like to get lang) in a way that satisfies both conditions below:

It must be available in the Clojure core language (no third-party libs, no usage of repl utilities)
It must not use string manipulation (e.g. find the @ and $ characters via regexp and then strip away the parts before/after them).

In other words, I'm looking for something like: (get-pretty-printed-function-name fun). (I already did some research, and found only solutions which do not satisfy the criteria above. Still asking, just in case ;) )

The attempted, NOT WORKING solution using var-set/with-local-vars:

(defn logfun [fun]
   (with-local-vars [depth 0]
       (fn [& args]
           (do
               (var-set [depth (inc @depth)])
               (println (str (apply str (repeat @depth " ")) ">>> (" fun " " args ")"))
               (let [result (apply fun args)]
                    (do
                         (println (str (apply str (repeat @depth " ")) " <<< " result))
                         (var-set [depth (dec @depth)])
                         result))))))

EDIT: using bound-fn, I get one step further, but unluckily it still does not do what is expected, as it seems that the variable depth in the closure is reset to zero upon every invocation of the returned function:

(defn logfun [fun]
   (with-local-vars [depth 0]
       (bound-fn [& args]
           (do
               (var-set depth (inc @depth))
               (println (str (apply str (repeat @depth " ")) ">>> (" fun " " args ")"))
               (let [result (apply fun args)]
                    (do
                         (var-set depth (dec @depth))
                         (println (str (apply str (repeat @depth " ")) " <<< " result))
                         result))))))

Result:

 >>> (lang.core$fact@510da75f (5))
 >>> (lang.core$fact@510da75f (4))
 >>> (lang.core$fact@510da75f (3))
 >>> (lang.core$fact@510da75f (2))
 >>> (lang.core$fact@510da75f (1))
 <<< 1
 <<< 2
 <<< 6
 <<< 24
 <<< 120


texts:
This is a program I wrote to convert binary to ASCII. I am still learning ARM assembly. How can I improve my program? Are there any bad programming habits in my code?

I've tested it on Raspberry Pi and Android.

@
@ ARM assembly programm which converts binary to ASCII
@ written by Kyle Kersey,  (C) 2015
@

.global main

main:
    adr r2, content     @ load address of binary string
    mov r3, #0          @ bit counter
    mov r4, #0          @ byte value
    b loop

loop:
    ldrb r0, [r2], #1   @ load next byte from memory
    cmp r0, #0          @ check for null terminator
    beq end_loop        @ quit loop

    sub r0, r0, #48     @ convert '0' or '1' to 0 or 1 to a bit
    lsl r4, r4, #1      @ byte<<1
    add r4, r4, r0      @ byte+=bit

    add r3, r3, #1      @ increment bit counter

    cmp r3, #8          @ if at 8th bit
    moveq r0, r4        @ move byte to r0 for printing
    moveq r4, #0        @ clear byte
    moveq r3, #0        @ clear bit counter
    bleq printChar      @ print byte, branch with link

    b loop              @ continue loop, branch without link

end_loop:
    mov r0, #10         @ ascii new line
    bl putchar          @ print new line
    mov r7, #1          @ return 0
    swi 0               @ call software interupt 0

printChar:
    push {r2, lr}       @ store content and return address
    bl putchar          @ print ascii character stored in r0
    pop {r2,lr}         @ restore the content and return address
    mov pc, lr          @ set the return address

charFormat:
    .asciz "%c"
    .align 4

content:
    .ascii "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100\000"


texts:
I've developed a function to calculate the exit angle of a projectile after it collides with a boundary/edge inside a rectangular space, based on the entry angle and the axis it is colliding with.

Given those two factors, the actual boundary is implied, since a projectile travelling at an angle of 315° (where 0°/360° sit at 3 o'clock) and colliding with a horizontal boundary (the x axis) must be colliding with the top boundary.

The current implementation came about through iterative refactoring of a much more verbose and redundant version, however I can't vocalise exactly why some parts are necessary, but they appear to satisfy the requirements and I'm confident it works based on a number of tests.

function reflectAngle(angle, axis) {

    if (angle % 90 === 0)
        return (angle + 180) % 360;

    let reflected;
    let segment = (angle % 90) * 2;

    if (axis === 'X')
        reflected = angle + (180 - segment);

    else if (axis === 'Y')
        reflected = angle - segment;

    if (angle < 90)
        reflected += 180;

    return reflected % 360;
}

Can this function be simplified or improved for readability?


texts: Invert-range operation in a circular vector

texts:
I implemented a invert-range operation in a (logical) circular vector. A circular vector is a vector without a logical starting and ending object, or, equivalently, the successive element of the element at the last index of the vector is the element at index 0 (similarly for the previous element).

I'm not 100% sure it's correct. If it's correct, any suggestions to improve it (especially in terms of performance)?

#include <cmath>

...

vector<SomeObject> vec;

...

/*
 * Invert the segment starting at object at index i and ending at object at index j.
 * */
void invert(const int i, const int j) {

    // assert i and j are in the bounds

    if (vec.size() < 2 || i == j) {
        return;
    }

    int segment_size;

    if(j < i ){
        segment_size = std::ceil(((vec.size() - i) + j) / 2.0);
    } else {
        segment_size = std::ceil(std::abs(j - i) / 2.0);
    }

    for (int x = 0, k = i, w = j; x < segment_size; ++x) {
        std::swap(vec[k], vec[w]);
        k = next(k);
        w = previous(w);
    }

}

where next and previous are the following procedures:

/*
 * Returns the index to the object after the object at index i.
 * */
int next(const int i) {
    return (i + 1) % vec.size();
}

/*
 * Returns the index to the object before the object at index i.
 * */
int previous(const int i) {
    return (i - 1) % vec.size();
}

Note: these functions were actually methods, i.e. part of a class, and they actually working on a field and not on, e.g., global variable.


texts: TwoFish implementation with Bouncy Castle

texts:
After much research, I was able to implement the twofish algorithm using Bouncy Castle Portable for .NET. The code has been tested and is working perfectly, to the best of my knowledge.  But I do not know if it was well implemented and I would like someone's opinion. It would be nice to know if it is done correctly because it would be for other developers to use. Is there any improvement in security and performance that could be made? Any idea?

public class BCEngine
{
    private readonly Encoding _encoding;
    private readonly IBlockCipher _blockCipher;
    private PaddedBufferedBlockCipher _cipher;
    private IBlockCipherPadding _padding;

    public BCEngine()
    {

    }

    BCEngine(IBlockCipher blockCipher, Encoding encoding)
    {
        _blockCipher = blockCipher;
        _encoding = encoding;
    }

    #region Public Methods

    public static string TwoFishEncryption(string TextPlain, string Password, byte[] Salt)
    {
        Sha3Digest Sha3Digest = new Sha3Digest();
        Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator(Sha3Digest);
        gen.Init(Encoding.UTF8.GetBytes(Password), Salt, 1000);
        KeyParameter param = (KeyParameter)gen.GenerateDerivedParameters(new TwofishEngine().AlgorithmName, 256);

        BCEngine bcEngine = new BCEngine(new TwofishEngine(), Encoding.UTF8);
        bcEngine.SetPadding(new Pkcs7Padding());
        return bcEngine.Encrypt(TextPlain, param);
    }

    public static string TwoFishDecryption(string TextEncripted, string Password, byte[] Salt)
    {
        Sha3Digest Sha3Digest = new Sha3Digest();
        Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator(Sha3Digest);
        gen.Init(Encoding.UTF8.GetBytes(Password), Salt, 1000);
        KeyParameter param = (KeyParameter)gen.GenerateDerivedParameters(new TwofishEngine().AlgorithmName, 256);

        BCEngine bcEngine = new BCEngine(new TwofishEngine(), Encoding.UTF8);
        bcEngine.SetPadding(new Pkcs7Padding());
        return bcEngine.Decrypt(TextEncripted, param);
    }

    #endregion

    #region Private Methods

    void SetPadding(IBlockCipherPadding padding)
    {
        if (padding != null)
            _padding = padding;
    }

    string Encrypt(string plain, ICipherParameters SetKeyParameter)
    {
        byte[] result = BouncyCastleCrypto(true, _encoding.GetBytes(plain), SetKeyParameter);
        return Convert.ToBase64String(result);
    }

    string Decrypt(string cipher, ICipherParameters SetKeyParameter)
    {
        byte[] result = BouncyCastleCrypto(false, Convert.FromBase64String(cipher), SetKeyParameter);
        return _encoding.GetString(result, 0, result.Length);
    }

    byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters SetKeyParameter)
    {
        try
        {
            _cipher = _padding == null ?
            new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);

            _cipher.Init(forEncrypt, SetKeyParameter);

            byte[] ret = _cipher.DoFinal(input);
            return ret;

        }
        catch (CryptoException ex)
        {
            // throw new CryptoException(ex);
        }
        return null;
    }

    #endregion

}


texts:
I want to make testable network calls using Swift.

For example, I want to download the latest from AWS if and only if it's version is newer than the downloaded file.

In order to do this I've created a function:

func requestDownloadLinkForAWS() {
    DispatchQueue.global(qos: .background).async { [weak self] in
        guard let self = self else {return}
        // Hard coded download for testing - where will this compatibility file be hosted??
        do {
            let decoder = JSONDecoder()
                if let dataResponse = content.data?[0]
                    {
                        if (dataResponse.appMinimumVersion >= appVersionString) && (dataResponse.appTargetVersion >= appVersionString) {
                            if let version = self.stagingBundle.getVersion()
                            {
                                if (version < dataResponse.version) {
                                    self.downloadLatestFileAWS(dataResponse.bucketName, dataResponse.folderName, dataResponse.version)
                                }
                            }
                        }
                    }
            }
        } catch let error as NSError {
            print ("\(error) 2 error")
        }
    }
}

Now my self.downloadLatestFileAWS is an async function that I can easily test.

My problem is to test the function above. There is no output here, but I need to test this function. What refactoring could I do to make this testable?


texts:
I made a basic website to practice HTML and CSS that will display 3 fruits with their given scores in an Olympic podium sort of way.

Have I used any bad practices and what I should do instead?

What can I do to fully optimize and shorten my code?

How readable is my code? How can I make it more readable?

    <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

Highest Fruit Score: 83

65

83

34


texts: Filtering out the correct car from a list of cars and retrieving only one car

texts:
I am filtering out a List<Car> based on the brand. Since each car is made by one brand, I want to make sure my method getCar() is called and just a single car is returned. If it returns more than one car, throw an exception.

This is a simplified example, my current implementation is as follows:

I have a list of cars stored in an array list, please assume this list cars already has car object stored in them.
Also, in my Car class implementation, I have a method call isCorrectBrand() which check if the brand matches.

List<Car> cars;

public Car getCar(String brand) {
    List<Car> filteredCars = new ArrayList<>();
    cars.stream()
            .filter(car -> car.isCorrectBrand(brand))
            .forEach(filteredCars::add);

    if (filteredCars.size() > 1) {
       throw new Exception("");
    } else {
      return filteredCars.get(0);
    }
}

My approach is to first loop through the cars list, store them in a temp list, and if the list is size one, that means everything is fine, otherwise it indicates something wrong with either the brand message or the isCorrectBrand() implementation.

My questions are:

Is the exception thrown an appropriate one, if not what exception is appropriate for this use?
Is there a better way of writing this?


texts: A small module that allows threads to return their result

texts:
I have the following that works similar to forkIO, but returns a blocking "channel" that lets you receive the result of a forked IO computation. My main concern is its handling of exceptions. It will return Nothing if something is raised, but can't supply any more information then that.

I tried using try inside of wrapAction, which returns an (Either Exception a), but I couldn't figure out what exception type to use. I tried SomeException thinking it would catch everything, and supply a message, but it doesn't. Running a computation that divides by 0 resulted in Right being returned, but threw a "divide by 0" exception when I tried inspecting the result. Surely in a generic situation like this I can't specifically catch every possible exception (given a user could create their own). How should I set up the exception handling so that a Leftcan be returned with an exception message?

import Control.Concurrent
import Control.Exception

data RThread a = RThread (IO a) (MVar (Maybe a))

newReturn :: IO a -> IO (RThread a)
newReturn act = newEmptyMVar >>= return . RThread act

wrapAction :: RThread a -> IO ()
wrapAction (RThread act chan) = onException (act >>= putMVar chan . Just) (putMVar chan Nothing)

returnFork :: IO a -> IO (RThread a)
returnFork act = do
    nR <- newReturn act
    forkIO $ wrapAction nR
    return nR

waitForResult :: RThread a -> IO (Maybe a)
waitForResult (RThread _ chan) = takeMVar chan

Any critique would be appreciated

Simple usage:

import System.Random
import Control.Monad

testFn :: IO [Int]
testFn = returnFork (replicateM 100 $ randomRIO (1,100) >>=
    waitForResult

Although realistically you would pass the result of waitForResult somewhere else to wait.


texts: Watch log dir for new file, automatically tail to slack

texts:
We have a process that outputs to log files in the format /var/log/xxx/YYYY_MM_DD.log - the file name is chosen programmatically and is not rotated using logrotate or anything like that. We want to automatically tail the latest file and pipe that to slackcat so that we can see the logs in a certain slack channel.

I came up with the following solution that works great, but I'm no bash expert so I am wondering if this could be simplified? The hardest part was avoiding zombie processes when something dies or gets killed, but I'd love to do this with one file instead of 2 also:

watchlogdir.sh

#!/bin/sh
trap "pkill -TERM -g $$; exit" INT TERM EXIT
    while true; do
      /root/tailtoslack.sh &
      PID=$!
      echo $PID
      echo $$
  inotifywait -e create /var/log/xxx/
  pkill -TERM -P $PID
  kill $PID
done

tailtoslack.sh

while true; do
    FILETOWATCH=`ls -t /var/log/xxx/*.log | head -1`
    tail $FILETOWATCH -f -n1 | grep -v "DEBUG:\|^$" --color=never --line-buffered | /root/slackcat &> /tmp/slackcat
    sleep 31
done

The core of watchlogdir.sh, besides the interruption handling stuff, is using inotifywait to watch for a new file created in the log directory, and when that happens, killing tailtoslack.sh and respawning it so it can find the new file

tailtoslack.sh just looks for the latest file, and pipes that to slackcat after filtering out DEBUG lines and empty lines. the while loop here is because some lines in the error logs cause slackcat to crash, so this way if that happens it'll sleep for a little while and retry.

Without changing the requirements of how the log files are written, can any of this be done better?


texts: Program for finding longest run of zeros from a list of 100 random integers which are either 0 or 1

texts:
I have written an answer to this question on Stack Overflow. To make it easier for you, I have copy-pasted the main question below.

  Write a program that generates 100 random integers that are either 0
  or 1.

  Then find the:

  longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in [1,0,1,1,0,0,0,0,1,0,0] is
  4.

Here is my answer to this:

import random

l = []

def my_list():
    for j in range(0,100):
        x = random.randint(0,1)
        l.append(x)
    print (l)
    return l

def largest_row_of_zeros(l):

    c = 0
    max_count = 0

    for j in l:
        if j == 0:
            c += 1
        else:
            if c > max_count:
                max_count = c
            c = 0
    return max_count

l = my_list()
print(largest_row_of_zeros(l))

NOTE: I have changed zero_count to max_count as it sounds more sensible. It keeps track of the max_count (or the largest number of zeros in a row) seen so far, and if a number is not 0, it resets the value of c (count) to 0 after updating the value of max_count with a new value.

So, I would like to know whether I could make this code shorter and more efficient.

Any help would be highly appreciated.


texts: Re-writing rough JS code with loads of jQuery plugins

texts:
I want to include about 10 jQuery plugins in a project but do so in a better way than just pasting them into a JS file.

I want to capture various device data and other data passed from the server-side (in a HTML meta tag) and I want some of this to decide which jQuery scripts to run - or none in the case of some devices.

I also want to be able to extend jQuery plugins, globally control events, globally control setTimeout() and basically write the code in a much better way to maintain.

I have been learning from various tutorials and would like to gauge my understanding.

I have written the code below form various tutorials and advice and it should be a better way to extend and implement jQuery and feedback would be great. I haven't actually ran the code, I'm just trying to understand how the best way to design this would be.

Am I on the right track for how to structure this?

/* all the original jQuery plugins */
(function ($) {
    $.slider = function () {
        //etc
    };
}(jQuery));

/* jQuery wrappers - one for each jQuery script */
function JquerySlider($) {
    var extensionMethods = {
        showId: (function () {
            return this.element[0].id;
        }())
    };

    $.extend(true, $.slider.prototype, extensionMethods);
}

/* execute all the jQuery scripts */
function InitJquery($) {
    this.slider = new JquerySlider($);
}

/* get various device data */
function Device() {
    // get meta data from HTML
    // holds a value 1-3 for the quality of the device (detected server-side)
    this.quality = Number(document.getElementById('device-quality').content);

    // get viewport width
    this.viewportWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}

/* standard JS */
function InitStandard(jQuery) {
    //get device information
    this.device = new Device();

    // initialise jQuery, if device is capable
    if (this.device.quality === 1) {
        this.jqueryPlugins = new InitJquery(jQuery);
    }
}

/* cross-browser add event function */
if (window.addEventListener) {
    var addEvent = function (ob, type, fn) {
        if (typeof ob != 'undefined') {
            ob.addEventListener(type, fn, false);
        }
    };
} else if (document.attachEvent) {
    var addEvent = function (ob, type, fn) {
        if (typeof ob != 'undefined') {
            var eProp = type + fn;
            ob['e' + eProp] = fn;
            ob[eProp] = function () {
                ob['e' + eProp](window.event);
            };
            ob.attachEvent('on' + type, ob[eProp]);
        }
    };
}

/* initialise standard JS on load and pass in the jQuery object */
(function init(jQuery) {
    var js = new InitStandard(jQuery);
}(jQuery));

addEvent(window, 'load', init);


texts: "import translate" in a way that works with Python 2 and 3

texts:
I'm trying to make my script cross-Python (Python 2 and 3 compatible),
and to solve an import problem I did this:

__init__.py file

import sys

if (sys.version_info[0] < 3):
    from core import translate
else:
    from .core import translate

Is it the good way to do it?


texts: How can i make my Get_Numb_of_Digits_in_a_number() function more accurate?

texts:
Here's my function but it sometimes has unpredicted results with entering different numbers but with the same number of digits getting different results. I figure it has something to do with a computers inaccurate decimal saving tecnique but i would like to know how to make it more accurate.

///////////////////////     Numb_Digits()   ////////////////////////////////////////////////////
        enum{DECIMALS = 10, WHOLE_NUMBS = 20, ALL = 30};
    template<typename T>
unsigned long int Numb_Digits(T numb, int scope)
{
        unsigned long int length= 0;
        unsigned long int whole_numb= (int)numb;
            // gets the number of whole numbers
        for(int mod =0; mod!=whole_numb; length++)
            mod = whole_numb% (int)pow(10, (double)length);
        int numb_of_wholes= length-1; length= 0; bool all = false;
        double test = 0, test2= 0;
    switch(scope){
        case ALL: all = true;       // different order to avoid decimal inaccuracies
                                    // like 2.4 being 2.39999                         // 10 bil (10 zeros)
        case DECIMALS:                      numb*=10000000000;      numb-=whole_numb*10000000000;
             for(; numb != 0; length++)
                numb-=((int)(numb/pow((double)10, (double)(9-length))))* pow((double)10, (double)(9-length));
             if(all != true) break;

        case WHOLE_NUMBS: length += numb_of_wholes;
             if(all != true) break;

        default: break;}
                                            return length;
};


texts:
This is part of a Particle Swarm Optimization algorithm, a snippet of a Particle class implementation.

/**
 * Particle class constructor
 * @param p - the position of the particle
 * @param v - the velocity of the particle
 */
Particle::Particle(std::array<double, 30> p, std::array<double, 30> v) {
    bestFitness = fitness = rastriginEvaluation(p);
    bestPosition = position = p;
    velocity = v;
}

// setter methods
void Particle::setFitness(double f) { fitness = f; }
void Particle::setBestFitness(double f) { bestFitness = f; }
void Particle::setPosition(std::array<double, 30> p) { position = p; }
void Particle::setBestPosition(std::array<double, 30> p) { bestPosition = p; }
void Particle::setVelocity(std::array<double, 30> v) { velocity = v; }

Notice the constructor directly accesses member attributes yet I have setter methods. Should I be using the setter methods to initialize attributes? Either is fine, I wonder what is more proper.

For example, instead of:

bestFitness = fitness = rastriginEvaluation(p);
bestPosition = position = p;
velocity = v;

I could do:

setFitness(rastriginEvaluation(p));
setBestFitness(rastriginEvaluation(p));
setPosition(p);
setBestPosition(p);
setVelocity(v);

For this example, rastriginEvaluation() is called twice, when the original code only calls it once. It is therefore slower but what is better practice?

I could also wonder about getter methods in the mix:

setFitness(rastriginEvaluation(p));
setBestFitness(getFitness());
setPosition(p);
setBestPosition(getPosition();
setVelocity(v);

If it makes a difference, all attributes are private.


texts: Canonical Implementation of Move Semantics

texts:
I am trying to compose an illustrative example which shows how to implement move semantics on an object that will be stored in a vector.

Please consider the following code, which is my illustrative example so far. It is designed to be a canonical, pedantically correct implementation of an object that implements move semantics, does not implement copy semantics, and can be stored in a vector<> (Where T is Moveable, below). How did I do?

#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <memory>
#include <iterator>
using namespace std;

class Moveable
{
public:
    string foo_;
    string bar_;

    Moveable(Moveable&& rhs) : foo_(std::move(rhs.foo_)), bar_(std::move(rhs.bar_)) {}  // move construction
    Moveable(const string& foo) : foo_(foo) {};             // convert construction
    Moveable& operator=(Moveable&& rhs)     // move assignment
    {
        foo_ = std::move(rhs.foo_);
        bar_ = std::move(rhs.bar_);
        return * this;
    }
private:
    Moveable(const Moveable&);              // not defined, not copy-constructible
    Moveable& operator=(const Moveable&);   // not defined, not copy-assignable
    Moveable();                             // not defined, not default constructible
};

Moveable generate_it()
{
    static string foo ;
    if( foo.empty() || foo[0] == 'z' )
        foo.insert(0, 1, 'a');
    else
        foo[0]++;
    return foo;
}

int main()
{
    typedef vector<Moveable> Moveables;
    Moveables v;
    generate_n(back_inserter(v), 1024, &generate_it);
    cout << v.size() << endl;
    string target = "zzz";
    auto that = find_if(v.begin(), v.end(), [target](const Moveables::value_type& it) -> bool
    {
        return it.foo_ == target;
    });

    if( that != v.end() )
        v.erase(that);

    sort(v.begin(), v.end(), [](const Moveables::value_type& lhs, const Moveables::value_type& rhs) -> bool
    {
        return lhs.foo_ > rhs.foo_;
    });
    cout << v.size() << endl;
}


texts:
My code looks like "spaghetti code". I have yet to use OOP in PHP but I am really interested in how a good programmer would handle this many if statements. It looks like a mess.

<?php
    session_start();
    include './functions.php';

    if(empty($_FILES['browseMovie']) || empty($_FILES['browseThumbnail']) || empty($_GET['title']) || empty($_GET['description']))
    {
        die('Please insert all fields.');
    }

    $filePartsMovie = pathinfo($_FILES['browseMovie']['name']);
    $filePartsThumbnail = pathinfo($_FILES['browseThumbnail']['name']);

    if($filePartsMovie['extension'] !== "mp4")
    {
        die('Video has to be a .mp4 file.');
    }

    if($filePartsThumbnail['extension'] !== "jpg" && $filePartsThumbnail['extension'] !== "png")
    {
        die('Thumbnail has to be in jpg/jpeg or png format.');
    }

    if($_FILES['browseMovie']['size'] + $_FILES['browseThumbnail']['size'] > 1600600000)
    {
        die('filesize of video and thumbnail = higher 1.5 GB.');
    }

    $id = $_SESSION["id"];
    $name = $_SESSION["username"];
    $folderName = generateUniqueFolder();
    $title = mysql_real_escape_string($_GET['title']);
    $description = mysql_real_escape_string($_GET['description']);

    // the original file name will be stored in the database as well
    $thumbFileName = basename($_FILES['browseThumbnail']['name']);
    $vidFileName = basename($_FILES['browseMovie']['name']);

    $userDir = "../users/$name/";
    $videoDir = $userDir . "videos/" . $folderName . "/";

    $uploadMovieDir =  $videoDir . $vidFileName;
    $uploadThumbnailDir = $videoDir . $thumbFileName;

    if(!isLoggedIn() || !is_dir($userDir))
    {
        die('User does not have own folder. Please contact the administrator.');
    }

    if(!mkdir($videoDir))
    {
        die('Could not create unique video folder.');
    }

    if(!move_uploaded_file($_FILES['browseMovie']['tmp_name'], $uploadMovieDir))
    {
        rmdir($videoDir);
        die('Could not upload the video correctly.');
    }

    if(!move_uploaded_file($_FILES['browseThumbnail']['tmp_name'], $uploadThumbnailDir))
    {
        removeTreeDir($videoDir);
        die('Could not upload the thumbnail correctly.');
    }

    $con = connectDb();
    $videoQuery = "INSERT INTO video(userId, title, description, foldername, vidFileName, thumbFileName) VALUES ($id,'$title','$description','$folderName', '$vidFileName', '$thumbFileName')";

    if(!mysql_query($videoQuery))
    {
        removeTreeDir($videoDir);
        die('Could not add the video to the database.');
    }

    mysql_close($con);

    echo "true";
?>

Somewhere in the middle of my code I also need a bunch of variables. How would one clean that up? Create an object and aggregate them together?


texts: Implementation of Observer Pattern in C++14

texts:
I have written a small class for implementing the observer pattern in C++(14). I would welcome any comments, corrections criticisms and suggestions.

Observable.h:

#include <functional>
#include <vector>

class Observable
{
public:
    using Callback = std::function<void(void)>;

    template<typename O,typename F>
    void AddObserver(O self, F f)
    {
        obs.push_back(Callback([self,f](){(self->*f)();}));
    }

    void NotifyObservers(){for(auto f: obs){f();}}

private:
    std::vector<Callback> obs{};
};

Sample Code

main.cpp

#include <iostream>

#include "Observable.h"

class A : public Observable
{
    private:
        int a;
        std::string s;
};

class B : public Observable
{
public:
    void EventHappened()
    {
        std::cout << "B has observed an event\n";
    }
};

void bar()
{
    std::cout << "This will not work";
}

class C
{
public:
    explicit C(A& a,B& b) : m_a(a), m_b(b)
    {
        a.AddObserver(this,&C::ReactToEventFromA);
        b.AddObserver(this,&C::ReactToEventFromB);

        //a.AddObserver(this,bar); //This will Fail.
        //b.AddObserver(this,&B::EventHappened); //This will Fail.
    }

    void ReactToEventFromA()
    {
        std::cout << "C has observed the event from A\n";
    }

    void ReactToEventFromB()
    {
        std::cout << "C has observed the event from B\n";
    }

private:
        A& m_a;
        B& m_b;
};

int main()
{
    A a;
    B b;
    C c(a,b);

    a.AddObserver(&b,&B::EventHappened);

    a.NotifyObservers();
    b.NotifyObservers();
}

The basic idea is that, to preserve simplicity, when you want a class to be able to notify observers, you just inherit publicly from Observable. And you use the AddObserver method to register any member function of any object to observe the class.

This is just a simple quick mock up, therefore the signature of the callback has been hardcoded to void(void). It shouldn't be too difficult to add the ability to register more complex functions. But this is it for now.


texts: Do you like this kind of helper, which creates short lived helper objects through a delegate?

texts:
Just curious if this is a reasonable idea.  I wouldn't do it all the time.  The example I'm in now is that of the data context and repository that uses it.

I kind of like this because, compared to calling new in AssignButtonClicked, it gives my code the same quality of feeling independent of resource allocation as when using constructor injection (which I can't do for short lived resources).

void AssignButtonClicked(object sender, EventArgs e)
{
    WithPaymentBatchRepository((context, repository) =>
    {
        foreach (var itemIDs in this.SelectedItemIdsAsInts)
        {
            repository.SetPaymentBatchId(itemIDs, this.SelectedPaymentBatchId);
        }

        context.SaveChanges();
    });

    Refill();
}

static void WithPaymentBatchRepository(Action<EomTool.Domain.Entities.EomEntities, EomTool.Domain.Concrete.PaymentBatchRepository> action)
{
    using (var context = new EomTool.Domain.Entities.EomEntities(EomAppCommon.EomAppSettings.ConnStr, false))
    {
        var repository = new EomTool.Domain.Concrete.PaymentBatchRepository(context);
        action(context, repository);
    }
}


texts:
This is a generalized A* pathfinder in Go. I am new to the language and am eager for advice about best practices.

In particular, I am not sure if the type assertion I make in Heuristic is the correct way to bind the implementation to the interface.

I have stolen the PriorityQueue type from the package documentation for container/heap.

Implementation

package pathing

import (
    "container/heap"
)

type Node interface {
    Neighbors() []Edge
    Heuristic(goal Node) float64
    Success(goal Node) bool
}

type Action string

type Edge struct {
    dest   Node
    action Action
}

func AStar(start Node, goal Node) []Action {
    seen := make(map[Node]bool)
    openHeap := make(PriorityQueue, 0)
    heap.Init(&openHeap)
    cameFrom := make(map[Node]Edge)
    gScore := make(map[Node]float64)
    fScore := make(map[Node]float64)
    gScore[start] = 0
    fScore[start] = gScore[start] + start.Heuristic(goal)
    heap.Push(&openHeap, &Item{node: start, priority: fScore[start]})
    seen[start] = true
    for {
        node := heap.Pop(&openHeap).(*Item).node
        if node.Success(goal) {
            return reconstructPath(cameFrom, node)
        }
        for _, edge := range node.Neighbors() {
            adj := edge.dest
            action := edge.action
            if seen[adj] {
                continue
            }
            seen[adj] = true
            // reverse the edge for reconstruction
            cameFrom[adj] = Edge{dest: node, action: action}
            // adjacency cost is based on a constant step
            gScore[adj] = gScore[node] + 1
            hScore := adj.Heuristic(goal)
            fScore[adj] = gScore[adj] + hScore
            heap.Push(&openHeap, &Item{node: adj, priority: fScore[adj]})
        }
    }
}

func reconstructPath(cameFrom map[Node]Edge, node Node) []Action {
    if edge, ok := cameFrom[node]; ok {
        return append(reconstructPath(cameFrom, edge.dest), edge.action)
    }
    return make([]Action, 0)
}

Test

package pathing

import (
    "math"
    "testing"
)

type GridNode struct {
    x int8
    y int8
}

const (
    UP    Action = "up"
    DOWN  Action = "down"
    LEFT  Action = "left"
    RIGHT Action = "right"
)

// orthogonal movement
func (node GridNode) Neighbors() []Edge {
    return []Edge{
        Edge{
            dest:   GridNode{node.x + 1, node.y},
            action: "right",
        },
        Edge{
            dest:   GridNode{node.x - 1, node.y},
            action: "left",
        },
        Edge{
            dest:   GridNode{node.x, node.y + 1},
            action: "up",
        },
        Edge{
            dest:   GridNode{node.x, node.y - 1},
            action: "down",
        }}
}

// euclidean norm
func (node GridNode) Heuristic(goal Node) float64 {
    gridGoal := goal.(GridNode)
    return math.Sqrt(math.Pow(float64(gridGoal.x)-float64(node.x), 2) +
        math.Pow(float64(gridGoal.y)-float64(node.y), 2))
}

func (node GridNode) Success(goal Node) bool {
    return node == goal
}

func TestAStar(t *testing.T) {
    start := GridNode{x: 0, y: 0}
    goal := GridNode{x: 4, y: 4}
    path := AStar(start, goal)
    expectedLength := 8
    if len(path) != expectedLength {
        t.Errorf(
            "Expected length %d, was length %d.",
            expectedLength,
            len(path))
    }
}


texts: Consistent implementation of PHP class constants (arrays not allowed)

texts:
I'm currently writing a class:

final class MyTestClass {
  const URL = 'http://www.example.org';
  private static $MY_ARRAY = array('...');

  // since this is not allowed
  // const MY_ARRAY = array('...');
}

So my question is whether I should make URL a private static variable, too?
These values are constant and are only used in the class itself.


texts:
Given the code below, I'm curious to know if you'd have better naming suggestions for types:

VegetablePresentersFactory
VegetablePresenterFactory

It bothers me a bit that their names only differ by a single character ('s'), and that this character is located in the middle of the name.

class VegetablesApp {
    private final VegetablePresentersFactory vegetablePresentersFactory; // gets injected

    public void displayVegetablePresenters(AllVegetables all) {
        List<VegetablePresenter> presenters = vegatablePresentersFactory.create(all);

        displayPresenters(presenters);
    }
}

class VegetablePresentersFactory {
    private final VegetablePresenterFactory vegetablePresenterFactory;

    public List<VegetablePresenter> create(AllVegetables all) {
        List<VegetablePresenter> presenters = new ArrayList<>();

        list.add(vegetablePresenterFactory.create(all.getTomato()));
        list.add(vegetablePresenterFactory.create(all.getLettuce()));
        list.add(vegetablePresenterFactory.create(all.getBacon()));

        return presenters;
    }
}

interface VegetablePresenterFactory {
    VegetablePresenter create(Vegetable vegetable);
}


texts:
String Calculator

  Create a simple String calculator with a method int Add(string numbers).

  The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0).
  For example "" or "1" or "1,2".
  Start with the simplest test case of an empty string and move to 1 and two numbers
  Remember to solve things as simply as possible so that you force yourself to write tests you did not think about.
  Remember to refactor after each passing test.

  Allow the Add method to handle an unknown amount of numbers.
  Allow the Add method to handle new lines between numbers (instead of commas).

  The following input is ok: "1\n2,3" (will equal 6).
  The following input is NOT ok: "1,\n" (not need to prove it - just clarifying).

  Support different delimiters

  to change a delimiter, the beginning of the string will contain a separate line that looks like this: "//[delimiter]\n[numbers…]".
  For example, "//;\n1;2" should return three where the default delimiter is ';'.
  The first line is optional. All existing scenarios should still be supported.

  Calling Add with a negative number will throw an exception "negatives not allowed" - and the negative that was passed. If there are multiple negatives, show all of them in the exception message.

import re

def string_calculator(string):
    """
    Sums numbers in a string separated by delimiters.

    >>> string_calculator("")
    0
    >>> string_calculator("42")
    42
    >>> string_calculator("473,12")
    485
    >>> string_calculator("1\\n2,3")
    6
    >>> string_calculator("//;\\n1;2")
    3
    >>> string_calculator("-42, 2")
    Traceback (most recent call last):
    ...
    ValueError: negatives not allowed ['-42']
    >>> string_calculator("-42,31,-312")
    Traceback (most recent call last):
    ...
    ValueError: negatives not allowed ['-42', '-312']
    """
    if re.match('-[0-9]+', string):
        raise ValueError("negatives not allowed {}".format(
            re.findall('-[0-9]+', string)))
    separators = ',', '\\n'
    if "//" in string:
        sep_info = re.findall('//.+\n', string)[0]
        separators = sep_info.replace('//','').replace('\\n','')
        string = string.replace(sep_info, '')
    if not string:
        return 0
    if not any(separator in string for separator in separators):
        return int(string)
    return sum(int(number) for number in re.split('|'.join(separators), string))


texts: Personal questionnaire using JavaScript prompts

texts:
This is just playing around and practicing javascript. I am learning JavaScript from Codecademy and I practice coding everyday so I can learn much as possible. I have a lot of if statements, prompt boxes, some alert boxes. I just got finished learning about functions and returns. I just don't know how to use the return in a browser for like document.write or even an alert box.

function prompter() {
    var toc = prompt("What do you prefer? Tea or Coffee");
    if ((toc == "tea") || (toc == "Tea")) {

    } else if ((toc == "coffee") || (toc == "Coffee")) {

    }
    var foc = prompt("What do you prefer? Facebook or MySpace");
    if ((foc == "facebook") || (foc == "Facebook")) {

    } else if ((foc == "myspace") || (foc == "Myspace")) {

    }
    document.write("
So you like " + toc + " and " + foc + " that is awesome.
");
}

function pickAColour() {
    var fun = prompt("What is your favorite colour? , mine is red.");
    document.write("
You like the colour " + fun + " that is a nice colour
");
}

function pickANumber() {
    alert("Lets do some math, do you like Math?");
    var pan = prompt("Please pick a number");
    var nap = prompt("Please pick another number");
    var symbol = prompt("Please pick one of the following symbols +  -  *  /");
    pan = parseInt(pan); //The parseInt() function parses a string and returns an integer.
    nap = parseInt(nap); //The parseInt() function parses a string and returns an integer.
    if (symbol == "+") {
        alert("You picked the Add symbol");
        alert("Lets add both these numbers together. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan + nap) + "");
    }
    if (symbol == "-") {
        alert("You picked the Minus symbol");
        alert("Lets Minus both of these numbers. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan - nap) + "");
    }
    if (symbol == "*") {
        alert("You picked the Multiply symbol");
        alert("Lets Multiply both these numbers. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan * nap) + "");
    }
    if (symbol == "/") {
        alert("You picked the Divide symbol");
        alert("Lets Divide both these numbers. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan / nap) + "");
    }
}

function run() {
    var name = prompt("What is your name?");
    document.write("
Welcome to this special JavaScript page " + name + "
");
    prompter();
    pickAColour();
    pickANumber();
    document.write("Thank You for visting this page");
}

run();


texts: Forcing type-safe IDs for use with Collections and Maps

texts:
Introduction

I have a hierarchically nested tree class (like SampleFolder, s.b.) that I want to serialize.

The problem arises with the collection of sub items like this one:

List<SampleFolder> subFolders;

I do not want to load the entire tree but only one folder at a time, when I deserialize!
So instead of creating a list of the actual objects I need to use IDs. Naturally I am using a primitive based data type for reduced overhead:

List<Double> subFolders;

All good with serialization here. But in a more complex project handling all those Double-IDs, esp. within maps starts to become very confusing during development. As the project increases in complexity it happens that I would hand the wrong ID to a collection.

Map<Double, List<Double>> myAssociations; // what? which id goes where?

So to battle this issue of lost-type safety I created an interface Item and inner class Id (s.b.). This is the resulting usage (more in-depth example see SampleFolder, below):

Map<Id<Car>, List<Id<Wheel>>> myAssociations; // a lot more readable, isn't it?

Question

I couldn't find a best-practice for this issue, so if there is a better way to solve this "type-safety" issue please let me know.
Even though this seems to work, I am wondering if this is good code in respect to the use of generics and if the implementation of hashCode() and equals() is correct.
I am open for optimization suggestions and other critics.

code to review: Item with Id

interface Item {

    double getId();

    class Id<T extends Item> implements Serializable {

        private double id;

        public Id(T item) {
            this.id = item.getId();
        }

        public Id(double id) {
            this.id = id;
        }

        public double asDouble() {
            return id;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }

            if (!(obj instanceof Id)) {
                return false;
            }

            Id<?> cast = (Id<?>) obj;

            return id == cast.id;
        }

        @Override
        public int hashCode() {
            return Double.valueOf(id).hashCode();
        }

        public static <E extends Item> Id<E> from(double id) {
            return new Id<E>(id);
        }

        public static <E extends Item> Id<E> from(E enumItem) {
            return new Id<E>(enumItem);
        }

        @Override
        public String toString() {
            return String.valueOf(id);
        }
    }
}

Sample usage (class not part of the actual project; for illustration purposes only):

public class SampleFolder implements Item, Serializable {

    private final double id;
    private List<Id<SampleFolder>> subFolders;
    private List<Id<MoreItem>> moreItems;
    private List<Id<EvenMoreItem>> evenMoreItems;

    public SampleFolder() {
        id = new Date().getTime();
        subFolders = new ArrayList<>();
    }

    public SampleFolder(double id, List<Id<SampleFolder>> subFolders) {
        this.id = id;
        this.subFolders = subFolders;
    }

    @Override
    public double getId() {
        return id;
    }

    public List<Id<SampleFolder>> getSubFolders() {
        return subFolders;
    }

    public void setSubFolders(List<Id<SampleFolder>> subFolders) {
        this.subFolders = subFolders;
    }
}


texts: Constraint Programming: Map color problem

texts:
I've written some python code to solve the map coloring problem. In my code, I represent the problem using Territory and MapColor objects:

class Territory:

    def __init__(self, name, neighbors, color = None):

        self.name      = name
        self.neighbors = neighbors
        self.color     = color

    def __str__(self):
        return str((self.name, self.neighbors, self.color))

class MapColor:

    def __init__(self, graph, colors):

        self.map     = graph
        self.colors  = colors
        self.vars    = list(self.map.keys())
        self.domains = { var: set(self.colors) for var in self.vars }

Here, MapColor.map represents a {str: Territory} mapping and MapColor.vars, the string keys of the the dictionary (my solve function visits the territories in the dictionary iteratively; once we've exhausted this list, we have know the problem has been solved). Here's an example how this problem can be instantiated:

WA  = 'western australia'
NT  = 'northwest territories'
SA  = 'southern australia'
Q   = 'queensland'
NSW = 'new south wales'
V   = 'victoria'
T   = 'tasmania'

colors    = {'r', 'g', 'b'}

australia = { T:   Territory(T,   [V]                 ),
              WA:  Territory(WA,  [NT, SA]            ),
              NT:  Territory(NT,  [WA, Q, SA]         ),
              SA:  Territory(SA,  [WA, NT, Q, NSW, V] ),
              Q:   Territory(Q,   [NT, SA, NSW]       ),
              NSW: Territory(NSW, [Q, SA, V]          ),
              V:   Territory(V,   [SA, NSW, T]        ) }

problem = MapColor(australia, colors)

Notice that MapColor.domains is used to keep track of the possible colors a Territory can take. My solve function in fact adds some optimization to the standard backtracking method by reducing the domains of neighboring territories. In this function, the variable i is used to iterate through the keys of MapColor.map.

As I write in the comments, this code adapts the approach typically used to solve puzzles: the idea is to make a move and then continue solving the rest of the puzzle, moving to the next open spot on the board. Since we can't iterate over a "board" with explicit indices, I iterate over the keys of MapColor.map.

def solve(self, i):

    if i == len(self.vars):
        return True

    # discussion on why we keep track of old domain is in comments
    old = {var: set(self.domains[var]) for var in self.vars}
    var = self.vars[i]
    print 'domain for '  + var + ': ' + str(self.domains[var])
    if self.map[var].color != None:
        return self.solve(i + 1)

    for color in self.domains[var]:

        if self.is_valid(var, color):

            self.set_map(var, color)
            self.remove_from_domains(var, color)

            if self.solve(i + 1):
                return True

            self.set_map(var, None)
            self.domains = old

    return False

My question: How can I use a heap (python has heapq) to choose to visit the Territory with the smallest domain next? Should I pass the heap along with each recursive call?

Or should I try to make this method iterative? Would that require using both a stack and a heap? Advice on how to do this would be much appreciated!

For reference, here are the other functions used in my code:

def is_valid(self, var, color):
    territory = self.map[var]

    for neighbor in territory.neighbors:
        if color == self.map[neighbor].color:
            return False

    return True

def set_map(self, key, color):
    self.map[key].color = color

def remove_from_domains(self, key, color):
    territory = self.map[key]

    for var in territory.neighbors:
        if self.map[var].color != None:
            continue
        if color in self.domains[var]:
            self.domains[var].remove(color)


texts:
I've written a module for repeating blocks of code, generally to cover issues related to eventual consistency and testing screen elements which may take some time to fully load. It looks like this:

class Repeater
  def initialize(&block)
    @repeat_block = block
  end

  def repeat(times: 25, delay: 0.2)
    result = nil
    times.times do
      result = @repeat_block.call
      break if @until_block.present? && @until_block.call
      sleep(delay)
    end
    result
  end

  def until(&block)
    @until_block = block
    self
  end
end

The Repeater takes two blocks of code, one to be run and the second to check for an exit criteria. Optionally the number of repeats and delays can be overwritten after the .repeat method.

This is implemented in many places throughout the codebase, an example of such is:

  result = false
  Repeater.new do
    result = event_present_in_database
  end.until do
    result
  end.repeat(times: 10, delay: 0.1)
  result

In this case the event_present_in_database method is being repeated called until it returns true instead of false, which indicates that the event has been created as expected, or else times out indicating there's an issue.

This certainly works for what I want it to do, however it doesn't seem very neat and I'm sure it could be tidied up. I know Ruby has all sorts of tricks that I've yet to come across, is there a way to leverage these to make this nicer to use/easier to read.