Multiple return statements smells like what?

First of all, I would question whether this code works correctly. Based on the names in your code, I assume that for example DoCompileCodeBase() should execute even when StopOnCompileFailure is false, but its result should be ignored. But that's not what happens: when StopOnCompileFailure is false, DoCompileCodeBase() doesn't even execute, because of short-circuiting evaluation of &&.

If what the code does is really what it should do (which is what I'm going to assume in the following text), then you should probably rename the settings properties.

Second, you can extract the checks and the Do method calls into a separate method (Simon's answer already suggested something similar):

// may need a better name
private bool ExecuteInternal()
{
    var errors = new List<string>();
    var logger = _logProvider.GetLogger(GetType().Name);
    var settings = Properties.Settings.Default;

    DoArchiveOldInstallers(errors, logger);

    if (settings.StopOnBackupCurrentInstallerFailure && !DoBackupCurrentVersion(errors, logger))
        return false;

    if (settings.StopOnUpdateCodeBaseFailure && !DoGetLatestVersion(errors, logger))
        return false;

    if (settings.StopOnCompileFailure && !DoCompileCodeBase(errors, logger))
        return false;

    if (settings.StopOnBuildInstallerFailure && !DoBuildInstaller(errors, logger))
        return false;

    return true;
}

public override void Execute()
{
    bool success = ExecuteInternal();
    OnExecutedCompleted(success);
}

Third, since all the Do methods are on the same object, you could change errors and logger into fields, so that you don't have to pass them around. Though I'm not completely convinced this is actually better, especially if Execute() is a method that's called over and over.

Fourth, you might consider associating all the settings properties with the right Do method using some kind of data structure:

private readonly Tuple<bool, Func<bool>>[] action;

// in constructor:
actions = new Tuple<bool, Func<bool>>[]
{
    new Tuple<bool, Func<bool>>(settings.StopOnBackupCurrentInstallerFailure, DoBackupCurrentVersion),
    new Tuple<bool, Func<bool>>(settings.StopOnUpdateCodeBaseFailure, DoGetLatestVersion),
    new Tuple<bool, Func<bool>>(settings.StopOnCompileFailure, DoCompileCodeBase),
    new Tuple<bool, Func<bool>>(settings.StopOnBuildInstallerFailure, DoBuildInstaller)
}

private bool ExecuteInternal()
{
    var errors = new List<string>();
    var logger = _logProvider.GetLogger(GetType().Name);
    var settings = Properties.Settings.Default;

    DoArchiveOldInstallers();

    foreach (var action in actions)
    {
        if (action.Item1 && !action.Item2())
            return false;
    }

    return true;
}

The syntax to initialize the list of Tuples is not great. You could improve that by having a special type TupleList<T1, T2> : List<Tuple<T1, T2>>, which would have a method like void Add(T1 item1, T2 item2). That way, the initialization simplifies to:

actions = new TupleList<bool, Func<bool>>
{
    { settings.StopOnBackupCurrentInstallerFailure, DoBackupCurrentVersion },
    { settings.StopOnUpdateCodeBaseFailure, DoGetLatestVersion },
    { settings.StopOnCompileFailure, DoCompileCodeBase },
    { settings.StopOnBuildInstallerFailure, DoBuildInstaller }
}

The next step after this could be encapsulating each action into its own object, so that you could do something like:

foreach (var action in actions)
{
    if (!action.Execute())
        return false;
}

And each action would be responsible for checking the right setting, if appropriate. (Actions that don't do any checks, like DoArchiveOldInstallers could be represented by a different type that inherits from the same base, or something like that.) But I'm not sure doing that would be worth it in this case.


Since you didn't post the code of Neuron, InputNeuron and OutputNeuron so I just give some comments on the style.

Instance variables

private HashMap<String,InputNeuron> inputNeurons;
private LinkedList<Neuron> internalNeurons;
private LinkedList<OutputNeuron> outputNeurons;

Instance variables should be kept private and expose via methods.

Ps: I'm not sure here if you intended to let them package-private for other classess (e.g Neuron, etc) to access them directly.

Prefer reference to objects by their interfaces

It is considered a good practice to reference to objects by their interfaces rather than concrete implementation (if they have one). Here you are using the Collection Framework so it'd be better if you declared the instance variables via interfaces.

private Map<String,InputNeuron> inputNeurons;
private List<Neuron> internalNeurons;
private List<OutputNeuron> outputNeurons;

Make defensive copies

The constructor of NeuronNetwork uses directly the arguments passed to it which could lead to some subtle bugs. It'd be better if you make a copy of those arguments.

public NeuralNetwork(Map<String,InputNeuron> inputNeurons, List<Neuron> internalNeurons,
        List<OutputNeuron> outputNeurons) {
    this.inputNeurons = new HashMap<String, InputNeuron>(inputNeurons);
    this.internalNeurons = new ArrayList<Neuron>(internalNeurons);
    this.outputNeurons = new ArrayList(outputNeurons);
    this.outputNeurons.get(0).getOutput(); // potential IndexOutOfBoundException
}

The last line in the constructor could cause IndexOutOfBoundException if the outputNeurons is empty. I'm not sure the purpose of this line.

Avoid using array as return type if possible

The method timeStep returns an int[] which is an array. IMO this is not good since array is  less convenience and doesn't provides much useful behaviors. Returning a Collection or a  List would be a better choice.

public Collection<Integer> timestep(List<String> inputs) {
    System.out.println("Network: timestep: " + timestep);

    for (String inp : inputs) {
        assert inputNeurons.get(inp) != null : "timestep was given a String as key for an InputNeuron that didn't exist";
        inputNeurons.get(inp).fire();
    }

    for (Neuron internal : internalNeurons) {
        internal.nextTimestep();
    }

    for (Neuron outputNeuron : outputNeurons) {
        outputNeuron.nextTimestep();
    }

    List<Integer> output = new ArrayList<Integer>(outputNeurons.size());
    for (OutputNeuron outputNeuron : outputNeurons) {
        output.add(outputNeuron.getOutput());
    }

    timestep++;
    resetAll();
    return output;
}

Misc

You could rename the method getNrTimestep() to getTimestep() for more elegant.

That's it. Hope these could help.


Using one parent model and other extending it in a PHP framework

Well, having a parent model that is extended for all your model classes is always a good idea if they all share the same behaviour and help you with your development. I have implemented a similar approximation within my models and I'm doing something similar to what you do, but instead of writing the query in the controller, I call to the model to handle the retrieve of the data.

Doing as you do it, you have to write all the time the same kind of query in your controller, losing the MVC pattern. Let's say you want to retrieve the values of categories, in a point of your controller you'd have:

$this->games_model->limit(30,0)->where(array('categorie_id' => 1))->get_list()->result();

If you want to retrieve the categories in other line of your controller, you'll have to write the same sentence, and... what if, in some point of your development,  you wanted to change the field categorie_id to, let's say, super_categorie_id? You'd have to do it in all the calls in your application code... You lost all the value the M in MVC is offering, isolate management of data in the Model layer.

So, I'd keep the extension, but writing the methods for reading with is proper filters INSIDE of the child class, and pass it only the data not needed for filtering (as limit) as a parameter, and set them to a default.

I don't know if I clearly explained myself, any doubt write a comment, ;D


Dynamic array resizing and nesting conditions

Looping through the Array, counting the matches to avoid resizing the return Array is very efficient.

Application.Transpose is not needed because the return array is in the same shape as the original array.

  RemoveRows2D = Application.Transpose(arr_new)

This is correct:

  RemoveRows2D = arr_new

Using Application.Index to slice off the target column is a cool trick but is it really needed?  Not only does it add extra overhead but it adds an extra variable.  In my opinion, arr_col_k is just extra clutter because I don't think that  arr_col_k(i, 1) = strKeeper is any more readable than arr(i, x) = strKeeper.

  arr_col_k = Application.Index(arr, 0, k)

You can remove up_new = up_new + 1 from this loop:

If Headers Then                                   'handle header row
    For j = LBound(arr, 2) To UBound(arr, 2)
        arr_new(i, j) = arr(i, j)
    Next
    i = 1 + 1
    up_new = up_new + 1
End If

Moving forward, the main thing that I think you should focus on is the names of your variables.  Consider arr, k, strKeeper, up_new, arr_col_k, arr_new, what do the names of these variable tell you about the roles that they play?

Compare them to my alternative names.

arr: Data, DataArray, arrData, arrSource, Source, SourceArray
k: col, ColumnIndex
strKeeper:  Match

I use Match because it is used in many VBA and Excel functions.

up_new: Count
arr_col_k: Matches, arrTarget, ???I would have to think about this one.
arr_new:  Results, results, arrResults

I also use 1 or 2 character variable names for all my counters.  I prefer x, x1, y, y1 because  i or l can be tough to differentiate.

RemoveRows2D is basically a 2D version of the built in VBA.Filter function.  Whenever I write a version of a standardized method I start by copying the methods signature from the Object Browser and work from there.  Using the same structure and variable names as the built-in methods will make it easier for others to understand and use yours.

Question: Is there a more efficient way to nest the following:

If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then

Technically, using If and EsleIf blocks is more efficient because the VBA evaluates all the conditions in an If Then statement.  In your case the difference in efficiency is negligible.  Note: In my version of function I use a flag with If and EsleIf blocks because I think that it read better and is easier to debug.

If (arr_col_k(i, 1) = strKeeper And re_Tain) Then

ElseIf (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then

End If

Function Filter2D(SourceArray, Match As String, ColumnIndex As Long, Headers As Boolean, Optional Include As Boolean = True, Optional Compare As VbCompareMethod = vbBinaryCompare) As Variant()
    Dim count As Long, x As Long, y As Long
    Dim flag As Boolean
    Dim Results() As Variant
    'Adjust the ColumnIndex based on SourceArray Lbound
    'This allows the user to refer to the 1st column of a Option Base 0 array as 1 instead of 0
    ColumnIndex = ColumnIndex - LBound(SourceArray, 2) + 1
    'First loop to count matches
    For x = LBound(SourceArray) To UBound(SourceArray)
        If x = LBound(SourceArray) And Headers Then
            count = count + 1
        ElseIf Include Then
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) = 0 Then count = count + 1
        Else
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) <> 0 Then count = count + 1
        End If
    Next

    If count = 0 Then Exit Function

    'Adjust the count based on SourceArray Lbound
    count = count - LBound(SourceArray) + 1
    'Size the Results array to fit the data
    ReDim Results(LBound(SourceArray) To count, LBound(SourceArray, 2) To UBound(SourceArray, 2))
    'Reset count for reuse
    count = LBound(SourceArray)
    'Second loop to transfer the data
    For x = LBound(SourceArray) To UBound(SourceArray)
        If x = LBound(SourceArray) And Headers Then
            flag = True
        ElseIf Include Then
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) = 0 Then flag = True
        Else
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) <> 0 Then flag = True
        End If

        If flag Then
            For y = LBound(SourceArray, 2) To UBound(SourceArray, 2)
                Results(count, y) = SourceArray(x, y)
            Next
            count = count + 1
        End If
        flag = False
    Next

    Filter2D = Results
End Function


How can I improve this code to display contact numbers?

At first I would suggest to get rid of the contact type enumeration and instead derive concrete contacts from your contact class. This will increase cohesion dramatically as this way you do not need to have fields like area code in your base contact class.

Regarding your problem: You could use something like a visitor pattern to navigate the "tree" of data (Persons -> Person -> Contacts) with your Person and Contact acting as elements accepting the abstract visitor. This will give you the flexibility to walk the tree for different purposes. For your scenario you could write something like a TableVisitor that creates the table structure you want to generate.


Retrieving result sets from a MySQL table

The first thing I've noticed is that you return 2 different things:

The data that the user wanted;
The error information.

Now, how will you distinguish between an error-ed query and a successful one? You can't! And that makes angels angry and cry.

Return null in case of error.

Your variable names are really....... conflicting and incomplete...

$x = 1; //Should be $i
$vec = []; //No idea what this is for
foreach($params as $p) //$p should be $param
$array = ''; // ... a variable called $array that receives a string ... WTH!?

A good variable name will give us an idea of it's content without having to read through all the code.
The name for $i (instead of $x) is the standard name used for an increment. Since you have $x++ below, it is a good name.

Now, you have this block:

if($stmt->execute()){
    while($row = $stmt->fetch(PDO::FETCH_OBJ)){
        $array = '';
        foreach ($cols as $col) {
            $array .= $row->$col.' ';
        }
        $vec[] = $array;
    }
    return $vec;
} else {
    return $db->errorInfo();
}

Use early returns, like this:

if(!$stmt->execute()){
    return null;
}
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
    $array = '';
    foreach ($cols as $col) {
        $array .= $row->$col.' ';
        }
    $vec[] = $array;
}
return $vec;

This helps the code to be more readable and reduces the nesting level. Too many chained ifs and loops will cause your code to be hard to read.

You have the following if, just a little bellow:

if($stmt = $db->prepare($sql)){
    $x = 1;
    $vec = [];
    if(count($params)){
        foreach($params as $p){
            $stmt->bindValue($x, $p);
            $x++;
        }
    }
}

Applying the early return:

$stmt = $db->prepare($sql)
if(!$stmt){
    return null;
}

$i = 1;
$vec = [];

foreach($params as $param){
    $stmt->bindValue($i, $param);
    $i++;
}

See? It is so much easier to read!

In fact, the loop can be like that: (this point is subjective!)

foreach( array_keys($params) as $i => $param ) {
    $stmt->bindValue($i + 1, $params[$param]);
}

Bye bye $i++;!

Going deeper on your code, I see that you also have some useless code.

Check this block:

if(count($params)){
    foreach($params as $p){
        $stmt->bindValue($x, $p);
        $x++;
    }
}

Why do you have that count() there? It does nothing there. Just do this:

foreach($params as $param){
    $stmt->bindValue($i, $param);
    $i++;
}

The foreach doesn't care about the length of $params. As long as it is an array.

And now, going to this block:

while($row = $stmt->fetch(PDO::FETCH_OBJ)){
    $array = '';
    foreach ($cols as $col) {
        $array .= $row->$col.' ';
    }
    $vec[] = $array;
}
return $vec;

Question time:

What, in the name of the Lord, is going on here?
Why are you fetching an object instead of an associative array?
What does $array do?
Why is it called $array?
What is $vec for? What's in it?

After testing myself, I concluded this: It's bugged!!!
The expected result is different that the provided result.
I really don't get the reasoning to do $row->$col.' ';.

Here's a test code I've build, based on yours:

//test variable, fakes the database
$items = array(
    (object)array(
        'b'=>5,
        'c'=>'a'
    ),
    (object)array(
        'b'=>7
    )
);

$cols = array('b','c');//only 1 column

//simulates $stmt->fetch(PDO::FETCH_OBJ)

while($row = array_shift($items)){
    $array = '';
    foreach ($cols as $col) {
        $array .= $row->$col.' ';
    }
    $vec[] = $array;
}
var_export($vec);

Result I expected (added extra whitespace):

array (
    0 =>
    array (
        'b' => 5,
        'c' => 'a',
    ),
    1 =>
    array (
        'b' => 7,
    ),
)

Result obtained:

Notice:  Undefined property: stdClass::$c in [...][...] on line 7

array (
    0 => '5 a ',
    1 => '7  ',
)

Check it on http://sandbox.onlinephpfunctions.com/code/1e0527eccba4ada6de7b4cdba9967ab9df4e2ce7

In conclusion: The code is broken! Fixing it is left as an exercise for you.


An IEnumerable (and IOrderedEnumerable) represents a question, not an answer. axisList is not really a list -- it is a question asking "What is the sequence of elements from _gameObjects ordered by X value?". So every time you do this:
            GameObject a = axisList.ElementAt(i);
            GameObject b = axisList.ElementAt(j);

You are answering the question "What is the ith element in that ordering". Which means it needs to re-order the sequence on every iteration! Your outer loop ends up being hugely expensive (O(n^3 log(n)) if my math checks out); you certainly don't need to do that.
You should cache the result of the ordering and re-use it in your loop. Change this
IOrderedEnumerable<GameObject> axisList = _gameObjects.OrderBy(x => x.LeftRightMost.X);

to this:
var orderedByX = _gameObjects.OrderBy(x => x.LeftRightMost.X).ToList();

.ToList() will evaluate the OrderBy query and return a flattened "answer" that you can keep reusing, and as a bonus it has O(1) lookup so ElementAt is fast -- you could even change ElementAt(i) to [i] to make that more clear.


Your join function is confusing, why use *args if you're only going to take args[0]? As far as I can see you could just rewrite it like this:

def join(arg):
    return b''.join(arg)

The only difference is that you can't pass arbitrary unused parameters now, but that would communicate the function's use better. If you have to use this as a work around then you should note why it's necessary with a docstring, since it's not obvious from context and your function just looks like a convenient way to build bytestrings.

def join(*args):
    """Return a bytestring of the first argument's elements joined.

    Will ignore all arguments after the first.
    This is necessary to deal with the foo bar."""

Semantically, I think it might make sense for you to raise a ValueError for the unknown type error. Backwards as it sounds, the user has passed the correct type (a dictionary) but that dictionary has an invalid value. It doesn't matter that the value indicates a type, the error the user has made is with the values they provided.


Is it ok to break long html elements down into multiple lines?

I'd already answered this in the comments (which I shouldn't, we got answer fields for this), but anyway...

Because this makes it much clearer and easier to read in my opinion.

Absolutely. And that's a good reason to do it. Your 80-100 character limit makes sense as well. 80 is considered a standard 'limit' of sorts in many languages (Python is famous for it, but back in the day punch cards and teletypes were already limited to 80 columns).
Google's HTML style guide states:

Break long lines (optional).
While there is no column limit recommendation for HTML, you may consider wrapping long lines if it significantly improves readability.
When line-wrapping, each continuation line should be indented at least 4 additional spaces from the original line.

You've already verified your validator doesn't have a problem with it either, so, go for it. In hindsight, if the validator would've had problems with it, it would've been time for a better validator.
Better readability => better maintainability => less bugs and less development time.


Converting an angle in degrees to a pretty string representing it in radians

Here are some thoughts on your code:

I'm not too fond of function annotations – Maybe it's just me, but I find the function annotations a slightly confusing syntax addition. I would rather extend the docstring with this information.
Compress the doctests a little – You get bonus points for using doctests, but I would compress the output somewhat. Maybe build an array of result values, and do a comparison against that. Or simply reduce the number of values. As it stands, it is more doctests code than actual code doing something useful
Avoid duplicating calculations – You do the 180 // gcd and abs(angle // gcd) twice. One for the if and one as a result. This could possibly read better using temporary variables to both avoid the double calculation, and to simplify the ternary statements.

However there is an even neater solution to avoid most of your code, and that is to use all of the capabilities of the fractions module. Using this module your function can be reduced to:

rads = fractions.Fraction(angle, 180)
return "{}π/{}".format(angle, rads.numerator, rads.denominator)

Of course, this does return mostly the same as your function returns, but it does return some of the basic cases like "0π/1" or "1π/3". These could be handled using some ternary operations, which leads us back to code similar to your original code (but without exposing the calculations, and with compression (not reduction) of test cases):

def degrees_to_pretty_radians(degrees):
    """Return the degrees in fractions of π:

    >>> tests = [0, 1, 18, 31, 45, 60, 120, 180, 270, 360, 480]
    >>> all_tests = tests + [-x for x in tests]
    >>> expected_result = ['0π', 'π/180', 'π/10', '31π/180',
    ...        'π/4', 'π/3', '2π/3', 'π', '3π/2', '2π', '8π/3',
    ...        '0π', '-π/180', '-π/10', '-31π/180',
    ...        '-π/4', '-π/3', '-2π/3', '-π', '-3π/2', '-2π', '-8π/3']
    >>> actual_result = [degrees_to_pretty_radians(d) for d in all_tests]
    >>> actual_result == expected_result
    True
    """

    rads = fractions.Fraction(degrees, 180)
    numerator = "" if rads.numerator == 1 else \
                "-" if rads.numerator == -1 else \
                rads.numerator
    denominator = "" if rads.denominator == 1 else \
                  "/{}".format(rads.denominator)
    return "{}π{}".format(numerator, denominator)


Encode strings by subtracting one from each character code

Try looping through it with a simple for loop:

var b = '';
for (var i = 0; i < a.length; i++)
{
   b += String.fromCharCode(a.charCodeAt(i) - 1)
}
return b;


Codility AbsDistinct: Why is this solution not O(n)?

I don't see any reason why your solution would not be O(N).

However, it would fail if the array contained Integer.MIN_VALUE, since its absolute value won't fit within an int.


A faster method would avoid the numeric divisions. Instead, it would load the number in a string (through the sprintf function), reverse the string, and finally recast the string into a number (with the help of the sscanf function).

I'm attaching a function named fastrev which in turn uses an auxilliary function reverse_string. Hopefully, this would improve runtime for large numbers.

char* reverse_string(char *s1, char* s2)
{
    char *p, *q;
    int len = strlen(s1);

    for (p = s1; *p; p++) {
        s2[len-1] = *p;
        len--;
    }
    return s2;
}

int fastrev(int num) {
    static char nbuff[32];
    static char rnbuff[32];
    int rnum;

    sprintf(nbuff, "%d", num);
    reverse_string(nbuff, rnbuff);
    sscanf(rnbuff, "%d", &rnum);
    return rnum;
}


There is no integer value for which this undefined. Having a zero in the numerator is a legal math operation that results as zero. having a zero in the denominator would result in an undefined result, but that concern is mitigated by the fact that the absolute value of the product of two integers will be greater than or equal to zero and then you add one to that product before doing the division. In other words, the smallest denominator that the equation could have is one which is legal. So you could remove the if statements

using System;

class TaskTwo {

    static void Main() {
        // Declare variables
        int x, y;
        double w;

        Console.WriteLine("Please, enter two the numbers");
        x = int.Parse(Console.ReadLine());
        y = int.Parse(Console.ReadLine());

        w=(Math.Abs(x) - Math.Abs(y))/ (1 + Math.Abs(x*Y));

        // Display the result on the screen
        Console.WriteLine("W = " + w);
       }
    }

This should suffice.


The whitespace needs a lot of changes to be PEP8-compliant. The capitalisation is also unconventional: functions and variables in Python usually start with a lower-case letter.

The meaning of Player is not entirely clear, and the logic is hard to follow because of that. The convention for this type of combinatorial game is to denote a position as "N" (Next player wins) or "P" (Previous player wins). So I think that Solve should be renamed position_is_N, and then the Player variable becomes unnecessary.

if condition: return doesn't need a following else:.

The loop can be tidied up considerably with range and any. I think this is equivalent:

@lru_cache(maxsize=None)
def position_is_N(x, y):
    return x % y == 0 or \
           any(not position_is_N(max(x2, y), min(x2, y))
               for x2 in range(x % y, x, y))

A comment about the constraint that x >= y would be nice.

  range of both X and Y is 1 to 10^18

Consider inputs 10**18, 3 (or other similarly small y). How many times might the loop run in the worst case?

As a rule of thumb, for a challenge like this if you need to do anything more than 10**9 times your algorithm is wrong. I can only suggest that you will need a complete rewrite to pass the time limit, so you should build a table of small values and see whether you can spot and prove a pattern. The problem is probably far more about mathematics than programming.


Class for exposing information with computer properties (getters)

Set Initial Values?
private var taxRate:Double = 0
private var discount:Double = 0
private var initialPrice:Double = 0

func setInitialValues(initialPrice:Double, discount:Double, taxRate:Double){
    self.taxRate = taxRate
    self.discount = discount
    self.initialPrice = initialPrice
}

I don't care for this at all.
First, I don't see a good reason for these three properties to necessarily be private.  Why should the user have to guess what they've set their properties to?
Further more, you're not protecting these values from being reset.  The user simply has to call setInitialValues again.  The method name may be an attempted hint at that being the incorrect use of the class, but my mantra is let the compiler do as much for us as possible.
We should expose these properties to the user.  We should not allow the user to modify these properties after initialization.  We should write an init method.
let taxRate: Double
let discount: Double
let basePrice: Double

init(taxRate: Double = 0, discount: Double = 0, basePrice: Double = 0) {
    self.taxRate = taxRate
    self.discount = discount
    self.basePrice = basePrice
}

Why is salePrice() a function?
You have implemented basically everything else as a computed, read-only property.  Why can't salePrice also be a computed, read-only property?  If you want it to be private, that's fine if that makes sense for your class, but it can still be a computed property.
var salePrice: Double {
    return basePrice - savings
}

Also, note what I've done here.  The get { } is omitted.  Computed properties that just return a value can omit the get and are implicitly read-only.  Any code is assumed to be for the get if you have omitted the get & set keywords.

internal is the default access level.
You have marked some things as private.  You have omitted an access specifier on most things, and then your grand total method is specified as internal.  Marking internal is the same as omitting an access specifier.  You should drop this internal keyword here, or consistently use it with all the other properties.  None of your members are public in your current implementation.

About that grandTotals method...
This method almost seems out of place if it weren't for the fact that the class is called CalculatorBrain.  But it doesn't depend on any state, so it should probably be a static method.
Your loop is far from optimal.  But, we don't even need a loop.  We can use reduce.
return list.reduce((0,0,0)) {
    return (
        $0.totalPrice + $1.totalPrice,
        $0.savings + $1.savings,
        $0.taxes + $1.taxes
    )
}

But... I might avoid returning a tuple.  Why not just make a struct?
struct GrandTotal {
    let price: Double
    let savings: Double
    let taxes: Double
}

And now instead of a method that feels like it's in a weird place, we just add an appropriate init:
struct GrandTotal {
    let price: Double
    let savings: Double
    let taxes: Double

    init(list: [Item]) {
        let totals = list.reduce((0,0,0)) {
            return (
                $0.totalPrice + $1.totalPrice,
                $0.savings + $1.savings,
                $0.taxes + $1.taxes
            )
        }

        price = totals.0
        savings = totals.1
        taxes = totals.2
    }
}


Selecting a div with a blue border and changing its text

To be honest this is very over-engineered. The same can be done with very little to no JavaScript by taking advantange of the features of CSS. But one by one.

First off the class name content is bad choice. It is very generic. It runs into the danger to be used in some other context on the same page and it doesn't describe what you are using it for. Something like selectable would be better.

Using className to identify elements is for one verbose, for the other unrelatiabe. An element, for example, that has both the classes content and selected could have a className "content selected" or "selected content" or "content selected someOtherClass", etc. Just because you set it to "content selected" there is no guarantee that it will stay that.
Instead you should use the classList property. It allows you the set, remove, toggle and check for separate classes (and more).
So, for example, the block
const selectedContentReference = document.querySelectorAll('.selectedContent');
for (div of selectedContentReference) {
  if (div.parentNode.className == 'content') {
    div.className = 'selectedContent contentThatShouldBeHidden';
  }
  else if (div.parentNode.className == 'content selected') {
    div.className = 'selectedContent';
  }
}

can become:
const selectedContentReference = document.querySelectorAll('.selectedContent');
for (div of selectedContentReference) {
  const parentIsSelected = div.parentNode.classList.contains("selected");
  div.classList.toggle("contentThatShouldBeHidden", !parentIsSelected);
}

There is more that could be said to the JavaScript, however all this class toggling is unnecessary. By using, for example, the CSS child combinator and the :not pseudo class you can show and hide the approprate texts depending on the selected class on the parent element alone.
Using the same HTML and limiting the toggle function to:
// Moving the list of elements outside the function, because the list doesn't change
const contentReference = document.querySelectorAll('.content');

function toggle(el) {
  for (div of contentReference) { div.classList.remove("selected"); }
  el.classList.add("selected");
}

and following CSS:
.content:not(.selected) > .selectedContent,
.content.selected > .notselectedContent {
   display: none;
}

And as I mentioned at the beginning it is possible to do this without JavaScript. HTML has such a toggling feature built in: radio buttons. And CSS can be used to style elements depending on if a radio button is selected (:checked) or not, even if the radio button isn't visible.
https://jsfiddle.net/27kw8qe1/


Basic implicit tree implementation in Java

More efficient and accurate is a bit shift.

this.treeArray =  new int[(int) Math.pow(2, treeDepth)];
treeArray =  new int[1 << treeDepth];

A test is in order for the top:

if (0 > treeDepth || treeDepth > 31) {
    throw new IllegalArgumentException();
}

The name returnRightSubTree is a bit irritating because of that return, synonymical yieldRightSubTree or get/create.

  public Tree returnLeftSubTree() {
    return yieldSubTree(false);
  }

  public Tree returnRightSubTree() {
    return yieldSubTree(true);
  }

  private Tree yieldSubTree(boolean right) {
    if (depth == 0) return null;

    Tree ret = new Tree(depth - 1);
    int[] trees = ret.getTreeArray();
    for (int i  = 1; i < depth; i++) {
      int iTarget = 1 << (i - 1);
      int iSource = (1 << i) + (right ? 1 << (i - 1)) : 0);
      for (int j  = 0; j < depth - 1; j ++) {
        trees[iTarget + j] = trees[iSource + j];
      }
    }
    return ret;
  }

which could be faster using System.arraycopy:

  private Tree yieldSubTree(boolean right) {
    if (depth == 0) return null;

    Tree ret = new Tree(depth - 1);
    int[] trees = ret.getTreeArray();
    for (int i  = 1; i < depth; i++) {
      int iTarget = 1 << (i - 1);
      int iSource = (1 << i) + (right ? 1 << (i - 1)) : 0);
      System.arraycopy(trees, iSource, trees, iTarget, depth - 1);
    }
    return ret;
  }

The i dependent expression before the j loop. As you see, just as i++
one could have (but not necessarily):

    for (int i  = 1, iT = 1; i < depth; i++, iT <<= 1) {
      //int iTarget = iT;
      int iSource = (iT << 1) + (right ? iT : 0);

For the rest:

Tab indentation in java is 4. Historically a tab size of 3 was often for C/C++,
and for academic reasons: "there should be less long code with nesting in favour of
more methods" 4 was chosen; also as 8 was the archaic system tab size.

A tab size of 2 is still seen in XML/HTML, but I would refrain from that. Especially
as with lambdas one gets more unreadable indentations.


The code looks good to me as well except if you are looking for the ids of the failed logins you would not want to count the ids (SELECT count(id)) but instead just select the id (SELECT id).


Having a log for a production application is an excellent idea. Some quick notes on logging web applications in general:

  Application logging should be always be included for security events.

  ...

  Each log entry needs to include sufficient information for the
  intended subsequent monitoring and analysis. It could be full content
  data, but is more likely to be an extract or just summary properties.
  The application logs must record "when, where, who and what" for each
  event.

OWASP Loggin Cheat Sheet

With that in mind, winston is generally considered a good choice for Node.js logging. It's dependencies are a little dated, and support is minimal. Another option is Scribe.js (lightweight, but also minimal support).

  This reduces the reuse of any lib code as it cannot stand on its own
  without having a reference to applog.

Not necessarily something bad. What you have is compact and easy to transport. You could consider pulling this snippet into it's own file and then require-ing that file in each JS script as needed.

I'm not aware of anything you can do to overcome this.

  It doesn't feel like a best practice to have global references used
  inside modular object-oriented code.

You're right, global variables/functions in general aren't the best. They can cause issues with naming and referencing in the global scope. There are a few solutions to this, w3 has a section devote to avoiding globals.

If your snippet can be placed inside a class (ES6 only) or an app object, I suggest that.

  if I did switch away from Winston it's possible that all my code would
  need to be updated.

Certainly something to think about. With a "find and replace all" command (using a regex perhaps in your IDE) though, much of the hassle could easily be taken care of.


Here is an alternate implementation:

#!/usr/bin/env python3

from bs4 import BeautifulSoup
from pprint import pprint
import re
import requests

class Coins:
    table_re = re.compile('^AssetTable__Table-')

    def __init__(self, url="https://www.coinbase.com/price"):
        self.url = url
        self.session = requests.Session()

    # Check if I get a 200 status code and if so, create instance from bs4
    def _get_response(self) -> BeautifulSoup:
        response = self.session.get(self.url)
        response.raise_for_status()
        return BeautifulSoup(response.text, 'lxml')

    # Select the class and get the data
    def get_data(self) -> dict:
        soup = self._get_response()
        table = soup.find('table', attrs={'class': self.table_re})
        prices = {}
        for row in table.tbody.find_all('tr'):
            cells = row.find_all('td')
            if len(cells) < 6:
                continue
            name = cells[1].find('h4').text
            price = cells[2].find('h4').text
            prices[name] = price
        return prices

Note:

Do not rely on long, terrible, possibly dynamically-generated CSS class names
If you want to reuse this class to repeatedly fetch prices, then the members should be the session and the URL, and the data should be restricted to the function
Don't write access granted. Other than it being corny, you should only throw an exception if there's a failure, not write to stdout if there's a success in the data retrieval method. Such progress indicators are best left to the calling function above.
Just index into the cells. Don't use the modulus.


Exponentiation using while loop in Python

Your algorithm is \$O(n)\$ where \$n = \text{degree}\$.
This means the performance of your code is quite poor.
You can make an \$O(\log(n))\$ algorithm by using binary operators on the exponent.

For an explanation of this algorithm, you:

Have the exponent in a form where you can manipulate it's binary.
Whilst the exponent isn't empty:

If the last (smallest) index of the exponent is 1, times result by the base.
Remove the last index of the exponent.
Multiply the base by it's self.

Which results in:

def pow(base, exp):
    result = 1
    while exp:
        if exp & 1:
            result *= base
        exp >>= 1
        base *= base
    return result


Apple picking game. More efficient method than using global variables

You don't need to list those as globals. Variables defined at the module-level namespace are available in functions in that module. Just remove the global declarations and you should be fine.

Another thing: calling main() is kind of dangerous. It's always better to do this instead:

if __name__ == '__main__':
  main()

That way main() won't be run when the module is imported.


The compiler can't know beforehand if document.getElementById('js-btn-submit') wil return anything. That is why you cannot assign the result directly to a type.

One solution is to tell the compiler that you are certain that the HTML element exists, using !

let button = document.getElementById("button")! as HTMLButtonElement

If you are NOT certain that the button exists in the HTML document, you can use the suggestion given by VS Code:

If you hover the mouse over document.getElementById you can see that the returned type is null | HTMLElement

I've rewritten your object as a class, because in object notation the colon is used to pass the value, not the type: const obj = {a:3}

class FormValidation {
    submitBtn: null | HTMLButtonElement

    mapDOM() {
        this.submitBtn = document.getElementById('js-btn-submit') as HTMLButtonElement;
    }
}

const f = new FormValidation()
f.mapDOM()


Background task with instant abort capability in c#

Disclaimer: Don't do that

Aborting threads usually means that the thread will terminate and will no longer be available to do anything else. While that maybe exactly what you want there are some scenarios where you have to be really careful about aborting threads namely a shutdown process i.e (where you have to do some work before exiting).

It is also worth noting that you are trying to abort a thread from the thread pool, because the TPL uses the thread pool. And those threads should be always ready to get work done. If you abort one of the threads in the worst case then the thread pool will need to create another thread to replace it, meaning that you will have a cycle of threading creation and abortion.

Code Review

You are creating a CancellationTokenSource inside the working thread, meaning that only the working thread will be able to cancel/abort itself.
Cancellation is a mechanism meant to be used across multiple threads, because a thread is already responsible for it's own life-cycle.
So you should use other kinds of mechanisms, i.e time-based using Stopwatch, to determine if you want to leave or not.

If you want to know how to effectively cancel an operation please head to my other answer here

EDIT

Unlike you, I don't think there is something overly complicated on your code.
There should be a minimal set of comprehensible code to achieve some functionality and .NET API AFAIK doesn't have a simpler way to do it. However I would like to point two small things:

You could have used a using statement for System.Threading

You could have used meaningful names. I won't complain too much about cts because sometimes I also use that but I acknowledge that cancelSource is better. However ctcould be easily replaced by at least token or if you want to go a step further cancelToken. And t could be simply threador yet again currentThread.

Another alternative could also be to don't have that many variables I wouldn't mind to write cancelSource.Token and Thread.CurrentThread, if they happen to be used just once.


Optimize performance of flatten function in python

One avenue to try improve your speed is to use the Pythonic principle that it's Easier to Ask Forgiveness than beg Permission. This means that instead of testing your data every single time, you should just assume that it's in the correct form and catch the errors when you've gotten it wrong.

For instance, you test your dictionary here:

if isinstance(v[0], dict):
    counter = 0
    for entry in v:
        new_count_key = new_key + sep + str(counter)
        items.extend(self.flatten(entry, new_count_key, sep=sep).items())
        counter += 1
else:
    items.append((new_key, v))
    if new_key not in self.key_list:
        self.key_list.append(new_key)

What if instead you just assume that you have a list, and then work with the dictionary if you don't:

try:
    items.append((new_key, v))
    if new_key not in self.key_list:
        self.key_list.append(new_key)

except AttributeError:  # Is a dict, not a list
    counter = 0
    for entry in v:
        new_count_key = new_key + sep + str(counter)
        items.extend(self.flatten(entry, new_count_key, sep=sep).items())
        counter += 1

What you're doing here is attempting to append to items with the assumption that it's a list. If items is a dictionary and not a list, then your except catches the AttributeError that's raised and it will run the code for the dictionary format instead.

The advantage to this, is that you're not detecting the type, you're just catching when it's not a list. That means you spend no time calculating the datatype, you only need to spend time catching the exception when it comes up. This works best if the except catches the rarer datatype. So with my proposed solution, if most items will be lists then you'll save a lot more time than if most items end up being dictionaries.


Keeping history of Django model (by using memoization?)

Ok, after googling a bit more, I found a possible solution: django-simple-history:
from django.db import models
from core.models import User
from simple_history.models import HistoricalRecords

class Spam(models.Model):
    user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='spam')
    ham = models.CharField(max_length=10)
    eggs = models.IntegerField()
    history = HistoricalRecords()

This seems to do exactly what I need to do. I'll test it.


is there any possibility of optimizing the above code

Eliminating unnecessary processing will help...

Remove Needless if

if (!row.IsNull(col))
{
    b_dataValue = true;
    if (b_dataValue)
    {
        // ...
    }
    else
    {
        dt.Rows.Remove(row);
    }
}

b_dataValue is always true, so the if is not necessary, and the else will never execute. So ...

if (!row.IsNull(col))
{
    b_dataValue = true;
    {
        // ...
    }
}

Move If's to the top

If the table is null or has no columns then there's no point in going on. So check for this up front. This removes 2 nesting levels.

private void ModifyDataTable(DataTable dt) {
    if (dt == null) return;
    if (dt.Columns.Count <= 0) return;
    // ...
}

Reference by Table Name and Remove more If-ing

I'm guessing that your code is handling at least 2 different tables. If this is true then based on the name call "thisTable" code or "thatTable" code. Then you can eliminate all that checking for column names because you know they are there. And it eliminates another layer of if

private void ModifyDataTable(DataTable dt) {
    if (dt == null) return;
    if (dt.Columns.Count <= 0) return;
    if (dt.TableName == "thisTable") DoThisTableStuff(dt);
    if (dt.TableName == "thatTable") DoThatTableStuff(dt);

    // Knowing what table we're dealing with, code like this
   if (col.ColumnName == "report_data0") row[col] = rowreport_data0Sum + "%";
   else if (col.ColumnName == "report_data1") row[col] = rowreport_data1Sum + "%";

   // could turn into this
   row["report_data0"] = rowreport_data0Sum + "%";
   row["report_data1"] = rowreport_data1Sum + "%";

}


PageObject implementation (CoffeeScript, CasperJS)

Do we need to attach a casper reference to the PO class?
By using the module pattern you inject the dependency anyway.
Here is the P0 class with a tiny refactoring:

module.exports = (casper) ->

  class PO
    constructor: (@name, @selector, mixin={}) ->
      if PO[@name]?
        throw new Error "Failed creating PO #{@name}: ..."
      PO[@name] = @
      @[key] ?= val for own key,val of mixin

    waitUntilVisible: (cb) ->
      casper.waitUntilVisible @selector, cb
      @

    next: (po, cb) ->
      t0 = Date.now()
      msg = "Switching to PO #{po.name}"
      casper.log msg, 'debug'
      po.waitUntilVisible (err) ->
        casper.log "#{msg}: done in #{Date.now() - t0}ms", 'debug'
        cb err, po

Then you would use it like this:

casper = require 'casper'
PO     = require('MyModuleName') casper

new PO 'navbar', '',
  tabs: {}
  logout: (cb) ->
    casper.click '#logout'
    casper.waitFor (=> not @haveLogin()), (err) -> cb err, PO.login

  haveLogin: (cb) ->
    result = nick is casper.evaluate -> ($ '#current-user-nick').text()
    cb? result
    result

  addTab: ({name, switchSelector, readySelector, po}) ->
    @tabs[name] = arguments[0]

  toTab: (name, cb) ->
    cb new Error "Navbar tab #{name} not known" unless name of @tabs
    tab = @tabs[name]
    casper.click tab.switchSelector
    casper.waitUntilVisible tab.readySelector, (err)-> cb err, PO[tab.po]

On extending the class you can skip the constructor (as long as it's the same like the one of the superclass) and attach the PO['navbar'] to the prototype.

class PON extends PO
  navbar: PO.navbar


Dynamic programming solution for cross river algorithm

You have a small bug. Consider a river like ******.. such that the last spot is not landable. You can still cross the river by jumping beyond the end of the river from the last landable stone, but your code thinks that you cannot.

The solution to this is to do a top down DP. Define dp(position, speed) to be true if you can cross the river starting from position with given speed. You want to find dp(0,0), which you can do easily with memoised recursion.


Sure there is! You're looking for Optional.map

  If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

Optional<Path> getSrcDir() {
    return getProjectDir().map(p -> p.resolve("src"));
}


Pigeon and grain problem: find time until all the grain is eaten

Basically we're looking for the smallest value of \$T\$ which satisfies the discrete equation

$$ \left\lfloor {T \over x_1} \right\rfloor + \left\lfloor {T \over x_2} \right\rfloor + \dots + \left\lfloor {T \over x_n} \right\rfloor \ge m $$

where \$\lfloor {x \over y} \rfloor\$ is the floor division operation (// in Python). So we know the regular division operation (/ in Python) will also be a valid solution to this, albeit not necessarily with the smallest possible \$T\$:

$$ {T \over x_1} + {T \over x_2} + \dots +  {T \over x_n}  \ge m $$

If we factor out the \$T\$ time value, we see this is just an inequality of the form:

$$ \mathrm{Time} × \mathrm{Rate\ of\ consumption} \ge \mathrm{Amount\ consumed} $$

and thus

$$ \mathrm{Time} \ge {\mathrm{Amount\ consumed} \over \mathrm{Rate\ of\ consumption}}$$

We know the rate of consumption and amount consumed, and so by refactoring the earlier inequality we get this:

$$ T\left( {1 \over x_1} + {1 \over x_2} + \dots +  {1 \over x_n} \right) \ge m $$

and thus

$$ T \ge {m \over \left( {1 \over x_1} + {1 \over x_2} + \dots +  {1 \over x_n} \right)} $$

You can use this as a heuristic which will get you close to your desired value of \$T\$, now your search space just needs to check values greater than the above result. Start by

T = int(M / ((1. / xs).sum()))

Then iterate upwards to the correct value using your method of choice. How about filling the smallest available remainder to the next multiple? Like so:

while True:
    v = (T // xs).sum()
    if v >= M:
        break
    T += (xs - T % xs).min()
return T

I'm sure there's a closer-to-closed-form solution to this.


Polynomial multiplication using Karatsuba method

Algorithmic complexity is not a good indicator of real-world performance
When you have to choose between an \$\mathcal{O}(N^2)\$ or \$\mathcal{O}(N^{1.58})\$ algorithm, you would think that the latter is faster, however that is only true for sufficiently large values of \$N\$. In practice, unless you have more than a thousand digits to multiply, the simple \$\mathcal{O}(N^2)\$ algorithm is faster.
Don't make the inputs of equal length
If you want to multiply a polynomial of degree 100 with a polynomial of degree 1, then your program will expand the latter polynomial to degree 100, and then do the multiplication. But most of the work is now wasted on multiplying things by 0. Try to make your algorithm work for vectors of different lengths.
Avoid creating unnecessary intermediate results
If the goal is purely to get the XOR of the coefficients of the product, then you don't actually need to store the product before calculating the final result of the XORs. Instead, with a trivial algorithm, you can just simply do:
int result{};
for (auto i: a)
    for (auto j: b)
         result ^= i * j;

This avoids creating a temporary vector, which requires heap memory allocation, and avoids an additional pass over the temporary result to get the final answer. Again, this doesn't reduce algorithmic complexity, but it does reduce how many cycles you have to spend for each iteration of the \$\mathcal{O}(N^2)\$ algorithm even further.
Use a hybrid approach
In your implementation of Karatsuba's algorithm, you have this line:
if (deg == 1) return {a[0] * b[0]};

Knowing that for smaller vectors, a naive algorithm is actually faster, you can replace this line with:
if (deg < CUTOFF)
    return naive_product(a, b);

Where you set the constant CUTOFF to some value that you have to determine experimentally. This approach is similar to those taken by state-of-the-art sorting algorithms, which typically also use a divide-and-conquer approach and when the problem gets small enough, they will use insertion sort.
Pass vectors by const reference
Most of your functions like prod(), sum(), and so on, take parameters by value. This is very inefficient, since it means a copy of the  vectors used as input arguments will be made. Pass them by const reference instead, it's as simple as:
vector<int> sum(const vector<int> &a, const vector<int> &b) {
    ...
}


Eliminate for loops in numpy implementation

That W was tricky... Actually, your blocks are pretty irrelevant, apart from getting the right slice of W to do the np.dot with the corresponding X, so I went the easy route of creating an aligned_W array as follows:

aligned_W = W[:, idx2, idx1]

This is an array of shape (2, rows) where rows is the number of rows of your data set. You can now proceed to do your whole calculation without any for loops as:

from numpy.core.umath_tests import inner1d
pred = inner1d(X, aligned_W.T)
sigm = 1.0 / (1.0 + np.exp(-pred))
loss = (sigm - 0.5) * curr_y
cost = np.sum(loss)


Creates a menu and sidebar in Google Spreadsheets

1. Testing:

Although your functions don't return a value and they catch any error that is thrown, the functions do log whether the call was successful or not. You could use the Logger to test if they fail like so:

Logger.clear();
ui.showSidebar();
var string = Logger.getLog();
if (string.indeOf("(fail)") === -1) throw "test for 'showSidebar' failed";

Note: If your unit tests are run in the script editor some of the third party functions could throw errors that wouldn't occur when called from the spreadsheet. The ones in your current functions are all fine last I checked, but function calls like SpreadsheetApp.getActive() cannot be made from the script editor.

Writing wrapper classes would be the safest way to ensure that your functions are correct, but that assumes that your wrappers and mocks are perfectly written. You have to consider whether the work it would take to write/debug/test the wrapper and mock classes is worth the value of having unit tests for your functions--especially since there are currently only two and they are rather small.

2. OOP in Google Apps Script

Where to call your constructor

Declaring variables in the global scope is dangerous since Google doesn't offer specifics on the order that it's interpreter/compiler (who knows which) reads the code. Basically things like:

var UI = function () {}

and

UI.prototype.showSidebar = function () {};

and

var ui = new UI();

aren't guaranteed to be executed in the intended order, specifically if they're in separate script files. If you wish to dabble in this dark art (who doesn't?), please note the following:

Functions are hoisted
The rest of the code appears to be executed in the order that your script files were created

I would recommend making one of your script files a sort of "main" file; make this file the only place you preform logic on the global scope to ensure that all the global logic is executed in the intended order.

Note: Global logic is executed every time you execute a script.

Constructor and Prototype in Google Apps Scripts

The way your code creates the UI class depends on global logic. If you declare a UI instance at the global scope in a separate script file, the UI class or it's prototype might not yet be defined.

A way around this would be to use a factory function instead:

function createUI() {
    return {
        createAddonMenu : function () {},
        showSidebar : function () {}

    };
}

The factory function will be hoisted and all is well in the global scope.

To many parameters

Consider passing a single object for your constructor's parameter:

function createUI(settings) {
    var menuName = settings.menu.name;
    var menuFunction = settings.menu.action;
    // ...
}
var ui = createUI({
    menu : {
        name : "Show",
        action : "showSidebar"
    }
    sidebar : {
        // ...
    }
});

This gives names to the parameters at the caller's end, it makes it so the order of the parameters is irrelevant, and it makes optional values easier to work with since the order of other parameters won't be affected if one is omitted. When using this technique you may want to validate that all required parameters exist inside the parameter object.


Some things to note;

When doing time related things in C++, use std::chrono, not clock().
Your log will not work if it's used in multiple files. Instead of being in a .h file, put the definition of the logger in a cpp file and build both together.
Use include guards for header files

    #ifndef LOG_H
    #define LOG_H

    // Code

    #endif

Define constructors and use them properly and get rid of configure.

    Log(std::string fileName, bool printToConsole, bool saveToFile) :
        logFileName(fileName),
        print(printToConsole),
        save(saveToFile)
    {
    }

Do not use underscores for naming things. General rules for c++ are class names are PascalCase and functions are camelCase.
std::cout is slow, consider using sprintf to make it faster.
Don't write to a file every time you call log. Opening files and writing to them is slow. Consider writing to the file on a timestamp or aggregating a few logs before writing them.


Implementation of a Singularly LinkedList

C++ is not Java. You may safely get rid of all this->.
The client doesn't need to know about Node. Make it an inner class of the LinkedList.
The ~LinkedList() destructor is missing. You should also consider (or prohibit) the copy constructor, operator=, and move constructor.
add(int data, int position) may silently leak memory. If the position is too large, the created node is not linked into the list, and is lost. Also, there is no way to prepend a node.
I don't like the temp_head approach. Better leave the head alone, and iterate using a cursor variable, e.g.:

void LinkedList::print() {
    Node * cursor = head;
    while (cursor) {
        std::cout << cursor->data << '\n';
        cursor = cursor->next;
    }
}

At least, there is no need to restore head.

Ditto for add.


Improvements with caesar cipher encryption

Just a couple of small things you could improve/change on your code:

Unnecessary function/print statement. You can just do text = input('What message ... encrypt?\n') instead of making an extra function for it an using a seperate print statement.
The same goes for the input statement in the shift function, you can put the text of the print statement inside of the input.
Unnecessary default value for variable.
In the shift function you assign the value 0 to the variable key on forehand. But as you never use it outside the while True statement this is unnecessary. This line can be removed.
'Magic numbers'. Inside the encrypt function you use the ascii codes 65, 26 and 97 to quickly convert the characters. While their meaning might be obvious to you (and in this trivial case to most people) it is never a good idea to do this. It is cleaner to make a variable on top of your program in uppercase defining the value. So something like: UPPER_ASCII_SHIFT = 65 and then using that variable in the rest of the code. This way it is much easier to read for someone else. This is also a big theme in the cs50 course where this programming problem is originally from.
Try choosing clearer names for variables that immediately clarify their use and content. Something like hidden is a bit ambiguous, maybe encrypted_string is better? Also try to avoid single letter variable names like s, but rather call it something like shift_distance.


I am not a c# programmer.

Firstly, you use a for each and a nested for loop, but both of these are iterating through the same List. For consistency (and for the next comment to make sense), I suggest that you use for loops.

for (int i = 0; i < periods.Count; i++)

You could start i not from 0. but from your current location + 1 in the outer loop. The logic behind this is that you have already compared the pairs of periods previous to this - no need to double handle. Hence why using similar for loops will make this easier - you will be counting where you are in the List in the outer loop.

Making this small change means that if (Id != periods[i].Item1 is no longer needed - reducing one nesting level in the code.

As a 'meaningful name thing', I would call commonStartingDate and commonEndDate overlapStart and overlapEnd respectively - this is more descriptive of what you mean.
overlapStart = max(period1.Start, period2.Start)
overlapEnd = min(period1.End,period2.End)

Error checking: check that Item2 is always less than Item3 (and fix if not), otherwise your logic will be broken.

You could simplify var elapsedPeriod = commonEndDate - commonStartingDate and the following code by using:

int elapsedPeriod = (int)(commonEndDate - commonStartingDate).TotalDays

May not look simpler above, but in the next block:

                if (elapsedPeriod > periodInDays)
                {
                    periodInDays = elapsedPeriod;
                    firstId = Id;
                    secondId = tempId;

You don't use elapsedPeriod for anything else.

The main logic is good - I remember having to solve this problem 25 years ago when developing an accommodation booking database.


Simple dice roll using std::string as dice notation

Bug

Your code has an integer-division/multiplication problem/bug.

Consider the dice-roll specification 10d10+0.

Your code will parse this down to:

string dicePart1 = "10";
string dicePart2 = "10";
string dicePart3 = "0";

and this will be used as:

int add = toInt(dicePart3);
roll = toInt(dicePart1) * (rand() % toInt(dicePart2)) + add

At face value, this may be OK, but, in reality, the calculation boils down to:

roll = 10 * (rand() % 10) + 0;

This will only ever be able to produce 10 results, 0, 10, 20, 30, ...., 90, which really is not what you want.

You really should do this as a loop, or as a floating point operation.... the loop seems to be easier:

roll = toInt(dicePart3);
for (i = toInt(dicePart1); i > 0; i--) {
    roll += (rand() % toInt(dicePart2));
}

Second Bug

In addition to the bug I pointed out above, I have actually identified a second bug. Dice are always 1-based.... you cannot roll a '0'. So, the method would actually have to be:

roll = toInt(dicePart3);
for (i = toInt(dicePart1); i > 0; i--) {
    roll += 1 + (rand() % toInt(dicePart2));
}

Discussion on distribution...

You may be tempted to be more efficient and use the function:

int p1 = toInt(dicePart1);
int p2 = toInt(dicePart2);
int p3 = toInt(dicePart3);

roll = p1 + (rand() % (p1 * p2)) + p3;

The above will create a result that is distributed in the correct range.... but the actual distribution curve is flat.... the odds of a 10d10+0 being 10 is the same as it being 50.... but, in reality, there are many ways to throw a 50, but only 1 way to throw a 10. As a result, the roll-value of 10d10+0 is not evenly distributed in the range 10 ... 100. You need to use a method where each dice is rolled individually.

int p1 = toInt(dicePart1);
int p2 = toInt(dicePart2);
int p3 = toInt(dicePart3);

....

roll = p3;
for (i = p1; i > 0; i--) {
    roll += 1 + (rand() % p2);
}

The above will, for 10d10+0 produce values in the correct range 10 ... 100 and the value frequencies will be distributed normally, as expected.


Dict initialization and reuse
This:
ref = dict()
ref['I'] = 1
ref['V'] = 5
ref['X'] = 10
ref['L'] = 50
ref['C'] = 100
ref['D'] = 500
ref['M'] = 1000

should use a dict literal:
ref = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
}

You should declare this at the top of the program, so that this:
'[^IVXLCDM]+'

can become
'[^' + ''.join(ref.keys()) + ']+'

and this
'Roman Numerals may contain only the characters I, V, X, L, C, D, M'

can become
'Roman Numerals may contain only the characters ' + ', '.join(ref.keys())

No-op continue
This:
    else:
        continue

has no effect and can be deleted.
Booleans
bad should use True and False rather than 1 and 0.


Show time in format yyyy-MM-ddThh:mm:ss.SSS

Don't reinvent the wheel, this is java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME.

long time = System.currentTimeMillis();
ISO_LOCAL_DATE_TIME.format(Instant.ofEpochMilli(time).atZone(ZoneOffset.UTC))
// "2017-03-07T12:09:04.374"


My first reaction is that your click handler is doing way too much work on its own.  You should break up the code into smaller methods to make it easier to maintain.

Move all the OpenFileDialog setup to the designer file.  This will make it a field rather than local variable, preventing unnecessary object creation when a user clicks Add multiple times.  Additionally, it will wire-up the proper Dispose call for you.
Take the code for opening the files and put it into a separate method.
Split off your worker event handlers into class methods rather than anonymous methods, better separating out method responsibilities.

Other things I would do:

Pass the filenames to the BackgroundWorker in its RunWorkerAsync(Object) overload.  This prevents synchronization issues if a user clicks add while the worker is still running.
Folowing the Single Responsibility Principle, you should move the file testing into the ListBoxFile class or some other helper class.  UI views should not typically handle I/O.
Make ListBoxFiles._files non-static.  If you want singleton behavior for some reason, you can keep a static reference to a ListBoxFiles object.  Providing instance-based methods but backing them with a static collection could be a bit jarring to callers, failing the Principle of Least Surprise.
Instead of using Stream, it may be more clear to use File.OpenRead(string).
With either Stream or File.OpenRead, you need to dispose the streams
Instead of raising an add event on ListBoxFile, you should instead data bind your list control to a BindingList<T>.  That will handle automatically updating your control as items are added/removed.


That's a lot of shell commands to do very little.

You could replace all those shell commands to get the equivalent effect with just this:

rm ~/.bash_history; HISTFILE=

Let me explain step by step why this is equivalent:

cat /dev/null > ~/.bash_history - truncate the file. Exactly the same as the shorter > ~/.bash_history. This is pointless, because later you delete the file anyway.
history -c - clear the history. Pointless because later you delete the file anyway
history -w - write the content of the history to the file. Pointless because later you delete the file anyway
rm -r ~/.bash_history - delete the file, recursively. The recursive flag is pointless, as the history file is never a directory
exit - This is pointless, as the system function will exit automatically anyway

All this can be reduced to what I gave above, by benefiting from the fact that if HISTFILE is unset, history is not saved anywhere.

Btw, I don't understand why you need a gnome terminal at all. I think you can simply remove that special treatment.

Lastly, using system is generally not recommended, it should be avoided as much as possible. If you must use it for some reason, you should call commands by their absolute paths, otherwise the program will be vulnerable to path injection attacks.


As you probably noticed, the slowdown happens when n is large and k is close to n. If it is slower than it should be, it is likely because it is doing unnecessary work. Lets have a look at the case where n=5 and k=3, and go to the point in the execution of your program where arr[0] = 1 and index = 1. In the for-loop in subset(), you are looking at all possible values from start = 2 to n = 5. However, not all values will actually result in valid solutions. Here is a list of all {1, i} you check, and which subsets are possible:

{1, 2} -> {1, 2, 3} {1, 2, 4} {1, 2, 5}
{1, 3} -> {1, 3, 4} {1, 3, 5}
{1, 4} -> {1, 4, 5}
{1, 5} -> no solutions

As you can see, {1, 5} does not have any possible subsets. Or put otherwise, 5 is too large a number at pos[1] to give any solutions.

Instead of trying all numbers from start to n, try to find out what the actual maximum is that will still give solutions.


I have found a couple of things that could help you improve your code.

Avoid the use of global variables

I understand that it's just partial code so far, but it's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable as with sudoku in this code.

Don't use system("pause")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++. In this case, a better alternative would be getchar().

Be careful with char and int

Your chrton function returns an int and then stores it in a char-sized location.  Better would be to return char, since that's how sudoku is defined.

Consider using unsigned char for subscripts

It's not technically wrong, but you may wish to use unsigned char for the type of x and y.  It eliminates a class of errors that can occur if the array subscript is a negative number.  This is a fairly minor point, however.

Consider using more idiomatic C

While your use of and and not is not techncially wrong, because you have correctly included the iso646.h header, you should be aware that many experienced C programmers will be unfamiliar with these operator alternatives, and so if others read your code, it might be an impediment to their understanding of the code.  Similarly, your unusual formatting of if statements as one-liners is likely to seem a bit strange to experienced programmers.

Consider separating input and output

Right now, the main function issues a prompt, reads in the sudoku board and then prints it out as each character is read.  A more modular (and likely more maintainable) approach would separate these into separate functions.

Consider returning 0 instead of 1

A non-zero return value is interpreted as an error condition on most operating systems.  Normal program exit should return 0 or EXIT_SUCCESS or simply omit it, because the compiler will automatically insert the equivalent of return 0; at the end of main.


String search algorithm for finding if a long list of long strings string exists in a similarly sized haystack

In the post you write:

  I also believe the in operator is inefficient because it is using the naïve method of searching the string.

But if you look at the implementation of Python's in operator for strings, you find that it calls the FASTSEARCH function, which is "based on a mix between Boyer–Moore and Horspool".

The problem of searching many times for strings in a collection of documents is known as full-text search. The approach in the post is to search for the string in each document in turn: this scales linearly with the number and length of the documents. To improve on this scaling behaviour, you need to preprocess the collection of documents into an index. (Note that this only helps if you are searching many times—if you are searching only once, then you can't do better than searching each document.)

Here's a simple demonstration of the full-text search approach:

from collections import defaultdict

class SearchIndex:
    "A full-text search index."

    def __init__(self):
        # Mapping from word to set of documents containing that word.
        self._index = defaultdict(set)

    def add(self, document):
        "Add document to the search index."
        for word in document.split():
            self._index[word].add(document)

    def search(self, query):
        "Generate the documents containing the query string."
        candidates = min((self._index[word] for word in query.split()), key=len)
        for document in candidates:
            if query in document:
                yield document

This works by building a mapping from words to the sets of documents containing each word (an "inverted index"). When a document is added to the index, it is split into words by calling str.split, and the document is added to the mapping for each word. This is conveniently implemented using collections.defaultdict.

To search for a string, the string is also split into words, and the index consulted for each word. The rarest word (the one mapping to the fewest number of documents) is used to get a set of candidates, and then each candidate is searched for the entire string.

This is a very simple approach and there are many refinements you can make. In particular, if you are going to be making queries of the same set of documents over a long period of time then you will want to make your inverted index persistent, and for that you will want a full-text search engine or database.


Speeding up OpenCL matrix-vector multiplication

Ok, so I figured out what I was doing wrong.  Basically I was completely misunderstanding the way the work-groups and work-items were supposed to break up.

What I have in the code in my original post is 1 thread for each element of the matrix A, and then I broke each row of this matrix up into work-groups of size P.

What I was supposed to do instead was have P threads per row, which is a total of (M, P) threads, and then collect each row into a single work-group (of size P).  So instead of having N/P work-groups of size P per row, I now only have a single work-group of size P for each row.  Hopefully that makes sense to everyone.

So here is the corrected code.  I didn't put it into functions this time, so just run the script as is.  The script includes both mvmul1 and mvmul2 from that website I linked to in my original post.

using OpenCL
const cl = OpenCL
srand(1)

M = Int32(30)
N = Int32(300)
P = Int32(30)
A = rand(Float32, M, N)
x = rand(Float32, N)

mvmul1 = """
kernel void mvmul1(int M,
                        int N,
                        const global float *A,
                        const global float *x,
                        global float *y)
    {
        int i = get_global_id(0);
        float acc = 0.0f;

        for (int j=0; j<N; j++)
        {
            acc += A[M * j + i] * x[j];
        }

        y[i] = acc;
    }
"""

mvmul2 = """
kernel void mvmul2(int M,
                        int N,
                        int P,
                        const global float *A,
                        const global float *x,
                        global float *y)
    {
        int i = get_global_id(0);
        int j = get_global_id(1);

        local float sums[$(P)];
        float sum = 0.0f;

        for (int q=0; q<(N / P); q++)
        {
            sum += A[M * (j + P * q) + i] * x[j + P * q];
        }

        sums[j] = sum;
        barrier(CLK_LOCAL_MEM_FENCE);

        if (j == 0)
        {
            float sumtotal = 0.0f;
            for (int p=0; p<P; p++)
            {
                sumtotal += sums[p];
            }

            y[i] = sumtotal;
        }
    }
"""

device, ctx, queue = cl.create_compute_context()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx, :profile)

"""mvmul1"""

A_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=A)
x_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=x)
y_buff = cl.Buffer(Float32, ctx, :w, M)

program = cl.Program(ctx, source=mvmul1) |> cl.build!
kernel = cl.Kernel(program, "mvmul1")
evt = cl.call(queue, kernel, M, nothing, M, N, A_buff, x_buff, y_buff)

tout = round(evt[:profile_duration] * 1e-9, 6)
yout = cl.read(queue, y_buff)
t = @elapsed y = A * x
println("mvmul1 is ", round(t / tout, 3), " times as fast as Julia. ", isapprox(yout, y))

"""mvmul2"""

A_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=A)
x_buff = cl.Buffer(Float32, ctx, (:r, :copy), hostbuf=x)
y_buff = cl.Buffer(Float32, ctx, :w, M)

program = cl.Program(ctx, source=mvmul2) |> cl.build!
kernel = cl.Kernel(program, "mvmul2")
evt = cl.call(queue, kernel, (M, P), (1, P), M, N, P, A_buff, x_buff, y_buff)

tout = round(evt[:profile_duration] * 1e-9, 6)
yout = cl.read(queue, y_buff)
t = @elapsed y = A * x
println("mvmul2 is ", round(t / tout, 3), " times as fast as Julia. ", isapprox(yout, y))

You'll notice that for M < N, mvmul2 does well while mvmul1 doesn't.

But if you change M, N and P such that M >= N, then mvmul1 does well while mvmul2 doesn't, interesting


Do not use namespace std; It is a bad practice that you should stop as soon as possible.
Do not trust magic macros like speedup. For such small code fragments that are repeated only few time it is often way better to write it out.
use std::size_t instead of unsigned long long int
You already know the maximum number of chewing gums, So reserve space for your vector early to avoid reallocations. You can always later call shrink_to_fit to free the unneded memory.
Use descriptive names even in challenges that only call them N or K. N is the number of gums so call it numGums or whatever you want. This improves readability quite a bit. This also goes for example hardness, which is a vector so it should be plural e.g. hardnesses.
Declare variables when you need them. This creates more or less independent code paths that might late be put into functions more easily.
In your loop you use it++. This requires a copy of it before the increment. Especially for iterators and friends ++it is more efficient as it does not involve the copy.
Try to separate command flow with a whitespace, e.g. for (). This helps to discriminate it from normal functions.
EDIT C++11 knows the language construct nullptr, use it rather than NULL

The early portion of our code would then look like this

std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::size_t numGums, chewingThreshold;
std::cin >> numGums >> chewingThreshold;

std::vector<std::size_t> hardnesses;
hardness.reserve(numGums);
for (std::size_t gum = 0; gum < numGums; ++gum) {
    std::size_t hardness;
    std::cin >> hardness;
    if (hardness < chewingThreshold) {
        hardnesses.push_back(hardness);
    }
}
hardnesses.shrink_to_fit();

If you look at this code in a year, you will still understand most of its meaning, without having to search for documentation.

Avoid single line command flow statements like if (*it+*it2 < K) numPairs+=1; as much as possible. This completely breaks readability of your code as you know have to check every for and if statement if it has a coomplicated condition or hidden code or nothing at all.
Your code does work, but it is highly inefficient from a mathematical point of view. As a hint I would suggest you think about how to utilize a std::map for this problem.


Implementation
Better is a nebulous concept. The first one assumes that both arrays are the same length and fails to play all audio otherwise, so I'll say that's worse. I would suggest pulling the subarray computation into a method.
private void playAudio(final byte[] audio) {
    this.player.playBlock(Arrays.copyOfRange(audio, 4, audio.length - 4));
}


Is this a correct knockout ViewModel setup?

Overall, it looks really good and serves as a pretty great model of what Knockout models should look like, but, internally there are some strange things here like arrays that you are using [0] only on (this could be the result of poor data format via your backend web services) and some ambiguity between Panes, Pane, and PaneOptions.

(1) Use the guard or ternary operator to create defaults

This will help you avoid some of these logic blocks in all of your constructors.

(2) Fix ambiguity with singular and plural constructors (Planes, Plane)

The relationship between Panes and Pane are a little strange! In the Survey constructor, you are create a variable called panes (this.panes) and then instantiating and passing a new Pane to which you are passing an array of panes? A little bit recursive. In the Pane constructor I would not expect to take in panes in the arguments. I think your intention is for the Survey to create an array of panes, like this:

function Survey(name, panes, tester)
{
  var _this = this;

  // 1
  this.name = ko.observable(name || '');
  // 2
  this.panes = ko.observableArray();
  this.tester = ko.observable(tester);

  if(panes){
    panes.forEach(function(pane){
      _this.panes.push(new Pane(pane));
    });
  }
}

(3) Fix improper use of arrays with fixed [0] element

Why is Panes plural in the Pane constructor, if you are only using array item 0? I think the Pane constructor should just take in an parameter like options which would be used to return an individual pane:

function Pane(config)
{
  this.type = ko.observable(config.type);
  this.head = ko.observable(config.head);
  this.content = ko.observable(config.content);
  this.options = ko.observableArray([new PaneOptions(config.options)]);

  /*
   * You could return "this" but in JS that is the default behavior.
   */
}

Additionally, this will help you avoid JS errors when you might attempt to access a null array. For example, if panes in panes[0].options were null, you would have an error at pane[0] before you even got to the options property.

I am not sure why you are operating on options[0] here - at the point when you are instantiating a Pane, you should be passing in a config (see above) which has an options property, which will most likely be an object like { data: "", target: "" } since that is what you are expecting in the PaneOptions constructor:

function PaneOptions(options)
{
  // Setup defaults with ternary operator
  this.data = ko.observable(options ? options.data : '');
  this.target = ko.observable(options ? options.target : '');
}

Applicable original code with numbered callouts corresponding to items above

function Survey(name, panes, tester)
{
  // 1
  this.name = ko.observable(name || '');
  // 2
  this.panes = ko.observableArray([new Pane(panes)]);
  this.tester = ko.observable(tester);
}

// 2
function Pane(panes)
{
  if (panes) {
    // 3
    this.type = ko.observable(panes[0].type);
    this.head = ko.observable(panes[0].head);
    this.content = ko.observable(panes[0].content);
    this.options = ko.observableArray([new PaneOptions(panes[0].options)]);
  }
  else {
    this.type = ko.observable();
    this.head = ko.observable();
    this.content = ko.observable();
    this.options = ko.observableArray([new PaneOptions()]);
  }
}

function PaneOptions(options)
{
  if (options) {
    // 3
    this.data = ko.observable(options[0].data);
    this.target = ko.observable(options[0].target);
  }
  else {
    this.data = ko.observable();
    this.target = ko.observable();
  }
}


Whether Scala or any other language, it's not a good sign when you have big blocks made of pasted/copied lines (tttFormat, board and atPlay).  There is some logical structure to those repeated lines and you should code that instead of copying lines.
There is a bug: the middle row is inverted (654 instead of 456).
The line asking for the player move should probably be in the while-loop.  Just my opinion.
To keep good "separation of concerns", the player input should be read in the main loop and passed to the method that updates the board.
The nextTurn followed by nextTurn at the end to get the winner is "hacky".


The key differences between a throttled function and a debounced function are that the throttled function can return a value because it is called synchronously and the debounced version cannot because it is used asynchronously.

You have lost that on your throttle implementation. I would at least make the following change:

Function.prototype.throttle = function (milliseconds) {
    var baseFunction = this,
        lastEventTimestamp = null,
        limit = milliseconds,
        lastresult;

    return function () {
        var self = this,
            args = arguments,
            now = Date.now();

        if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
            lastEventTimestamp = now;
            lastresult = baseFunction.apply(self, args);
        }
        return lastresult;
    };
};


The formula is elegant, and the approach is correct.
You have to be careful with complexities though. Specifically you have to be very clear about what \$n\$ is. Typically complexity is a function of the size of input (which is, provided that \$n\$ is a matrix dimension, \$n^2\$ itself), so I'd qualify your solution as linear. And since each element should be accounted for, no better solution is possible.
The asymptotic constant could be better. The problem doesn't ask to rotate the matrix; it is only asks to print the matrix as if it was rotated. In other words, building output is technically a waste of time. Use your formula to print elements as you enumerate them.


Particle in Cell: efficient data structure handling

If you have move push_back then you should also have emplace_back.

population.emplace_back(pos_x,pos_y,seed_type,10.1);

Erasing the individual means moving everyone that comes after. If you don't care about order then do a swap with back:

auto iter=population.begin();
//...stuff...
(*iter).cell_ptr->erase((*iter).cell_iter); // erase the ptr to the agent from the cell
std::swap(*iter, population.back());
population.pop_back();
//doesn't invalidate iter