texts:
This is a python implementation of the Alternating Direction Method of Multipliers - a method of constrained optimisation that is used widely in statistics (http://stanford.edu/~boyd/admm.html).

This is simplified version, specifically for the LASSO:

Given a sparse vector $$x \in R^n$$and matrix $$A \in R^{m \times n}$$ and noisy measurements $$y = Ax + e$$where $$e$$ is additive Gaussian white noise we can solve the following minimisation problem

$$
\hat{x} = \min_x ||y-Ax||_2^2 + \lambda||x||_1
$$

to recover an estimate of $$x$$

The algorithm proceeds iteratively by calculating

$$ x^{k+1} = (A^TA + \rho I )^{-1}(A^Ty + \rho (z - u))$$
$$ z^{k+1} = \mathrm{sign}(\hat{x})\mathrm{max}\left(0, |x| - \frac{\lambda}{\rho}\right) $$

until some convergence criteria is met.

The implementation of the algorithm is below:

import numpy as np
import matplotlib.pyplot as plt
from math import sqrt, log

def Sthresh(x, gamma):
    return np.sign(x)*np.maximum(0, np.absolute(x)-gamma/2.0)

def ADMM(A, y):

    m, n = A.shape
    w, v = np.linalg.eig(A.T.dot(A))
    MAX_ITER = 10000

    "Function to caluculate min 1/2(y - Ax) + l||x||"
    "via alternating direction methods"
    xhat = np.zeros([n, 1])
    zhat = np.zeros([n, 1])
    u = np.zeros([n, 1])

    "Calculate regression co-efficient and stepsize"
    l = sqrt(2*log(n, 10))
    rho = 1/(np.amax(np.absolute(w)))

    "Pre-compute to save some multiplications"
    AtA = A.T.dot(A)
    Aty = A.T.dot(y)
    Q = AtA + rho*np.identity(n)
    Q = np.linalg.inv(Q)

    i = 0

    while(i < MAX_ITER):

        "x minimisation step via posterier OLS"
        xhat = Q.dot(Aty + rho*(zhat - u))

        "z minimisation via soft-thresholding"
        zhat = Sthresh(xhat + u, l/rho)

        "mulitplier update"
        u = u + xhat - zhat

        i = i+1
    return zhat, rho, l

A = np.random.randn(50, 200)

num_non_zeros = 10
positions = np.random.randint(0, 200, num_non_zeros)
amplitudes = 100*np.random.randn(num_non_zeros, 1)
x = np.zeros((200, 1))
x[positions] = amplitudes

y = A.dot(x) + np.random.randn(50, 1)

xhat, rho, l = ADMM(A, y)

plt.plot(x, label='Original')
plt.plot(xhat, label = 'Estimate')

plt.legend(loc = 'upper right')

plt.show()


texts: Returning interfaces in Java without significant casting

texts:
I am writing some code that takes and returns interfaces following the patterns in Effective Java Third Edition. I understand the principle - we want to take in interfaces because in many cases we don't really care about the discrete implementation but rather just the features of this interface. We return interfaces for the same reason. It gives the caller the ability to use the preferred implementation class. Take this extreme contrived example:
import java.util.*;

public class Main
{
    public static List<Integer> op(List<Integer> is) {
        ArrayList<Integer> results = new ArrayList<>();

        for (Integer i : is) {
            results.add(i + 1);
        }

        return results;
    }

    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList(Arrays.asList(1,2,3,4));

        // This line
        ArrayList<Integer> results = (ArrayList<Integer>) op(nums);

        System.out.println(results);
    }
}

So if the caller of op wanted to use a LinkedList they could through simple casting. But to me this feels clunky. In my codebase it is littered with various casts that seem to hinder readability.
Is there a smarter way to do this? Or is this explicit casting the only way to do this properly?


texts:
I'm a SQL learner. In answering the question* For the region with the largest sales total_amt_usd, how many total orders were placed? for the following schema:

(I am unsure of the dialect is but I think it is Postgres)
I came up with the following solution and I wonder if am committing any bad practice (since the official solution is very different).
SELECT
  r.name AS region_name,
  COUNT(*) AS orders_n
FROM ORDERS AS o
INNER JOIN accounts AS a
  ON o.account_id = a.id
INNER JOIN sales_reps as s
  ON a.sales_rep_id = s.id
INNER JOIN region as r
  ON s.region_id = r.id
GROUP BY 1
ORDER BY SUM(o.total_amt_usd) DESC
LIMIT 1;

Official solution:
WITH t1 AS (
   SELECT r.name region_name, SUM(o.total_amt_usd) total_amt
   FROM sales_reps s
   JOIN accounts a
   ON a.sales_rep_id = s.id
   JOIN orders o
   ON o.account_id = a.id
   JOIN region r
   ON r.id = s.region_id
   GROUP BY r.name),
t2 AS (
   SELECT MAX(total_amt)
   FROM t1)
SELECT r.name, COUNT(o.total) total_orders
FROM sales_reps s
JOIN accounts a
ON a.sales_rep_id = s.id
JOIN orders o
ON o.account_id = a.id
JOIN region r
ON r.id = s.region_id
GROUP BY r.name
HAVING SUM(o.total_amt_usd) = (SELECT * FROM t2);

* This is a part of exercise 4.13 of a great online course by Udacity.


texts: Verifying and reducing Latin squares with Python 3

texts:
Similar to my previous post, I'm completing this challenge, which is to verify whether an n × n grid is a Latin square. I have also solved the bonus problem, which is to rearrange a valid Latin square so that its first row and first column are in order.

It is intended that both functions could be used independently. Any feedback is appreciated.

from itertools import chain

def is_latin(n, numbers):
    assert type(numbers) is str
    assert type(n) is str or type(n) is int

    n = int(n)
    list_numbers = [int(m) for m in numbers.split(" ")]

    valid_combination = set(range(1, n+1))
    rows = (set(list_numbers[m:m + n]) for m in range(0, n ** 2, n))
    columns = (set(list_numbers[m::n]) for m in range(n))

    for line in chain(rows, columns):
        if not(line == valid_combination):
            return False
        elif line == valid_combination:
            continue
        else:
            raise Exception("{}{}".format(line, valid_combination))
    return True

def reduce_latin(n, numbers):
    assert type(numbers) is str
    assert type(n) is str or type(n) is int

    n = int(n)
    latin = is_latin(n, numbers)
    if latin:
        return [[((i+m)%n)+1 for i in range(n)] for m in range(n)]
    elif not latin:
        return None
    else:
        raise Exception("{}{}".format(latin, numbers))

if __name__ == "__main__":
    print(reduce_latin("5", "1 2 3 4 5 5 1 2 3 4 4 5 1 2 3 3 4 5 1 2 2 3 4 5 1"))


texts: Instantiating a run-time implementation of an interface

texts:
Below is my code that was written for the following task (based on an SO question):

  Given a Java Collection (of N elements) create an ArrayList, containing N
  collections of the same type with just one element in each.

Here's my code for such method:

public static <E> ArrayList<Collection<E>> SplitCollection (Collection<E> col) throws InstantiationException, IllegalAccessException {
    ArrayList<Collection<E>> listOfCollections = new ArrayList<>();
    for(E el: col) {
        // creating an empty collection of type E
        Collection<E> colEl = col.getClass().newInstance();
        colEl.add(el);
        listOfCollections.add(colEl);
    }
    return listOfCollections;
}

Is there a better way to create a run-time instance of an implementation class for an interface?
Did I overdo anything in light of type erasure?
Other code critique?

When I decided to use no-argument constructor I was aware that the very existence of one is not (and cannot be) enforced by the interface. As it stated in the docs:

  All general-purpose Collection implementation classes (which typically
  implement Collection indirectly through one of its subinterfaces)
  should provide two "standard" constructors: a void (no arguments)
  constructor, which creates an empty collection, and a constructor with
  a single argument of type Collection, which creates a new collection
  with the same elements as its argument. In effect, the latter
  constructor allows the user to copy any collection, producing an
  equivalent collection of the desired implementation type. There is no
  way to enforce this convention (as interfaces cannot contain
  constructors) but all of the general-purpose Collection
  implementations in the Java platform libraries comply.

So I was writing my code for general-purpose Collection implementations.

I never intended this code to be used for production purposes.  I merely wanted to see how far programming to interface together with Generics could get you before you have to use a concrete type and implementation.


texts: Better implementation of checking function

texts:
I have a checking function that checks the correct type for a class Check_Annotation, I was wondering if there is a better way to implement this, my current code right now is:

def _check_list_or_tuple (self, param, annot, value, check_history):
    assert isinstance(value, type(annot)), "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {}".format(value, type_as_str(value), type_as_str(annot))
    if len(annot) == 1 and type(annot[0]) != list and type(annot[0])!= tuple and inspect.isfunction(annot[0]) == False:
        for x in value :
            check_history = ''
            check_history += str(annot[0])
            assert type(x) == annot[0], "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {} \nlist[{}] check: {}".format(x, type_as_str(x), annot[0], annot.index(annot[0])+1, check_history)
    elif type(annot[0]) == list or type(annot[0]) == tuple or inspect.isfunction(annot[0]) == True:
        for i in range(len(value)):
            self.check(param, annot[0], value[i])
    elif len(annot) > 1:
        check_history = ''
        check_history += str(annot[0])
        assert type (value[0]) == annot[0], "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {} \nlist[{}] check: {}".format(value[0], type_as_str(value[0]), annot[0], annot.index(annot[0])+1, check_history)
        check_history = ''
        check_history += str(annot)
        assert len(annot) == len(value), "AssertionError: 'x' failed annotation check(wrong number of elements): value = {} \nannotation had {} elements[{}]".format(value, len(annot), check_history)
        for x in value[1:]:
            check_history = ''
            check_history += str(annot[1])
            assert type(x) == annot[1], "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {} \nlist[{}] check: {}".format(x, type_as_str(x), annot[1], annot.index(annot[1])+1, check_history)

To me it is a bit rough on implementation and repetitive code. Does anyone have an idea of a shorter way to go about doing this?


texts: Bash script to send notifications when low on ram

texts:
Backstory

Recently, we've changed the PCs at my workplace to un Linux Mint.
It works amazing, is blazing fast and the adjustment time was very short.

However, I noticed my PC would freeze completely, sometimes.
I've determined that it is low RAM memory.

My working habits require me to open 10+ tabs (sometimes 100, in 5-8 Google Chrome windows).
This makes it so the swap is stuffed, as well as the RAM (Physical Memory).
Sometimes I have to use a VM running off of my PC, which takes 4GB for itself.

The code

Since old habits are hard to kill and isn't fun, I've decided to write code (which is a lot more fun).

Since Linux Mint doesn't warn about low available RAM, I've scattered around and put together a script to run every minute, and warn me when the memory is running low.

This script can also be executed from the console, displaying a message on it, if needed.
A detection method had to be added, since the output sent to cron is emailed by default.

#!/usr/bin/env bash
# based from https://askubuntu.com/questions/234292/warning-when-available-ram-approaches-zero
LANG=en_US.UTF-8

# gets available and total ram
RAM=$(free -m)
total=$(echo "$RAM"|awk '/^[mM]em\.?:/{print $2}')
available=$(echo "$RAM"|awk '/^[mM]em\.?:/{print $7}')

# warn if less than these levels is free
# warning = 20%
# critical = 10%
WARNING=$(expr $total / 5)
CRITICAL=$(expr $total / 10)

# -h int:transient:1 <-- don't store the notification
# https://unix.stackexchange.com/questions/393397/get-notify-send-to-clear-itself-from-notification-tray/401587
if [ $available -lt $CRITICAL ]; then
    # using -u critical doesn't allow the notification to go away after -t ms have past
    # this causes issues if afk, since the notifications will queue until the -u critical is closed
    notify-send -i error -h int:transient:1 -t 60000 "Low memory!" "$available/$total MB free, critical at $CRITICAL MB"
elif [ $available -lt $WARNING ]; then
    notify-send -h int:transient:1 -t 15000 "Memory is going low" "Available: $available/$total MB, warns at $WARNING MB"
fi

# outputs if not ran by cron
# https://unix.stackexchange.com/questions/46789/check-if-script-is-started-by-cron-rather-than-invoked-manually
if [ -t 0 ]; then
    echo "Available: $available/$total MB, warns at $WARNING MB, critical at $CRITICAL MB"
fi

This script runs in crontab -e, with the following:

# https://unix.stackexchange.com/questions/247860/notify-send-doesnt-work-at-cinnamon
DISPLAY=":0.0"
XAUTHORITY="/home/<username>/.Xauthority"
XDG_RUNTIME_DIR="/run/user/<output from id -u>"

* * * * * /usr/bin/env bash /home/<username>/<script-from-above>.sh

Conclusion

It was really hard to get to this point, with plenty of issues.
Most information was available online, but, making it work was a pain.

I'm not really good with Bash scripting, which probably means that I have some really bad mistakes.
As far as I know, it works as intended, when intended:

Besides that, is there anything I can improve or change?
Any optimization/optimisation I can do?
Any localization/localisation issues that may come?


texts: Non-recursive filter to smoothen saw tooth wave

texts:
I'm currently writing some of my first assembly code for a new project, I am applying a small non-recursive filter algorithm to some saw tooth wave data held in memory, in order to blunt the edges.

Using thumb2 instruction set on a cortex m3.

The algorithm being used is:

y[0] = x[-2]/8 + x[-1]/8 + x[0]/4 + x[1]/8 + x[2]/8

I have spent a long time looking at my code but cannot seem to optimize it any further.
The Assembly code I have written is in a loop for the length of data and I have applied the algorithm as so:

  LDMIA r0,{r5-r9}     ; get the next 5 data values to be filtered
  ADD r5,r5,r9         ; sum x[-2] with x[2]
  ADD r6,r6,r8         ; sum x[-1] with x[1]
  ADD r9,r5,r6         ; sum x[-2]+x[2] with x[-1]+x[1]
  ADD r7,r7,r9,LSR #1  ; sum x[0] with (x[-2]+x[2]+x[-1]+x[1])/2
  MOV r7,r7,LSR #2     ; form (x[0] + (x[-2]+x[-1]+x[1]+x[2])/2)/4
  STR r7,[r3],#4       ; save calculated filtered value
  ADD r0,r0,#4         ; move pointer address forward
  SUBS r4,r4,#1        ; decrement loop counter

Can any one see anywhere I could have better optimized this?

Full Code if needed


texts:
I've written a script to crawl a website recursively until all the links connected to some tutorials are exhausted. It is working smoothly now. There is always room for improvement, though!

import requests
from lxml import html

Page_link="http://www.wiseowl.co.uk/videos/"
visited_links = []

def GrabbingData(url):
    base="http://www.wiseowl.co.uk"
    visited_links.append(url)
    response = requests.get(url)
    tree = html.fromstring(response.text)
    title = tree.xpath('//p[@class="woVideoListDefaultSeriesTitle"]//a/text()')
    link = tree.xpath('//p[@class="woVideoListDefaultSeriesTitle"]//a/@href')
    for i,j in zip(title,link):
        print(i,j)

    pagination=tree.xpath("//div[contains(concat(' ', @class, ' '), ' woPaging ')]//a[@class='woPagingItem' or @class='woPagingNext']/@href")
    for nextp in pagination:
        url1 = str(base + nextp)
        if url1 not in visited_links:
            GrabbingData(url1)

GrabbingData(Page_link)


texts: Generating the pretty bit at the end of a URL

texts:
I'm having a dip into F# and am attempting not to write it like it's C#.

One area that bothers me is using members of System.String. These often need to be chained together, but the only way to do so that I've seen so far is pretty much the same as C#.

For example, I've written a function to generate the pretty bit at the end of a URL (similar to SE):

module String =

    open System.Text.RegularExpressions

    ///Makes a string suitable for use as part of a URL:
    ///Removes syntax, replaces spaces with dashes and lowers case,
    ///then trims first word after 30 chars
    let prettify (x:string) =

        let parsed = Regex.Replace(x.Trim(),"[^0-9a-zA-Z ]","").Replace(" ","-").ToLower()

        match String.length parsed with
            | m when m > 30 ->
                match parsed.IndexOf("-",30-1) with
                    | p when p < 0 -> parsed
                    | p -> parsed.[..p]
            | _ -> parsed

Is there a way to refactor this to be "better F#"?  I'm particularly concerned about how to better handle the methods on System.String and Regex.Replace. (The match part is a little convoluted to handle the edge case of the last word being the one that takes it over 30 chars.)


texts: Selects all elements with a specific data attribute and equalizes their heights

texts:
This script looks for a data attribute applied to elements within a specified wrapper.
It then sets all elements with the attribute to the same height (height of tallest div).
I needed to add a wait time as the script would sometimes get the heights of the divs before the page had fully rendered. Even though the await is set to 0, it works.

There is also an event listener to listen for resize, and adjust the elements as they change size.

I have only been coding JS for a few weeks so I am not great at it.

HTML

Some content

Some content

Some content

Some content

Script

function equalizer(wrap) {
  const equalizeEls = Array.from(wrap.querySelectorAll(`[data-equalize]`));
  const wait = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));

  //get the largest height in the array
  function getLargestNumber(arr) {
    return Math.max(...arr);
  }

  //get an array of heights
  function getTallest(arr) {
    const allheights = arr.map(x => x.clientHeight);
    return getLargestNumber(allheights)
  }

  function equalizeHeights(els) {
    const largest = getTallest(els);
    return els.forEach(el => {
       el.style.minHeight = `${largest}px`
    });
  }

  async function handleResize() {
    await wait(0); //needs a await to ensure page is fully loaded
    equalizeHeights(equalizeEls)
  }

  window.addEventListener('DOMContentLoaded', handleResize);
  window.addEventListener('resize', handleResize);
}

Running the script

new equalizer(document.querySelector(`#div1`))


texts: Ensuring a non-zero radius when constructing a circle

texts:
Is there a little "better" way of writing the line:

raise RuntimeError if not radius.is_a? Numeric or radius == 0

I want to only allow numbers bigger than 0.

class Shape
  def initialize(name)
    @name = name
  end

  def to_s
    "name: #{@name}"
  end
end

class Circle < Shape
  def initialize(name, radius = 0)
    raise RuntimeError if not radius.is_a? Numeric or radius == 0
    super(name)
    @radius = radius
  end

  def area
    @radius ** 2 * Math::PI
  end

  def to_s
    "name: #{@name} - radius: #{@radius}"
  end
end

This is my spec:

describe Circle do
  it "should raise exception if radius is 0 or nil" do
    expect {
      Circle.new("0", 0)
    }.to raise_error(RuntimeError)

    expect {
      Circle.new("nil", nil)
    }.to raise_error(RuntimeError)
  end
end

Maybe this?

raise RuntimeError unless radius.is_a?(Numeric) && radius != 0


texts:
Recursive version. The only interesting function:

        List& List::reverse()
        {
            if (empty())
            {   return *this;
            }
            int val = head();
            //
            // The fun bit.
            // See if you can figure this bit out.
            return pop().reverse().append(val);
        }

The rest:

#include <iostream>
#include <memory>
struct List
{
    struct Node
    {
        int     val;
        std::unique_ptr<Node>   next;
        Node(){}
        Node(int v, Node* oldTail)
            : val(v)
            , next(nullptr)
        {
            oldTail->next.reset(this);
        }
        friend std::ostream& operator<<(std::ostream& s, Node const& data)
        {
            return s << data.val << " ";
        }
    };
    Node    sentinal;
    Node*   tail;
    public:
        List()
            : tail(&sentinal)
        {}
        bool empty() const
        {
            return &sentinal == tail;
        }
        int& head()
        {
            // Pre-Condition not empty
            return sentinal.next->val;
        }
        List& append(int val)
        {
            tail = new Node(val, tail);
            return *this;
        }
        List& pop()
        {
            // Pre-Condition not empty
            sentinal.next.reset(sentinal.next->next.release());
            tail = sentinal.next.get() ? tail : &sentinal;
            return *this;
        }
        List& reverse();
        friend std::ostream& operator<<(std::ostream& s, List const& data)
        {
            for(Node* loop = data.sentinal.next.get(); loop != nullptr; loop=loop->next.get())
            {   s << *loop;
            }
            return s << "\n";
        }

};


texts: Artificial Neural Network Classifier in Matlab

texts:
I am trying to build a neural network classifier. I have created a neural network with 1 hidden layer (25 neurons) and 1 output layer (1 neuron/binary classification).

The dataset I am using has the following dimensions:

size(X_Train): 125973 x 122
size(Y_Train): 125973 x 1
size(X_Test): 22543 x 122
size(Y_test): 22543 x 1

My overall goal is to compare different training functions. But, I would like first to get your feedback about my code and how I improve it.

% Neural Network Binary-classification

clear ; close all; clc

%% =========== Part 1: Loading Data =============

%% Load Training Data
fprintf('Loading Data ...\n');

load('dataset.mat'); % training data stored in arrays X, y
X_training=X_training';
Y_training=Y_training';
X_testing=X_testing';
Y_testing=Y_testing';

%% Create the neural network
% 1, 2: ONE input, TWO layers (one hidden layer and one output layer)
% [1; 1]: both 1st and 2nd layer have a bias node
% [1; 0]: the input is a source for the 1st layer
% [0 0; 1 0]: the 1st layer is a source for the 2nd layer
% [0 1]: the 2nd layer is a source for your output
net = network(1, 2, [1; 1], [1; 0], [0 0; 1 0], [0 1]);
net.inputs{1}.size = 122; % input size
net.layers{1}.size = 25; % hidden layer size
net.layers{2}.size = 1; % output layer size

%% Transfer function in layers
net.layers{1}.transferFcn = 'logsig';
net.layers{2}.transferFcn = 'logsig';

net.layers{1}.initFcn = 'initnw';
net.layers{2}.initFcn = 'initnw';

net=init(net);

%% divide data into training and test
net.divideFcn= 'dividerand';
net.divideParam.trainRatio = 60/100; % 80% training
net.divideParam.valRatio = 20/100; % 20% validation set
net.divideParam.testRatio = 20/100; % 20% validation set

net.performFcn = 'crossentropy';

%% Training functions
net.trainFcn = 'trainscg'; %Scaled conjugate gradient backpropagation

%% Train the neural network
[net,tr] = train(net,X_training,Y_training); % return the network and training record

%% Test the Neural Network on the training set
outputs = net(X_training);
errors = gsubtract(Y_training,outputs);
performance = perform(net,Y_training,outputs);

%% Plots  (%training)
figure, plotperform(tr)
figure, plottrainstate(tr)

%% Test the Neural Network on the testing test
outputs1 = net(X_testing);
errors1 = gsubtract(Y_testing,outputs1);
performance1 = perform(net,Y_testing,outputs1);

figure, plotconfusion(Y_testing,outputs1)
figure, ploterrhist(errors1)

Below if the validation curve.

Confusion Matrix (Training set)

Confusion Matrix (Testing set)

Any remarks?

Edit:

I have used feature scaling or normalization:

net.performParam.normalization = 'standard';

which has improved the overall accuracy:

For more information, I have added the error histogram:


texts:
I would like to improve my preg_replace regex.
This is to clean a features list.

I want allow for the begining of each line:

alphanumeric characters
== and alphanumeric characters
-- alphanumeric characters
++ alphanumeric characters
** alphanumeric characters

my regex:

$features = "
    == Category one
    → feature 1
    ++ feature 2
    -- feature 3
    ==-
    ! feature 4
    % feature 5";

preg_replace('/' .
          '^[^[:alnum:]]{0,}(==-.*)$' . '|' .              // ==-
          '^[^[:alnum:]]{0,}([\+|\-|\*|\=]{2}.*)$' . '|' . // ==
          '^[^[:alnum:]]{0,}(.*)$' .                       // abc
          '/mu', '$1$2$3',
          $features);

Dirty features:

== Category one
→ feature 1
++ feature 2
-- feature 3
==-
! feature 4
% feature 5

Clean:

== Category one
feature 1
++ feature 2
-- feature 3
==-
feature 4
feature 5

It works, but i think there is a better way ...
Thanks


texts: A Summation Function For Boost.MultiArray in C++

texts:
This is a follow-up question for
A Summation Function For Arbitrary Nested Vector Implementation In C++ and A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++. I am trying to implement a recursive_sum function for the Boost Multidimensional Array Library. The purpose of this recursive_sum function is to sum up each element in a input boost::multi_array data.  The recursive structure here is similar to the previous implementation for std::vector and the other type nested iterable. Furthermore, I found that there are several types including boost::multi_array, boost::detail::multi_array::sub_array and boost::detail::multi_array::const_sub_array in Boost.MultiArray library. I am trying to handle these types with multiple overload function as below.
template<class T> requires is_summable<T>
auto recursive_sum(const T& input)
{
    return input;
}

//  Deal with the boost::multi_array case
template<class T, std::size_t Dims> requires is_summable<T>
auto recursive_sum(const boost::detail::multi_array::const_sub_array<T, Dims>& input)
{
    T sum_output{};
    for (typename boost::multi_array<T, Dims>::index i = 0; i < input.shape()[0]; i++)
    {
        sum_output += recursive_sum(input[i]);
    }
    return sum_output;
}

//  Deal with the boost::multi_array case
template<class T, std::size_t Dims> requires is_summable<T>
auto recursive_sum(const boost::detail::multi_array::sub_array<T, Dims>& input)
{
    T sum_output{};
    for (typename boost::multi_array<T, Dims>::index i = 0; i < input.shape()[0]; i++)
    {
        sum_output += recursive_sum(input[i]);
    }
    return sum_output;
}

//  Deal with the boost::multi_array case
template<class T, std::size_t Dims> requires is_summable<T>
auto recursive_sum(boost::multi_array<T, Dims>& input)
{
    T sum_output{};
    for (typename boost::multi_array<T, Dims>::index i = 0; i < input.shape()[0]; i++)
    {
        sum_output += recursive_sum(input[i]);
    }
    return sum_output;
}

The used is_summable concept:
template<typename T>
concept is_summable = requires(T x) { x + x; };

The test for this recursive_sum function:
int main()
{
    // Create a 3D array that is 3 x 4 x 2
    typedef boost::multi_array<double, 3> array_type;
    typedef array_type::index index;
    array_type A(boost::extents[3][4][2]);

    // Assign values to the elements
    int values = 0;
    for (index i = 0; i != 3; ++i)
        for (index j = 0; j != 4; ++j)
            for (index k = 0; k != 2; ++k)
                A[i][j][k] = values++;

    auto recursive_sum_output = recursive_sum(A);
    std::cout << "recursive_sum_output: " << recursive_sum_output;

    return 0;
}

All suggestions are welcome.

Which question it is a follow-up to?
A Summation Function For Arbitrary Nested Vector Implementation In C++ and
A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++

What changes has been made in the code since last question?
The previous question is focused on the common containers in C++ STL, such as std::vector. The main idea in this question is trying to implement another type summation function which can deal with boost::multi_array.

Why a new review is being asked for?
I found that there are three types of array structure in Boost.MultiArray library which are boost::multi_array, boost::detail::multi_array::sub_array and boost::detail::multi_array::const_sub_array. In order to handle these different type classes, there are three overload functions recursive_sum for dealing with each type separately. I am not sure is there any better way to simplify these overload functions. Moreover, if there is any possible improvement for this code, please let me know.


texts: Longest Substring Without Repeating Characters in Scala

texts:
Question is taken from Leetcode and solution works for their test cases. I do see a scope of improvement and make it more functional (getting rid of vars and mutables data structures). Please suggest improvement to help me.

Problem

Given a string, find the length of the longest substring without repeating characters.

Input: "abcabcbb"
Output: 3

Input: "bbbbb"
Output: 1

Input: "pwwkew"
Output: 3

code

import scala.collection.mutable.HashMap

object Solution extends App{

    def lengthOfLongestSubstring(s: String): Int = {
      if (s.isEmpty) 0
      else {
      val lookupTable = HashMap[Char,Int]()
      var start = 0
      var length = 0
      for ( (c, i) <- s.zipWithIndex) {
        if (!(lookupTable contains c)) {
          lookupTable(c) = i
        } else {
          val newLength = i - start
          if (newLength > length) length = newLength
          start = lookupTable(c) + 1
          lookupTable.retain((k,v) => v >= start)
          lookupTable(c) = i
        }
      }
      Math.max(length, (s.length - start))
    }
  }
    Seq("abcabcbb", "pwwkew", "", "nnnn", "b", "  ", "aab" , "abca" ,"abba") foreach { s =>
      println(s + " = " + lengthOfLongestSubstring(s))
    }
}

Output

abcabcbb = 3
pwwkew = 3
 = 0
nnnn = 1
b = 1
   = 1
aab = 2
abca = 3
abba = 2


texts: Html Templating for a WIP static site generator, written in Javascript

texts:
I wrote this to go in my simple static site generator. it takes any plaintext file (but meant for html) and injects the specified file contents and other data at matching tags. This is my first "big" JavaScript project, and most of my knowledge has come from several-year-old posts on StackExchange, YouTube, and Medium, so I cannot guarantee that I have followed modern conventions.
I have included test code, and It should run as-is however it does require a single index.html file in the same dir to test fileInject().
const fs = require('fs');

var test = `<!-- template:one -->
<!-- template:two -->
<!-- template:three -->
<!-- template:index.html -->
<!-- template:five -->`;

var data = [['one','apple'],['three','orange'],['five','banana']];

// Grab tags from template files. Does not return duplicates.
const getTags = (template) => {
    const regex = /\<\!\-\- template:(?<label>(?:(?!\<\!\-\-).)+) \-\-\>/g;
    var match, matches = [];
    while(match = regex.exec(template)) {
        if(!matches.includes(match)) {
            matches.push([match.groups.label, match[0]]);
        }
    }
    return matches;
}

// Inject data at matching tags. Tag object format: [['key','value'], ...]
// Silent on failure, but mostly because I do not know how to check if template.replace() succeeds or fails.
const dataInject = (template, tags) => {
    for(let tag of tags) {
        const regex = new RegExp(`\<\!\-\- template:${tag[0]} \-\-\>`, 'g');
        template = template.replace(regex, tag[1]);
    }
    return template;
}

// Find and inject file contents at matching tags.
// Logs errors on failure.
const fileInject = (template) => {
    const tags = getTags(template);
    for(let tag of tags) {
        try{
            fs.accessSync(tag[0]);
            const partial = fs.readFileSync(tag[0]).toString();
            template = template.replace(tag[1], partial);
        } catch(e) { console.log(`error injecting file '${tag[0]}'`) }
    }
    return template;
}

// Individual tests
//console.log(dataInject(test, data));
//console.log(fileInject(test));

//combined tests. Both work, however (if combined) dataInject() should be called first as fileInject() will finish quicker encounter fewer failures.
//console.log(dataInject(fileInject(test), data));
console.log(fileInject(dataInject(test, data)));


texts: Pretty-print dollar amounts using custom precision for large amounts

texts:
Given a floating-point number, which is representing a dollar value, I'm aiming to return a rounded, human-readable string. Here are the rules for numbers equal to or greater than 1 million, equal to or greater than 1 but less than 1 million, and, finally, less than 1:

one decimal place for million, two places for billions and three places for trillions
numbers over 999 trillion are displayed in trillions, e.g. 1,000 trillion not 1 quadrillion
if less than 1 million, two decimal places (cents)
if less than 1, then as cents (multiplied by 100)

numbers which don't round up to at least 1 cent count as 0 cents

Also, for numbers greater than 1, there's no display of precision if mantissa is all zeros (e.g. 1.000 trillion becomes 1 trillion and 1.00 becomes 1.)
import math

def convert_float_to_value(number):
    if number == 0.0:
      return "0 cents"
    digits = 1 + math.floor(math.log10(number))
    if digits > 12:
        return f"${round(number / 10**12, 3):,.3f} trillion".replace(".000", "")
    elif digits > 9:
        return f"${round(number / 10**9, 2):,.2f} billion".replace(".00", "")
    elif digits > 6:
        return f"${round(number / 10**6, 1):,.1f} million".replace(".0", "")
    elif digits > 0:
        return f"${round(number, 2):,.2f}".replace(".00","")
    else:
        return f"{round(number * 100):,} cents".replace("1 cents", "1 cent")

I already sense some improvements, like perhaps I should be checking this really is a floating-point value and not an integer, or just turning whatever I get into a float. But what do you think of this approach? There are a number of pretty-printing libraries but these are some very specific rules.


texts:
I've made a Python Flask app and I have some questions about the structure of the main module (equivalent of index.py).
Here is what it looks like:
from flask import Flask, render_template

import database as db
import weather_forecast as wf
import os

app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html',
                       sites=db.create_site_list_sqlite(),
                       api_key=os.environ.get('GOOGLE_MAPS_JS_API_KEY'))

@app.route("/contact")
def contact():
    return render_template('contact.html')

@app.route("/weather_forecast/<climbing_area>/<city_id>/<lat>/<lon>/<weather_site>")
#creates url using climbing area name, city id, lat, lon, and location of weather site
def weather_forecast(climbing_area, city_id, lat, lon, weather_site):

    return render_template('weather_forecast.html',
                       climbing_area=climbing_area,
                       city_id=city_id,
                       daily_forecast=wf.format_daily_forecast(city_id),
                       extended_forecast=wf.format_extended_forecast(city_id),
                       historical_forecast=wf.get_historical_weather(lat, lon),
                       dates=wf.get_date_range(),
                       lat=lat,
                       lon=lon,
                       weather_site=weather_site,
                       sites=db.create_site_list_sqlite(),
                       api_key=os.environ.get('GOOGLE_MAPS_JS_API_KEY'),
                       image_url=wf.image_choice(lat, lon, city_id))

if __name__ == '__main__':
    app.run(debug=True)

I have three pages in my application, home, contact, and a dynamically created weather_forecast url.
Basically, when the home() function runs and renders the home page template, it runs this line: sites=db.create_site_list_sqlite()
The create_site_list_sqlite() function returns a bunch of data from an SQLite database, which is used to populate some a href hyperlinks. When a user clicks on one of those links, it goes to a weather forecast page, created by the def weather_forecast() route. That same data is then used to populate the URL in the proceeding weather forecast page.
My reason for doing this is, it was the best way I could figure out to run the create_site_list_sqlite() function. I could have populated the weather_forecast url by re-running that function but it seemed redundant.
Is this good practice to run the create_site_list_sqlite() function (or any others) as few times as possible?
Also, because I needed several pieces of data from what that function returns (climbing_area, city_id, lat, lon, and weather_site), the url for a weather forecast page is rather long. I personally think its fine but is there some reason to tighten this up if possible, just as an example, here is what one of the weather forecast page URLs looks like:
http://localhost:5000/weather_forecast/Ibex/5538080/38.881/-113.461/Delta

Thank you for any input.


texts:
This code loops through an array called $rootScope.watchlist (uses AngularJS). It gets the current iteration of the loop to access that x iteration through $rootScope.watchlist and get the id index. If that matches the variable titleID, then it will splice (remove) that index only and then stop the foreach to stop unnecessarily continuing.

for (var i = $rootScope.watchlist.length - 1; i >= 0; i--) {
    if($rootScope.watchlist[i]['id'] == titleID) {
        $rootScope.watchlist.splice(i, 1);
        break;
    }
}

Is there a better way of doing such? Possibly using .some()?


texts:
I'm learning Node and Redis and created a semaphore for master/slaves.

var redis = require("redis"),
    _ = require('underscore'),
    async = require('async'),
    client = redis.createClient();

var isMaster = false,
    SEMAPHORE_ADDRESS = 'semaphore';
var lifeCycle = function(next) {
  if(isMaster) {
    client.set([SEMAPHORE_ADDRESS, true, 'EX', 5], function(err, val) {
      console.log('master lifecycle');
      if(err !== null) { throw err; }
      else if(val === 'OK') {
        console.log('everything ok; I will send slaves some tasks');
      } else {
        assert.fail();
      }
      next();
    });
  } else {
    console.log('slave lifecycle');
    client.set([SEMAPHORE_ADDRESS, true, 'NX', 'EX', 5], function(err, val) {
      if(err !== null) { throw err; }
      if(val === null) {
        console.log('slaves takes some tasks');
      } else if(val === 'OK') {
        console.log('I`m master');
        isMaster = true;
      }
      next();
    });
  }
};
async.forever(
  function(next) {
    setTimeout(
      lifeCycle.bind(null, next),
      1000
    );
  }
);


texts:
From HackerRank's 10 Days of JavaScript, Day2: Loops:

  Complete the vowelsAndConsonants function in the editor below. It has one parameter, a string,s, consisting of lowercase English alphabetic letters (i.e., a through z). The function must do the following:

  First, print each vowel in s on a new line. The English vowels are a, e, i, o, and u, and each vowel must be printed in the same order as it appeared in s.
  Second, print each consonant (i.e., non-vowel) in s on a new line in the same order as it appeared in s.

The following code is in JavaScript. The code runs perfectly fine, just finding a way to make it better.

function vowelsAndConsonants(s) {
    let sp = s.split("");
    let arr1 =[];
    let arr2 =[];
    for(let i=0;i<sp.length;i++)
    {
        if(sp[i]=='a'||sp[i]=='e'||sp[i]=='i'||sp[i]=='o'||sp[i]=='u'){
            arr1.push(sp[i]);
        }else{
            arr2.push(sp[i]);
        }
    }
    for(let i = 0;i<arr1.length;i++){
        console.log(arr1[i]);
    }
    for(let i = 0;i<arr2.length;i++){
        console.log(arr2[i]);
    }
}


texts: animate button presses in a sequence (tkinter)

texts:
I am attempting to animate the series of button presses in the simon game I am creating with tkinter. The animate method is called for each button that needs to be pressed in the series. It currently presses all of the buttons at the same time rather than in a series as it is meant to.

from tkinter import *
from random import choice
root = Tk()
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
frame = Frame(root)
frame.grid(row=0, column=0, sticky=N+E+S+W)

def animate(btn):
    btn.config(relief=SUNKEN, state=ACTIVE)
    btn.after(200, lambda: btn.config(relief=RAISED, state=NORMAL))

class Game(object):
    def __init__(self):
        self.colors = ["green", "red", "yellow", "blue"]
        self.i = 0
        self.round = 1
        self.moves = []
        self.cpu_moves = []

        self.btns = []
        for row in range(2):
            Grid.rowconfigure(frame, row, weight=1)
            for col in range(2):
                Grid.columnconfigure(frame, col, weight=1)
                btn = Button(frame, width=150, height=150, bg=self.colors[0],
                             command=lambda b=self.i: self.user_select(b))
                btn.grid(row=row, column=col)
                self.btns.append(btn)
                self.colors.remove(self.colors[0])
                self.i += 1

    def user_select(self, btn):
        self.moves.append(btn)
        print(self.moves)
        print(self.cpu_moves)
        if self.moves == self.cpu_moves:
            self.clear_user_moves()
            self.round += 1
            self.cpu_move()
        elif len(self.moves) == len(self.cpu_moves) and self.moves != self.cpu_moves:
            self.clear_cpu_moves()

    def clear_user_moves(self):
        self.moves = []

    def clear_cpu_moves(self):
        self.cpu_moves = []

    def cpu_move(self):
        nums = [0, 1, 2, 3]
        self.cpu_moves.append(choice(nums))
        print(self.cpu_moves)
        for i in self.cpu_moves:
            root.after(200, animate(self.btns[i]))

class App(object):
    def __init__(self, master):
        self.master = master
        game = Game()
        game.cpu_move()

root.geometry("300x300")

app = App(root)
root.resizable(width=False, height=False)
root.mainloop()


texts: Calling a button's OnClick method elsewhere - Good Practice?

texts:
I have two buttons on an ASP.NET page that have separate OnClick methods in the code behind. In one of the methods, if a certain condition is met, the entire process of the other method should be executed.

Here is a simplified example of my code, which works as I intend in my actual implementation:

// OnClick="ThisButton_OnClick" for ThisButton
protected void ThisButton_OnClick(object sender, EventArgs e)
{
    // do stuff
    if(condition)
        ThatButton_OnClick(null, null);
    else
        // do stuff
}

// OnClick="ThatButton_OnClick" for ThatButton
protected void ThatButton_OnClick(object sender, EventArgs e)
{
    // do stuff
}

My question is this: is it good practice to do something like this, where you call a method specifically designed for OnClick without clicking that button, or should I be more explicit (perhaps have a separate helper function that is called by ThatButton_OnClick and in the if)?


texts:
I have never use css animations before, so I just want to know, is this the 'best' way to animate a Ticker? I 'best' in this case encompasses efficient and semantic use of html and css.

It's worth noting that I intend to add extra functionality to this, such as manual scrolling back and forth. Is this set up ok for extending with javascript or is something here too temperamental?

Basic functionality is, Tweets scroll from right to left. When you put your mouse on one the scrolling stops and the tweet expands, and the time posted appears.

JSFiddle to see it in action

HTML:

        test

                @Something
                3m

content

CSS:

#controller {
    background-color: blue;
    display: inline-block;
    position: absolute;
    width: 100%;
}
#controller:hover #ticker {
    -webkit-animation-play-state: paused
}
#ticker {
    -webkit-animation: move_eye 6s linear 0s infinite normal;

}
@-webkit-keyframes move_eye {
    from {
        margin-left:110%;
    }
    to {
        margin-left:-50%;
    }
    90% {
    }
}
#text{
    display: inline-block;
}
#tweet {
    box-sizing: border-box;
    background-color: white;
    display: inline-block;
    position: relative;
    border-radius:5px;
    margin: 0px 1px;
    padding: 0px 3px;
}
#tweet:hover {
    font-size: 120%;
}
#tweet:hover #extra_info {
    display: inline-block;
}
#tweet:hover img {
        width: 40px;
        height: 40px;
}
#extra_info {
    display: none;
}

img{
    width: 30px;
    height: 30px;
}


texts:
I've just recently started running some wargames (Natas, OverTheWire) and thought I'd implement some of my scripting experience to solve them instead of doing it manually (though I did that first).

I've got this script:

import requests
from requests.auth import HTTPBasicAuth

def exploit(host, credentials):
    print(host)
    try:

        r = requests.get(host,
                         auth=HTTPBasicAuth(credentials[0],
                                            credentials[1]),
                         headers={'referer': 'http://natas5.natas.labs.overthewire.org/'}
                         )

        print([line for line in r.content.decode('ascii').split('\n') \
               if 'natas5' in line][0])

    except Exception as e:
        print(e)

def main():
    host = 'http://natas4.natas.labs.overthewire.org'
    credentials = ('natas4', 'Z9tkRkWmpt9Qr7XrR5jWRkgOU901swEZ')
    exploit(host, credentials)

if __name__ == '__main__':
    main()

I know it's a really basic script, but I'd really want to know if I'm following the right coding conventions and if there are ways of making a bit better. I've rarely used the requests library, so I'm still fairly new to it.


texts: Regular expression to parse guid and other attributes

texts:
I have this regular expression that extracts guid and couple of other attributes like name, type and version. Please review the regex for any optimizations and improvements.

Strings are always in the pattern of

/publication/guid/type/name;version=1234

regex

(([a-f0-9]+\-)+[a-f0-9]+)\/(.*?)\/(.*?);version=(\d*)

Test records

Extract bold pieces from string.

/publication/d40a4e4c-d6a3-45ae-98b3-924b31d8712a/collection/content1;version=1520623346833

Expected output:

d40a4e4c-d6a3-45ae-98b3-924b31d8712a
collection
content1
1520623346833

/publication/d40a4e4c-d6a3-45ae-98b3-924b31d8712a/article/testContent;version=1520623346891

Expected output

d40a4e4c-d6a3-45ae-98b3-924b31d8712a
article
testContent
1520623346891

Code

Language is F#, but the regex works in C# too.  Furthermore, I would like to use the same regex in Node.js, so I would like the regex to be language agnostic.

let matchEntity (m: Match) =
    { id= m.Groups.[1].Value; eType = m.Groups.[3].Value; name= m.Groups.[4].Value; version = m.Groups.[5].Value}

let regex = new Regex("(([a-f0-9]+\-)+[a-f0-9]+)\/(.*?)\/(.*?);version=(\d*)")
matchEntity regex.Match "/publication/d40a4e4c-d6a3-45ae-98b3-924b31d8712a/collection/content1;version=1520623346833"


texts:
I'm beginning to learn Go. I've decided to write some file utilities to help me with some bigger projects I intend to write. Coming from mainly a Python background, I'm sure there are plenty of stylistic and efficiency improvements to be made. I'm looking for general feedback, as I want to kick bad habits to the curb before they set it. Feedback such as:

Error Reporting
Use of defer in appendContent function
Testing Functions: Are there any libraries to help accomplish this, like how Python has unittest?

I use more comments than I usually would when programming because I'm still learning the language. The Usage: comments help me remember why I'm importing these libraries. Besides the specifically requested feedback, any and all criticism is welcome and appreciated!

Utilities

package main

import (
    "fmt"       // Usage: Printing errors and content of the files
    "io/ioutil" // Usage: Reading and writing files
    "os"        // Usage: Opening files and appending to them
)

func main() {
    testFunctions()
}

func testFunctions() {
    /*
        This method is solely for the purpose of testing the below methods
    */
    writeContent("test.txt", "Test Content")
    fmt.Println(getContent("test.txt"))
    appendContent("test.txt", "Test Content 2")
    fmt.Println(getContent("test.txt"))
}

func getContent(file string) string {
    /*
        Gets the content from the passed `file`
    */
    content, err := ioutil.ReadFile(file)
    if err != nil {
        fmt.Println(err)
        return "[NOT CONTENT]: AN ERROR OCCURED"
    }
    return string(content)
}

func writeContent(file string, content string) {
    /*
        Writes the passed `content`, creating a new file at `file`
    */
    formattedContent := []byte(content)
    err := ioutil.WriteFile(file, formattedContent, 0777)
    if err != nil {
        fmt.Println(err)
    }
}

func appendContent(file string, content string) {
    /*
        Appends the passed `content` to the end of the passed `file`
    */
    fileToAppend, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0600)
    if err != nil {
        panic(err)
    }
    defer fileToAppend.Close()
    _, err = fileToAppend.WriteString(content)
    if err != nil {
        panic(err)
    }
}


texts:
randip.py

I know there are probably better, easier ways to do this.
It was just a bit of a learning exercise for the sake of familiarising myself with Python.

It takes a single argument (positional parameter):
Either a 4 (IPv4) or a 6 (IPv6).

Usage:

./randip.py 4
61.104.170.242

./randip.py 6
4bfc:391d:3ec8:68ef:0ec8:529b:166d:2ece

Code:

#!/usr/bin/env python3

from sys import argv

from random import randint, choice
from string import hexdigits

def random_ip(v):

    if v == 4:
        octets = []
        for x in range(4):
            octets.append(str(randint(0,255)))
        return '.'.join(octets)

    elif v == 6:
        octets = []
        for x in range(8):
            octet = []
            for x in range(4):
                octet.append(str(choice(hexdigits.lower())))
            octets.append(''.join(octet))
        return ':'.join(octets)

    else:
       return

def main():
    print(random_ip(int(argv[1])))

if __name__ == '__main__':
    main()


texts:
This essentially checks if any of these if statements are true, then echos a statement.

Unfortunately, wrapping the error message with a div tag is impossible since I set error to 1 after I would have the div tag show up. I assume I could use a function for this but I don't understand how they work.

Is there a better way to check all these parameters then return a string that I can check if something exists in that string or not to post?

if ($error == '1'){ echo '
';}
if(strlen($display)<4)
{
echo "Display name is too short.
";
$error = '1';
}
if ($email == '')
{
echo "You did not put a valid email adress. We require this to verify your account.
";
$error = '1';
}
if(mysql_num_rows($check_display) != 0)
{
echo "Display name is already in use.
";
$error = '1';
}

if(mysql_num_rows($check_user) != 0)
{
echo "Username is already in use.
";
$error = '1';
}

if(mysql_num_rows($check_mail) != 0)
{
echo "Email is already in use.
";
$error = '1';
}

if ($pass != $pass2)
{
echo 'Passwords do not match.
' ;
$error = '1';
}
if ($error == '1'){ echo '
';}


texts: Getting a list of manufacturers from a database

texts:
I'm new to Zend Framework. Can you help me optimize this function, which gets a list of Manufactures with some conditions from a database?

private function Manufactures(
    $Condition = array(),
    $Order = array('name' => 'ASC'),
    $Strict = TRUE,
    $Limit = NULL)
{
    $Request = $this->_DbTable->select();
    $Clause  = $Strict ? '=' : 'LIKE';
    foreach ($Condition as $index => $value) {
        if (!is_array($value)) {
            $Request->where($this->_DbTable->info('name') . '.' . $index . ' '. $Clause .' ?', $value);
        } else {
            foreach ($value as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $valIndex) {
                        if (isset($valIndex['modifier']) && isset($valIndex['value'])) {
                            $Request->where($this->_DbTable->info('name') . '.' . $key . ' ' . $valIndex['modifier']. ' ?', $valIndex['value']);
                        }
                    }
                }
            }
        }
    }
    foreach ($Order as $index => $value) {
        $Request->order($index . ' ' . $value);
    }
    if($Limit) $Request->limit($Limit);
    $Data = $this->_DbTable->fetchAll($Request)
                           ->toArray();
    return isset($Data) ? $Data : NULL;
}


texts:
Please check my code below. I don't have any problems but I'm not aware how far the code will work, release and kill excel instances..

try
{
    wBook = xCel.Workbooks.Open(excelfilepath);
    xCel.Visible = false;
    this.xCel.DisplayAlerts = false;
    wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1);
    wSheet.Copy(Type.Missing, Type.Missing);
    wSheet = (Excel.Worksheet)wBook.Sheets[1];
    wSheet.SaveAs("1.xls");
}
catch
{
}
finally
{
    if (wBook != null)
    {
        try
        {
            wBook.Close();
        }
        catch
        {
        }
        Thread.Sleep(500);
    }

    if (excelprocid > 0)
    {
        Process xcelp = Process.GetProcessById(excelprocid);
        xcelp.Kill();
    }

    try
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
    catch{}

    Marshal.FinalReleaseComObject(wSheet); wSheet = null;
    Marshal.FinalReleaseComObject(wBook); wBook = null;
}


texts: Apply one random deduction pattern onto different lists with same index in Python

texts:
I am trying to apply certain random deduction pattern to different lists - different in items but having the same numbers of items. I wrote this code - I know it is pretty messy- but it seems it does the work. Please help me to make it better. To explain, better the base list changes each time the random pattern applied to the list. But the indexes that are deducted each time are from the same previous deducted list.

import random as rm
num = 30
n = 7
slp = 1

def main():
    indxLst = []
    L = [x for x in xrange(num)]
    index = [x for x in xrange(num)]
    indexLst = []
    for e in range(1,n):
        lChng = [ L[y]+e for y in xrange(num)]

        get = int((num/e)* slp)
        index = rm.sample(index,get)
        index.sort()

        print "Index %d ="%e,index
        indexLst.append(index)
        lChng = [lChng[x] for y, x in enumerate(indexLst[e-1]) ]

        lChng.sort()
        print "List %d ="%e,lChng
main()

For example the index list I get is the following each time I deduct:

Index 1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
Index 2 = [0, 2, 5, 8, 9, 10, 12, 16, 19, 20, 21, 22, 24, 26, 28]
Index 3 = [0, 2, 5, 12, 19, 20, 21, 22, 24, 26]
Index 4 = [2, 5, 19, 20, 21, 22, 24]
Index 5 = [5, 19, 20, 21, 22, 24]
Index 6 = [19, 20, 21, 22, 24]

List (n) is deducted from list (n-1)


texts: Pattern for creating a globally accessible custom plugin

texts:
I'm currently using this pattern to create and extend a globally accessible custom plugin to be used in a web application:

; // defensive programming: script may be concatenated with others

(function($) {
    "use strict";

    // allow Plugin to be extended from other scripts
    var window.Plugin = window.Plugin || {};

    var privateVars = {
        // this contains all of the plugin's "private static" fields
    };

    function someHelperFunction() {
        // this is a private method
    }

    $.extend(window.Plugin,
    {
        method1: function() {
            // this is a public method
        },
        method2: function() {
            // this is a public method
        }
    });
})(jQuery);

This approach looks fine to me and seems to tick all the boxes. However, since I'm far from a JS guru I wonder:

Are there any issues with the above pattern that I should be aware of?

Now suppose I want to introduce global configuration that affects the behavior of all subsequent calls to method1, for example allow the user to register a callback that will get fired every time before method1 executes.

In my mind, this syntax would be nice:

window.Plugin.method1.registerCallback(function() { ... });
window.Plugin.method1(); // take it for a test drive

Is this a good idea? If not, why? What would be a better approach?

To implement this, I would do

window.Plugin = { ... }; // as above
window.Plugin.method1.registerCallback = function() {
    // this would write something inside privateVars
};

Is there a more convenient way to add many properties to method1 like this?

For example, one that would not require one statement per property to be added. Should I use jQuery.extend for this as well?


texts:
I have implemented the Dining Philosophers Problem in Clojure with refs, trying to emphasize readability. Please point out if parts of it are inefficient, not idiomatic, or improvable in any way. Full code on GitHub.

;;;;;;;;;;;;;;;;;;;;
;;     DINING     ;;
;;  PHILOSOPHERS  ;;
;;     PROBLEM    ;;
;;;;;;;;;;;;;;;;;;;;
(ns concurrency.dining-philosophers
  (:gen-class)
  (:require [clojure.core.async :refer [go chan >!! <!!]]))

(def n-philosophers 5)
(def max-eating-time 3000)
(def max-thinking-time 2000)
(def retry-time 5)
(def forks (for [_ (range 0 n-philosophers)]
             (ref false)))

;; We use a core async channel to implement a logger that writes
;;  to the terminal. It will run on the main thread
(def logger-chan (chan))

(defn log [& xs]
  (>!! logger-chan (apply str xs)))

(defn logger [channel]
  (println "Ready to log...")
  (while true
    (let [msg (<!! channel)]
      (println msg))))

;; The philosopher function contains the main logic of the application
(declare get-forks eat think wait-retry-time)
(defn philosopher
  "Given a philosopher's location n at the table, tries to pick up both
    forks simultaneously and eat. When he is finished eating he thinks
    for a while. If he cannot pick up both forks, he retries after a while.
   This function runs in a thread"
  [n]
  (log "Philosopher " n " just sat down")
  (while true
    (if (get-forks n)
      (do (log "Philosopher " n " picked up forks")
          (eat n)
          (think n))
      (wait-retry-time))))

(declare get-fork left-fork right-fork release-fork)
(defn get-forks
  "We try to get the left fork first, and then the right fork. If we succeed
    in getting the left fork but not the right, we drop the left fork.
   Returns true if we succeed in getting both forks and false otherwise."
  [n]
  (dosync
   (if (get-fork (left-fork n))
     (if (get-fork (right-fork n))
       true
       (release-fork (left-fork n)))
     false)))

(defn get-fork [fork]
  (if @fork
    nil
    (ref-set fork true)))

(defn left-fork [n]
  (nth forks (mod (dec n) n-philosophers)))

(defn right-fork [n]
  (nth forks n))

(defn release-fork [fork]
  (ref-set fork false))

(declare release-forks)
(defn eat [n]
  (log "Philosopher " n " is dining")
  (Thread/sleep (rand-int max-eating-time))
  (release-forks n)
  (log "Philosopher " n " dropped forks"))

(defn release-forks [n]
  (dosync
    (release-fork (left-fork n))
    (release-fork (right-fork n))))

(defn think [n]
  (log "Philosopher " n " is thinking")
  (Thread/sleep (rand-int max-thinking-time)))

(defn wait-retry-time []
  (Thread/sleep retry-time))

(defn -main []
  (println "Starting main")
  (dotimes [i n-philosophers]
    (.start (Thread. #(philosopher i))))
  (logger logger-chan))
(-main)


texts: Jaccard distance between strings in Rust

texts:
The Jaccard distance between two sets is the size of their intersection divided by the size of their union. For example, the distance between {1, 2, 3} and {2, 3, 4} is 2 ({2,3}) / 4 ({1,2,3,4}) = 0.5.

The Jaccard distance can be used for string similarity by slicing a string into word or character n-grams. For example, with 2-character n-grams:

"Pear" vs "Peach"
`{"Pe", "ea", "ar"}` vs `{"Pe", "ea", "ac", "ch"}` = 2/5 = 0.4

I've written an implementation in Rust as an attempt to learn something about the language.

extern crate unidecode;
use unidecode::unidecode;

use std::collections::HashSet;

fn normalize(s: &str) -> String {
    unidecode(s).to_lowercase()
}

fn shingles(s: String) -> HashSet<String> {
    let mut xs = HashSet::new();
    let it = s.chars();
    let mut pk = it.peekable();

    loop {
        let cur = pk.next();
        let nxt = pk.peek();
        match (cur, nxt) {
            (Some(i), Some(nxt_i)) => {
                xs.insert(format!("{}{}", i, nxt_i));
            }
            _ => { break }
        }
    }
    return xs
}

// Intersection of the sets divided by the size of the union of the
// sets.
fn jaccard_distance(s1: String, s2: String) -> f64 {
    let s1_shingles = shingles(s1);
    let s2_shingles = shingles(s2);
    s1_shingles.len() as f64;
    let inter: HashSet<_> = s1_shingles.intersection(&s2_shingles).collect();
    let union: HashSet<_> = s1_shingles.union(&s2_shingles).collect();
    (inter.len() as f64) / (union.len() as f64)
}

fn comp_and_print(s1: &str, s2: &str) {
    let normal_s1 = normalize(s1);
    let normal_s2 = normalize(s2);
    println!("'{}' vs '{}' ... \t {}", s1, s2,
             jaccard_distance(normal_s1, normal_s2));
}

fn main() {
    comp_and_print("Apple sauce", "Apple Trees");
    comp_and_print("Apple pie", "Grandma's Apple pie");
    comp_and_print("Pear", "Peach");
}

The shingles method seems particularly bad. I'd like it to be more flexible (for 3 or 4 character n-grams, for instance) and the use of format! rather than join on a collection like I'd do in Ruby is ugly.

edit

Here's Ruby code for shingles since I can express what I mean easier in Ruby. My Rust implementation only handles n = 2 because I had trouble figuring out how to make it dynamic.

def shingles(str, n = 2)
  (0..(str.length - n)).map { |idx| str[idx..idx+(n-1)] }.to_set
end


texts:
I have a solution but it fails the performance for two tests. How can I speed it up?

def palindrome?(str)
  str.reverse == str
end

def parse(str)
  return -1 if palindrome?(str)

  str.length.times do |i|
    before = str[0...i]
    after = str[i+1...str.length]
    return i if palindrome?(before + after)
  end
end

tests = gets.strip.to_i
tests.times do
  str = gets.strip
  puts parse(str)
end

I tried replacing my palindrome checker function but using benchmarking this seems to actually execute slower:

def palindrome?(str)
  (str.length/2).times do |i|
    return false if str[i] != str[-(i+1)]
  end
  true
end
enter code here


texts:
I've created a logging system with one-use passwords (sent via SMS API). What I would like to know is if it's "safe". I know it is hard to estimate safety but I am curious if it is safer than regular password. I would appreciate any advice to improve following code.

Scheme is:

Logging:

Loggin at a webpage -> Ask external server for password -> Store the password in session var and when form is sent compare it with the sent one

External script:

When asked with proper apikey -> give random password and send it via SMS API

The code is below:

External script:

    <?php

   $apiKey='foobar123';

   if ($_GET['api']!=$apiKey) {

       header('HTTP/1.0 404 Not Found');
       die();
   }

    $ile=12; //char number

    $onepass='';
    for($i=0;$i<$ile;$i++)
    {
        $k=rand(1,10);
        $onepass.=$letter[$k];
    }
    if (!isset($_POST['ip'],$_POST['ip'])) {echo 'error'; die();}
    $ip=$_POST['ip'];
    $www=$_POST['www'];
    echo $onepass;

    include('sender.php'); //sending API

    ?>

Logging script (at page foo.com)

    <?php
    session_start();

    $sessi='1231dsahsda8';
    $www="foo.com";
    $ip=$_SERVER['REMOTE_ADDR'];

    if(isset($_GET['destroyer'])){
        if($_GET['destroyer']=='yes'){
            session_destroy(); echo 'Logged out - Log in again'; die();
        }
        if($_GET['destroyer']=='no'){
            session_destroy(); echo 'New pass has been sent!'; session_start();
        }
    }

    if (isset($_POST['password'])){
        if($_POST['password']==$_SESSION['pass']) $_SESSION[$sessi]="log";
        else echo'Wrong Password Send again';
    }

    if ($_SESSION[$sessi]!="log") {
        if(!isset($_SESSION['pass'])){
            $adres='http://www.foobar.com/index.php?api=foobar123';
            $c = curl_init();
            curl_setopt($c, CURLOPT_URL, $adres);
            curl_setopt($c, CURLOPT_POST, 1);
            curl_setopt($c, CURLOPT_POSTFIELDS, "ip=$ip&www=$www");
            curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); /
            $dane=curl_exec($c);
            curl_close($c);
            $_SESSION['pass']=$dane;
            echo 'Password has been sent';
        }
        echo'
Log in
<form action="?a" method="post"><input type="password" name="password" value=""/><input type="submit" value="Login" /></form>';
    }
    else{//authorised
         echo 'Logged
Logout


texts:
I've come up with the following code to generate a list of all dates between two given dates:

   def generate_all_valid_dates_in_range(_start_date, _end_date) when _start_date <= _end_date do
    (:calendar.date_to_gregorian_days(_start_date) .. :calendar.date_to_gregorian_days(_end_date))
    |> Enum.to_list
    |> Enum.map (&(:calendar.gregorian_days_to_date(&1)))
  end

I would appreciate any comments on style and if there's some built in function (in either Elixir or Erlang) to achieve this sort of functionality.


texts: A small emacs-lisp snippet for opening a register in another window

texts:
I'd like to get some feedback on whether this is idiomatic elisp, whether it's any good, and any small modifications that would be useful.  Thanks

(defun jump-to-register-other-window (register-name)
  "Open a register in the other window if file"
  ;; Should also display register contents if register is text
  ;; jump-to-register allows it to fail silently if non-legit
  ;; register is passed in

  (interactive "cJump to register: \n")
  (let ((cur-buff (buffer-name)))
    (jump-to-register register-name)
    (let ((register-buffer (buffer-name)))
      (switch-to-buffer cur-buff)
      (switch-to-buffer-other-window register-buffer))))

(global-set-key (kbd "C-x 4 j") 'jump-to-register-other-window)


texts:
I have made an exercise where I need to calculate the average per row of a .txt file. (see below)

Toa Narumi gradeA 10 8 7 4 6,5
Jean-François Le Clerk gradeB 5 4 7
Joe GradeC 10 10

I only want the numbers behind the name and grade.
This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Linq;

namespace RenoD_Oef_Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            // Variablen
            StreamReader bestand = new StreamReader(@"F:\RenoD_Oef_Strings\Punten.txt");
            string strRow; // String used to read every row of .txt file
            double?[] dblPoints; // Double array used to store all values
            List<string> strInput = new List<string>(); // String List used to store all data from .txt

            // Code
            while ((strRow = bestand.ReadLine()) != null) // Read row per row in .txt
            {
                strInput = strRow.Split(' ').ToList(); // Puts every word in the row in to the list

                int intX = 0;
                foreach(string strX in strInput)    // Calculate how many strings are in the list
                {
                    intX++;
                }

                dblPoints = new double?[intX];  // Calculate the max number of elements the double array can have

                intX = 0;
                foreach(var x in strInput)  // Checks if elements in the list can be converted in to a double
                {
                    try
                    {
                        double dblR = Convert.ToDouble(x);  // If element can be converted in to a double, it will be stored in the double array

                        dblPoints[intX] = dblR;
                        intX++;
                    }
                    catch
                    {
                        intX++; // If element CAN NOT be converted in to a double, it will be still be stored in the double array but without any value
                    }
                }

                double dblAverage = 0;   // Double used to save the total average of one row
                intX = 0;
                foreach(var k in dblPoints)
                {
                    if (k.HasValue) // Elements without value will be ignored
                    {
                        dblAverage += Convert.ToDouble(k); // All double values will be added up
                        intX++; // Used to see how much double values there are to calculate average
                    }
                }

                dblAverage = Math.Round(dblAverage/intX, 2);  // Calculate average + round up to two decimals

                Console.WriteLine(dblAverage.ToString());
            }

            bestand.Close();

            Console.ReadKey();
        }
    }
}

What I have done is

Read row per row .txt file
Put all elements of that row in a list
Calculate how many elements that the double array will need to store (same number of elements the list has), which I later on use to store all doubles of the list
Check if elements in the list can be converted in to a double array; If the element can be converted in to a double, it will be stored in the double array.

If element CAN NOT be converted in to a double, it will be still be stored in the double array but without any value.

Only calculate the average of the elements in my double array that have values.

I have tested the code, and it works without any issue.

My question is, have I taken a good approach? What would you have done to make it more efficient?

I have tried searching in other threads for solutions. I have seen simular questions, but was unable to find any exactly the same as my exercise.


texts: Building a set of AngularJS directives to provide the user information about their input

texts:
I am trying to create an AngularJS directive that will give information to the user about the text they are inputting such as the number of characters they must or may enter and so on and so forth.

To cut a long story short, I would be very grateful if someone could help me improve the javascript code for my directives. As of now the only thing the directives do is provide the user with the number of characters in the textarea.

Code is hosted on Github and located in this repository.

Here are my directives:

'use strict';

angular.module('myApp.directives', [])
    .directive('enhanced', function () {
        return {
            restrict: 'A',
            controller: 'enhancedCtrl',
            scope: {},
            transclude: true,
            template: '

'
        };
    })
    .controller('enhancedCtrl', ['$scope', function ($scope) {
        var info = function () {
            var size = 0;
            return {
                getSize: function () {
                    return size;
                },
                setSize: function (newSize) {
                    size = newSize;
                }
            };
        }();

        var callback;

        this.registerSizeChangedCallback = function (callback) {
            this.callback = callback;
        };
        this.notifyObserver = function () {
            this.callback();
        };
        this.setSize = function (size) {
            info.setSize(size);
            this.notifyObserver();
        };
        this.getSize = function () {
            return info.getSize();
        };
    }])
    .directive('enhancedTextarea', function () {
        return {
            restrict: 'A',
            require: '^enhanced',
            scope: true,
            replace: true,
            template: '<textarea></textarea>',
            link: function ($scope, $element, $attrs, enhancedCtrl) {
                $scope.$watch($attrs.ngModel, function (newVal) {
                   enhancedCtrl.setSize(newVal.length);
                });
            }
        };
    })
    .directive('notice', function () {
        return {
            restrict: 'A',
            require: '^enhanced',
            replace: true,
            scope: {},
            template: '
{{size}} characters
',
            link: function ($scope, $element, $attrs, enhancedCtrl) {
                enhancedCtrl.registerSizeChangedCallback(function () {
                    $scope.size = enhancedCtrl.getSize();
                });
            }
        };
    });

And my html:

<!doctype html>

    <meta charset="utf-8">
    <title>My AngularJS App</title>
    <link rel="stylesheet" href="css/app.css"/>

{{text}}

Can someone please provide feedback about both:

My usage of the AngularJS framework
My usage of Javascript

edit: I have greatly changed the api of my directive since my original post. Please have a look at the following commit. I am looking for people willing to help me on this "lone-directive" open-source projet... Everyone welcome!


texts: Rolling 100-sided "dice" until they are the same number

texts:
I've just begun my journey into python (1 week now) and I've written couple of lines incorporating everything I've learned so far. It would be greatly appreciated if anyone could guide me in writing a better formatted (appropriate style) version of this.

I've just written a couple of lines on finding two random rolls that stop when they roll the same number. When the same number is rolled, that number is recorded along with how many rolls it took to get there. I've also made the code to find those values and store them in a list, finding the average of roll number(same number) as well as roll count(How many rolls it took). Here is the code:

import random
totalrolls = 0
rollList = []
rollcountlist = []
while totalrolls < 500:
    totalrolls = totalrolls + 1
    rollcount = 0
    roll = random.randint(1,100)
    rolltwo = random.randint(1,100)
    while roll != rolltwo:
        roll = random.randint(1,100)
        rolltwo = random.randint(1,100)
        #print roll
        #print rolltwo
        rollcount = rollcount + 1
    if roll == rolltwo:
        rollList.append(roll)
        rollcountlist.append(rollcount)
        print "Random number that matched was: %s, after %s rolls. " % (roll, rollcount)
if totalrolls == 500:
    print "Finished rolling %s times." % totalrolls

averageroll = sum(rollList) / len(rollList)
averagerollcount = sum(rollcountlist) / len(rollcountlist)

print rollList
print rollcountlist
print averageroll
print averagerollcount


texts: Compare two version numbers in the form Major.Minor.Patch.Build to see if one is less than or greater than the other

texts:
Python 3.7.0

from sys import argv
class Version:
    def __init__(self, ver_str):
        if type(ver_str) != 'string':
            ver_list = ver_str.split('.')
            self.Major = int(ver_list[0])
            self.Minor = int(ver_list[1])
            self.Patch = int(ver_list[2])
            self.Build = int(ver_list[3])

    def __repr__(self):
        return "{}.{}.{}.{}".format(self.Major, self.Minor, self.Patch, self.Build)
    def __lt__(self, other):
        if other.Major != self.Major:
            return self.Major < other.Major
        elif other.Minor != self.Minor:
            return self.Minor < other.Minor
        elif other.Patch != self.Patch:
            return self.Patch < other.Patch

        else:
            return self.Build < other.Build

    def __gt__(self, other):
        if other.Major != self.Major:
            return self.Major > other.Major
        elif other.Minor != self.Minor:
            return self.Minor > other.Minor
        elif other.Patch != self.Patch:
            return self.Patch > other.Patch

        else:
            return self.Build > other.Build

    def printme(self):
        print("{}.{}.{}.{}".format(self.Major, self.Minor, self.Patch, self.Build))

def main(argv):
    validate_args(argv)

    ver_1 = Version(argv[1])

    ver_2 = Version(argv[2])
    op = argv[3]

    if op == '<':
        print("{} < {}: {}".format(ver_1, ver_2, ver_1 < ver_2))
    elif op == '>':
        print("{} > {}: {}".format(ver_1, ver_2, ver_1 > ver_2))
    else:
        print("Incorrect operator")
        exit(-1)

def validate_args(argv):
    no_of_args = len(argv)
    if no_of_args != 4:
        print("USAGE: {} 1.1.1.1 2.2.2.2 '<' or '>'".format(argv[0]))
        exit(-1)
    if (len(argv[1].split('.')) != 4) or (len(argv[2].split('.')) != 4):
        print("USAGE: {} 1.1.1.1 2.2.2.2. '<' or '>' IMPROPER VERSION FORMAT".format(argv[0]))
        exit(-1)
    if argv[3] != '>' and argv[3] != '<':
        print("USAGE: {} 1.1.1.1 2.2.2.2. '<' or '>' IMPROPER OPERATOR".format(argv[0]))
        exit(-1)

if __name__ == '__main__':
    main(argv)


texts: Edited simple Blackjack game in Python 3.4

texts:
I'm a beginning Python programmer, and earlier I made a simple Blackjack game in Python. The original version (which can be found here) got a lot of great feedback, so I rewrote the entire program to reflect the feedback I received. Again, any tips are appreciated.

import random
import itertools

# generates the deck and card values
SUIT = 'scdh'
RANK = '23456789TJQKA'
DECK = tuple(''.join(card) for card in itertools.product(RANK, SUIT))
VAL = []
for a in range(9):
    VAL += [a+2] * 4
for _ in range(3):
    VAL += [10] * 4
VAL += [1] * 4
DECKVAL = dict(zip(DECK, VAL))
counter = 0

def shuffle():
    # shuffles the deck into random order
    global s_deck
    s_deck = random.sample(DECK, 52)

class Hand:

    global counter, s_deck

    def __init__(self):
        # deals 2 cards
        # sets up variables hand_sum and init_sum for totaling
        global counter
        self.cards = list(s_deck[counter:counter + 2])
        counter += 2
        self.hand_sum = 0
        self.init_sum = 0

    def sum_hand(self):
        # totals the hand
        self.hand_sum = 0
        self.init_sum = 0
        for b in range(len(self.cards)):
            self.init_sum += DECKVAL[self.cards[b]]
        if ('As' in self.cards or 'Ac' in self.cards or 'Ad' in self.cards or 'Ah' in self.cards)\
                and self.cards and self.init_sum + 10 <= 21:    # special ace rule conditions
            self.hand_sum = self.init_sum + 10
        else:
            self.hand_sum = self.init_sum

    def draw(self):
        # draws a card from the deck
        global counter
        self.cards += list(s_deck[counter:counter + 1])
        counter += 1

    def hit_or_stay(self, dealer):
        # asks the player if they want to hit or stay
        self.bust(dealer)
        print("\n\nDealer's Hand:", dealer.cards[0], "--")
        print("Your hand is:", self.cards, "   Your sum is:", self.hand_sum, "\n")
        choice = input("Hit or Stay? ").lower()
        if choice == 'hit':
            self.draw()
            self.hit_or_stay(dealer)
        elif choice == 'stay':
            self.total(dealer)
        else:
            print("Please enter hit or stay")
            self.hit_or_stay(dealer)

    def total(self, dealer):
        # determines winner
        if self.hand_sum > dealer.hand_sum:
            print("You won the hand")
        elif self.hand_sum < dealer.hand_sum:
            if dealer.hand_sum <= 21:
                print("You lost the hand")
            else:
                print("Dealer busted")
        else:
            print("You tied")
        print("Dealer's hand:", dealer.cards, "   Dealer's sum:", dealer.hand_sum)
        print("Your hand:", self.cards, "Your sum:", self.hand_sum)
        print("\n*******************\n")

    def bust(self, dealer):
        # checks for player busting
        self.sum_hand()
        if self.hand_sum > 21:
            print("YOU BUSTED\n")
            self.hand_sum = 0
            self.total(dealer)
        else:
            pass

class Dealer(Hand):

    def __init__(self):
        Hand.__init__(self)
        self.logic()

    def logic(self):
        # makes sure the dealer hits "soft 17"
        self.sum_hand()
        while self.hand_sum < 17:
            self.draw()
            self.sum_hand()

class Game:

    def __init__(self):
        # starts the game
        x = input("Would you like to play?").lower()
        if x == "yes":
            shuffle()
            player = Hand()
            dealer = Dealer()
            player.hit_or_stay(dealer)
        else:
            pass

if __name__ == '__main__':
    game = Game()


texts: Copying contents between BufferedStreams in Java

texts:
This is a simple function that copies the content of one stream to another. My question is simple. I am currently, copying between the streams one byte at a time, but the streams are both Buffered. What are some ways to optimize it for speed? Any other advice would be appreciated as well.

private boolean copyToStream(BufferedInputStream inputStream, BufferedOutputStream fileStream) throws IOException {
    int byt;
    while ((byt = inputStream.read()) != -1) {
        fileStream.write(byt);
        }
    }
    return true;

}


texts:
I'm making an experiment on JS, trying to build a framework for OOP. It's called Universe.

The main purpose is to emulate a mini-universe, where classes are "created" with a defined behavior (prototype) and objects are created from those classes to provide data.

So far I managed to make inheritance work (although the instanceof operator doesn't work), but my inheritance looks horrible. I've like 6 hours trying to make it pretty, but I always get stuck on a huge line like

this.universe.classes.<ClassName>.prototype.fullName.call(this)

Excerpt from index.js

// trimmed for brevity
var MoleculeClass = universe.createClass('Molecule', {
    fullName: function () {
        return this.universe.classes.Atom.prototype.fullName.call(this) + " -- new molecule name with atoms -> " + this.get('numberOfAtoms') + "\n";
    }
}, 'Atom');

How can I make this "parent call" look more natural? More like this.parent.fullName or something like that.

When I tried passing parent as a reference to parent class it worked nice on 1-level inheritance, on a 2-level (grandchild class) the middle (child class) throws me a max call stack size exceeded error.

The BigBang.js library

is.js and utils.js are just convenient shortcuts; they may be changed for some library like lodash.js.

var is = require('./is.js');
var utils = require('./utils.js');

module.exports = (function () {
    var Containers = {};
    var GProto = {
        get: function(k){
            return Containers[this.__objectId__][k];
        },
        set: function(k, v){
            Containers[this.__objectId__][k] = v;
        },
        init: function(ctorArgs){
            Containers[this.__objectId__] = utils.extend({}, Containers[this.__objectId__], ctorArgs);
        },
        id: function(){
            return this.__objectId__;
        }
    };

    function Bigbang (config) {
        this.classes = {};
        this.inheritances = {};
        this.instances = {};
        this.handlers = {};
    };

    Bigbang.prototype = utils.extend({}, Bigbang.prototype, {
        createClass: function (className, newProto, inheritsFrom) {
            inheritsFrom = inheritsFrom || null;

            var newClass = function GClass(){};
            var parentClass = this.findClass(inheritsFrom);

            newClass.prototype = utils.extend({}, Object.create(parentClass ? parentClass.prototype : GProto), {
                __class__: className
            }, newProto);

            newClass.prototype.constructor = newClass;

            this.inheritances[className] = inheritsFrom;

            this.classes[className] = newClass;
            return this.createObject.bind(this, className);
        },
        findClass: function (className) {
            return utils.have(this.classes, className) ? this.classes[className] : undefined;
        },
        createObject: function (className, ctorArgs) {
            var classToBe = this.findClass(className);

            var uid = utils.uniqueId('object_');
            var instance = new classToBe();

            instance.__objectId__ = uid;

            instance.universe = this;

            Containers[uid] = {};

            instance.init(ctorArgs);

            return instance;
        }
    });

    return Bigbang;
})();

Little Explanation

CreateClass

Method creates a 'class' under the universe.
It'll apply inheritance and store it in classes for further use from the createObject method.

CreateObject

Creates an instance of a 'created' class.
Attach an objectID.
Link the universe where it's created.
Reserve a space in Containers to store its data.
Call init function (constructor).


texts:
I instantiate GtkInfobars a lot in my GTK+ application in order to communicate with the user. There are various types of infobars, depending on the message. Basically, any infobar could be a combination of the 4 different infobar message types and 5 different icons (which are painted on the left side of the infobar).

Initially, I would call my custom infobar function like this:

infobar("Message. Woo.", type=gtk.MESSAGE_INFO, icon=gtk.STOCK_DIALOG_WARNING, timeout=5)

After a while I decided I wanted to simplify all the creation calls... so I modified my infobar function so that I could do this:

infobar("Message. Woo.", type=(1,3), timeout=3)

I feel like the second way is better and that it's worth the code obfuscation, but I suspect not everyone will agree with me.

def infobar(self, msg=None, type=(1,1), timeout=3, vbox=None):
    """Popup a new auto-hiding InfoBar."""

    # List of possible infobar message types
    msgtypes = [0,
                gtk.MESSAGE_INFO,      # 1
                gtk.MESSAGE_QUESTION,  # 2
                gtk.MESSAGE_WARNING,   # 3
                gtk.MESSAGE_ERROR]     # 4

    # List of possible images to show in infobar
    imgtypes = [gtk.STOCK_APPLY,            # 0
                gtk.STOCK_DIALOG_INFO,      # 1
                gtk.STOCK_DIALOG_QUESTION,  # 2
                gtk.STOCK_DIALOG_WARNING,   # 3
                gtk.STOCK_DIALOG_ERROR]     # 4

    ibar                    = gtk.InfoBar()
    ibar.set_message_type   (msgtypes[type[0]])
    if vbox:
        # If specific vbox requested: assume ibar for filemode, add cancel button
        ibar.add_button     (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        ibar.connect        ('response', self.cleanup_filemode)
    else:
        # If no specific vbox requested: do normal ibar at the top of message area
        vbox = self.vbox_ibar
        ibar.add_button     (gtk.STOCK_OK, gtk.RESPONSE_OK)
        ibar.connect        ('response', lambda *args: ibar.destroy())
    vbox.pack_end           (ibar, False, False)
    content                 = ibar.get_content_area()
    img                     = gtk.Image()
    img.set_from_stock      (imgtypes[type[1]], gtk.ICON_SIZE_LARGE_TOOLBAR)
    content.pack_start      (img, False, False)
    img.show                ()
    if msg:
        # If msg was specified, show it, but change the default color
        label               = gtk.Label()
        label.set_markup    ("{}".format(msg))
        content.pack_start  (label, False, False)
        label.show          ()
    # FIXME: Why doesn't Esc trigger this close signal?
    ibar.connect            ('close', lambda *args: ibar.destroy())
    ibar.show()
    if timeout:
        glib.timeout_add_seconds(timeout, ibar.destroy)
    return ibar


texts: Optional base class template to get conditional data members

texts:
In generic code, I sometimes want to conditionally add a data member to a class template. Writing separate template specializations scales as 2^N for N conditional data members. Absent a static_if feature, I have found the following user-defined class templates empty_base<T> and optional_base<T> useful:

namespace xstd {
namespace block_adl {

template<class>
struct empty_base
{
        empty_base() = default;

        template<class... Args>
        constexpr empty_base(Args&&...) {}
};

template<bool Condition, class T>
using optional_base = std::conditional_t<Condition, T, empty_base<T>>;

}       // namespace block_adl

// deriving from empty_base or optional_base will not make xstd an associated namespace
// this prevents ADL from finding overloads for e.g. begin/end/swap from namespace xstd
using block_adl::empty_base;
using block_adl::optional_base;

}       // namespace xstd

Exploiting the empty base optimization then allows users to write class templates that have optional data members (conditional on user-defined template variable traits Trait1_v and Trait2_v)

template<class T>
class Test
:
    public Base0, // unconditional base class
    public xstd::optional_base<Trait1_v<T>, Base1>,
    public xstd::optional_base<Trait2_v<T>, Base2>
{
    using B1 = xstd::optional_base<Trait1_v<T>, Base1>;
    using B2 = xstd::optional_base<Trait2_v<T>, Base2>;
public:
    Test() = default;

    Test(Arg0 const& a0, Arg1 const& a1, Arg2 const& a2)
    :
        Base0(a0),
        B1(a1),
        B2(a2)
    {}
};

Note that the optional_base variadic constructor allows linear scaling of constructor delegation in the user-defined class template Test. One minor wart is that this constructor does require passing all parameters (but otherwise, 2^N different constructors have to be written). But if any of the traits variables evaluates to false, the corresponding parameter and call to the base constructor will be optimized away. And because optional_base also has a trivial default constructor, POD-ness of user-defined classes is preserved by inheriting from it.

Obviously, over-use of inheritance has to be avoided, but the above design does avoid quite a lot of code duplication. Oh, and I haven't tested this with virtual functions, virtual base classes and what-not. I just use this for assembling value-semantic classes out of conditional building blocks.

Question: what other design / usability issues could there be with the above code?


texts: Java executing rSync shell command with progress display

texts:
I basically want to write a simple GUI program to sync to directories using the rsync command. The core part of the code is below. My main question is, do I need to have the waitFor method included? At present, I have left it out, because I would like to show the user the --progress responses as it would in terminal, not wait until the end. Is this a bad idea?

public void executeCommand(String src, String dest) {
        System.out.println("Starting shell");
    Process p;
    try {
                System.out.println("Creating process...");
        p = Runtime.getRuntime().exec("rsync --progress -va "+src +" "+ dest );
        //p.waitFor(); <- is this important?
                    System.out.println("Creating reader...");
        BufferedReader reader =
                        new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line = "";
                    System.out.println("Starting sync...");
        while ((line = reader.readLine())!= null) {
                            System.out.println(line);
                            textAreaAppend(line);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

   public void textAreaAppend(String line){
    textArea.append(line +"\n");
}


texts:
Post a cursory read of this I implemented a simple dictionary and an interface to  assign, replace, look up, and redefine its terms to apply the concepts.

It's simple, but I'd still like to know any way I could make this cleaner and more pythonic.

def print_dict(dictionary):
  for key in dictionary:
    print("{} : {}".format(key, dictionary[key]))

def display_menu():
  print("\n0 = Quit"
    + "\n1 = Look up a term"
    + "\n2 = Add a term"
    + "\n3 = Redefine a term"
    + "\n4 = Delete a term"
    + "\n5 = Display Dictionary"
  )

def is_integer(value):
  try:
   temp = int(value)
   return True
  except ValueError:
   return False

def validate(choice):
  if is_integer(choice) and 0 <= int(choice) <= 5:
    return int(choice)
  else:
    print("Input must be an integer between 0 and 5, inclusive")
    return validate(input("\nEnter Selection: "))

def lookup_term(dictionary):
  term = input("which term would you like to look up? ")
  if term in dictionary:
    print("{} : {}".format(term, dictionary.get(term)))
  else:
    print("Term does not exist, input 2 to add new term")

def redefine_term(dictionary):
  term = input("which term would you like to redefine? ")
  if term in dictionary:
    dictionary[term] = input("and its definition? ")
  else:
    print("Term does not exist, input 2 to add new term")

def add_term(dictionary):
  term = input("What term would you like to add? ")
  if term in dictionary:
    print("Already exists. To redfine input 3")
  else:
    dictionary[term] = input("and its definition? ")

def delete_term(dictionary):
  del dictionary[input('Which term would you like to delete? ')]

def process_request(choice, dictionary):
  if choice == 0:
    print("Thank you for using Stack Exchange Site Abbreviation!")
    quit()
  elif choice == 1:
    lookup_term(dictionary)
  elif choice == 2:
    add_term(dictionary)
  elif choice == 3:
    redefine_term(dictionary)
  elif choice == 4:
    delete_term(dictionary)
  else:
    print_dict(dictionary)

def main():
  site_dictionary = {
    'SO'  : 'Stack Overflow',
    'CR'  : 'Code Review',
    'LH'  : 'Lifehacks',
    '??'  : 'Puzzling',
    'SR'  : 'Software Recommendations',
    'SU'  : 'Super User',
    'M'   : 'Music: Practice & Theory',
    'RE'  : 'Reverse Engineering',
    'RPi' : 'Raspberry Pi',
    'Ro'  : 'Robotics'
  }

  print_dict(site_dictionary)
  print("\nWelcome to Stack Exchange Site Abbreviation Translator!")
  display_menu()
  while(True):
    process_request(validate((input("\nEnter Selection: "))), site_dictionary)

if __name__ == "__main__":
  main()


texts:
I am making this program that is going to calculate distance from randomly generated dots (with x and y coordinates) to 5 bigger ones and then its going to put each smaller dot into the group with bigger one that is nearest to it. So, i am making this with classes and every dot is made as an object. I made 2 arrays of objects. One holds the bigger dots and other one smaller dots. I also made 2 separate classes. I am not sure if this should be done with nested classes/subclasses or my concept is ok.

My classes:

class Groups{
    int x;
    int y;
    int brush; //i use this just for groups to have different color when drawing
    public Groups(int a, int b, int brush)
    {
        this.x = a;
        this.y = b;
        this.brush = brush;
    }
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public int getBrush()
    {
        return this.brush;
    }
}

public class Dots{
    int x;
    int y;
    int group;

    public Dots(int x, int y)
    {
        this.x = x;
        this.y = y;
        this.group = 0;
    }

    public int getX()
    {return this.x;}

    public int getY()
    {return this.y;}

    public int getGroup()
    {return this.group;}

    public void setGroup(int x)
    {this.group = x;}
}


texts:
I wrote a simple program in Haskell which takes Hex input from stdin, converts the input to ascii and writes it to stdout. An example use:

$ echo -n '48656c6c6f2c2043522e534521' | unhex
Hello, CR.SE!

And here the source code:

import qualified Data.ByteString as B
import Data.Bits
import Data.Word

unhex :: [Word8] -> [Word8]
unhex [] = []
unhex (x:[]) = error "invalid input length"
unhex (x:y:xs) = [(shiftL (hex2val x) 4) .|. (hex2val y)] ++ unhex xs
    where hex2val x =  hex2val' $ (x .|. 0x20) -- lowercase char
          hex2val' x
        | x >= 48 && x < 48 + 10 =  0 + x - 48 -- 48 is '0' in ascii
        | x >= 97 && x < 97 +  6 = 10 + x - 97 -- 97 is 'a' in ascii
        | otherwise              = error "invalid hex input"

main = do
    input <- B.getContents
    B.putStrLn $ B.pack $ unhex $ B.unpack input

This is one of my first Haskell programs I wrote, would be interesting to get some feedback on how to accomplish this task more the "Haskell" way. I'd like to know if this kind of error reporting is appropriate.


texts:
Specifically, how can I improve the time complexity of my algorithm (currently it is O(listLength * numberOfLists))? It only beats 5% of accepted LeetCode solutions, which surprised me.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    private void advance(final ListNode[] listNodes, final int index) {
        listNodes[index] = listNodes[index].next;
    }

    public ListNode mergeKLists(final ListNode[] listNodes) {
        ListNode sortedListHead = null;
        ListNode sortedListNode = null;

        int associatedIndex;

        do {
            int minValue = Integer.MAX_VALUE;
            associatedIndex = -1;

            for (int listIndex = 0; listIndex < listNodes.length; listIndex++) {
                final ListNode listNode = listNodes[listIndex];

                if (listNode != null && listNode.val < minValue) {
                    minValue = listNode.val;
                    associatedIndex = listIndex;
                }
            }

            // An associated index of -1 indicates no more values left in any of the given lists
            if (associatedIndex != -1) {
                if (sortedListNode == null) {
                    sortedListNode = new ListNode(minValue);
                    sortedListHead = sortedListNode;
                }
                else {
                    sortedListNode.next = new ListNode(minValue);
                    sortedListNode = sortedListNode.next;
                }

                advance(listNodes, associatedIndex);
            }
        }
        while (associatedIndex != -1);

        return sortedListHead;
    }
}

Note that the Solution class in addition to ListNode is already provided, the only code that I wrote was inside mergeKLists.