Keyword classification in Scala... simple?

The posted code won't compile without a working definition of Keyword and PrepKeyword. And type is a reserved word so kwd.type isn't allowed (might be version dependent).
The code, as presented, is inconsistent or just plain wrong in its indenting but, other than that, it's reasonably clear in intent and presentation.
The logic is, perhaps, overly convoluted. I found that I had to go back and forth to see how output was built from input. I eventually decided that kwd.name was the key value from which most everything else flows. With that in mind I tried to rebuild the logic.
def preprocess(kwd: Keyword): Option[PrepKeyword] = {
  val fooName = "(?i)(foo)".r
  kwd.name.flatMap{
    case "name1"      => None
    case "myCategory" =>
      kwd.typ match {
        case 1 => Some(PrepKeyword(kwd, "GreatCategory", "Foo2"))
        case 2 => Some(PrepKeyword(kwd, "myCategory", "Foo2"))
        case _ => None
      }
    case fooName(fnm) => Some(PrepKeyword(kwd, fnm, "Foo1"))
    case nonFoo       => Some(PrepKeyword(kwd, nonFoo, "Foo2"))
  }
}

This, according to my tests so far, produces the same results. It builds the output in multiple places but in each case it's pretty easy to see how the input directed the output.


You're really overcomplicating it. The great thing about Joda Time is that it can do all the hard work for you. This simplified method will give the exact same output as your original Operation_Sum:

static String sumTimes(String time1, String time2) {
    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .minimumPrintedDigits(2)
            .printZeroAlways()
            .appendHours()
            .appendLiteral(":")
            .appendMinutes()
            .toFormatter();

    Period period1 = formatter.parsePeriod(time1);
    Period period2 = formatter.parsePeriod(time2);
    return formatter.print(period1.plus(period2));
}

Test cases I used on both your method and this new one:

@Test
public void testSum8Plus8() {
    String time1 = "08:00";
    String time2 = "08:00";
    assertEquals("16:00", JodaDemo.sumTimes(time1, time2));
}

@Test
public void testSum8Plus18() {
    String time1 = "08:00";
    String time2 = "18:00";
    assertEquals("26:00", JodaDemo.sumTimes(time1, time2));
}

@Test
public void testSum8Minus18() {
    String time1 = "08:00";
    String time2 = "-18:00";
    assertEquals("-10:00", JodaDemo.sumTimes(time1, time2));
}

In addition to the simplification, some other improvements:

Variables should be named camelCase (don't start with capital letter, don't use underscore)
Typical *Builder classes support a fluent interface, so instead of builder.someMethod(); builder.anotherMethod();, you can just chain the calls as builder.someMethod().anotherMethod();
Unit tests are good to let you make changes and confirm that everything is still working. It's also easier for code reviewers, so they can easily test refactored version of the code. Try to include more tests to cover all corner cases.

There were glaring logical mistakes in your original implementation. For example in this code:

if (time1.contains("-"))
{
    time1_out = time1.split(":");
    time1_out[0] = time1_out[0].replace("-", "");
    time1_out[1] = time1_out[1].replace("-", "");
    time1 = time1_out[0] + ':' + time1_out[1];
    sign_time1 = true;
}

This is (pretty much) equivalent to the simpler and better:

if (time1.contains("-")) {
    time1 = time1.replaceAll("-", "");
    sign_time1 = true;
}

That is, here, and in many other places in your code, you were doing a lot of operations that can be easily simplified to fewer operations.


Find most occurred number in sorted array of numbers

You should always question the question when given problems like this. For example, what if the input data is empty? What if there are two different values that appear the same number of times? etc. What if there are negative values?

Also, when dealing with problems like this its often best to separate the function doing the work, from the code presenting the result.

I would return an object from the function so that the "calling" code can look like:

var result = maxVal(data)
if (result.count) {
    console.log("NUM "+result.value+" occurred "+result.count+" times");
} else {
    console.log("No values in the data");
}

Then, I would also simplify your logic a whole bunch. You don't need to keep all those nested if statements.... You need just one test condition, and then an if/else condition...

function findMaxOccuredNum(nums){
    var result = {
        count: 0,
        value: 0
    };

    if (!nums) {
        return result;
    }

    var value = 0;
    var count = 0;

    for (var i = 0; i < nums.length; i++) {
        if (nums[i] != value) {
            count = 0
            value = nums[i];
        }
        count++;
        if (count > result.count) {
            result.count = count;
            result.value = value;
        }
    }
    return result;
}

function findMaxOccuredNum(nums){
        var result = {
            count: 0,
            value: 0
        };

        if (!nums) {
            return result;
        }

        var value = 0;
        var count = 0;

        for (var i = 0; i < nums.length; i++) {
            if (nums[i] != value) {
                count = 0
                value = nums[i];
            }
            count++;
            if (count > result.count) {
                result.count = count;
                result.value = value;
            }
        }
        return result;
    }

    function format(result) {
        return `Value ${result.value} & Count ${result.count}`;
    }
Result: <input id="output" type="text" cols="90">
<p>
<input type="button" onClick="alert(format(findMaxOccuredNum([0,1,2,3,4,4,5])));" value="[0,1,2,3,4,4,5]">
<input type="button" onClick="alert(format(findMaxOccuredNum([0,0,0,0,,1,2,3,4,4,5])));" value="[0,0,0,0,,1,2,3,4,4,5]">
<input type="button" onClick="alert(format(findMaxOccuredNum([-1,-1,-1,0,1,2,4,4,5])));" value="[-1,-1,-1,0,1,2,4,4,5]">
<input type="button" onClick="alert(format(findMaxOccuredNum([0,1,2,3,4,5])));" value="[0,1,2,3,4,5]">
<input type="button" onClick="alert(format(findMaxOccuredNum([0,1,2,3,4,4,5])));" value="[0,1,2,3,4,4,5]">
<input type="button" onClick="alert(format(findMaxOccuredNum([])));" value="[]">
<input type="button" onClick="alert(format(findMaxOccuredNum()));" value="null">


It is unnecessary to change the current directory in your python script. Instead you can just open the file with an absolute path - i.e.

madLibFileObject = open("C:\\MyPythonScripts\\madLib.txt")`

To avoid leaking files (madLibFileObject), it it a good idea to use a with statement whenever you open a file, which takes care of automatically closing it for you:

with open("C:\\MyPythonScripts\\madLib.txt") as madLibFileObject:
     madLib = madLibFileObject.read()

Using three regular expressions that each match one word is overkill for this task. It is instead better to use word.lower() == "verb"

for word in madLib.split():
    newMadLib.append(word)
    if word.lower() == "verb":
        x = input('Enter VERB:  ')
        newMadLib[y] = x
    elif word.lower() == "noun":
        x = input('Enter NOUN:  ')
        newMadLib[y] = x
    elif word.lower() == "adjective":
        x = input('Enter ADJECTIVE:  ')
        newMadLib[y] = x

Then, there is clearly quite a bit of code duplication in the above loop, so it should be shortened using a list:

PARTS_OF_SPEECH = ["verb", "adjective", "noun"]
for word in madLib.split():
    if word.lower() in PARTS_OF_SPEECH:
        newMadLib[y] = input("Enter " + word.upper())

Your y counter variable is a reimplementation of the enumerate built-in function, in addition to being poorly named. index would be a better name:

for index, word in enumerate(madLib.split()):

Full code:

PARTS_OF_SPEECH = ["verb", "noun", "adjective"]
with open("C:\\MyPythonScripts\\madLib.txt") as madLibFileObject:
     madLib = madLibFileObject.read()
newMadLib = []
for index, word in enumerate(madLib.split()):
     if word.lower() in PARTS_OF_SPEECH:
        newMadLib[index] = input("Enter " + word.upper())
newMadLib = ' '.join(newMadLib)
print(madLib)
print(newMadLib)


Even Fibonacci numbers under 4,000,000 (Project Euler #2)

Naming

var num1

That doesn't tell me what the variable is and does.  Is it the smallest Fibonacci number in the two needed to calculate the next?
Operators
Using spaces around your operators helps readability, which helps prevent bugs.
Scope
temp is only used in the while() loop, so you can reduce its scope.
Algorithm
The Fibonacci numbers go even/odd/odd/even/odd/odd... There is a good reason for this - they start with an even number (0), and an odd number (1). Even numbers plus odd numbers are odd numbers, so we get another odd number (1). Odd numbers plus odd numbers are even numbers, so we know this pattern will continue. With this knowledge, we only need to calculate every 3rd number.


Am I using Q the right way or is there a better way to do what I'm doing?

.then(q.nmcall(user, 'nextCount'))

is wrong. The nextCount call does return a promise (and starts its execution right away), while then does expect a [callback] function. You'd rewrite it to

.then(function(result_of_resetcount) {
    return q.nmcall(user, 'nextCount');
})

or shorten it with nfbind/nbind:

.then(q.nbind(user.nextCount, user))


Custom sorting function implemented as a jQuery plugin

Your code is nice and easy to understand. I'm going to break my review down into two sections: in the first section, I will suggest a different implementation, and in the second section, I will answer your questions.

New solution

In case you were not aware, JavaScript has a built-in function for sorting lists: Array.prototype.sort.

This function, basically, is used to take a list of data and sort it based on either it's built-in function, or a simple function you provide. This function takes two items from the array and returns either 1, 0, or -1 to tell sort how to place them in the array (the original array is mutated).

So, that being said, a much simpler way to sort these elements would be to do this:

// Sorts the items from greatest to least priority
$items.sort(function(a, b) {
    var aPriority = a.data("priority");
    var bPriority = b.data("priority");

    if(aPriority > bPriority) {
        // Note this is -1 despite aPriority being greater; -1 moves aPriority earlier in the list, sorting it greatest to least
        return -1;
    }
    if(aPriority < bPriority) {
        return 1;
    }
    return 0;
}

Not only is this simpler (and probably faster), it is also more idiomatic and easier to understand what is being done here.

Now that the native sort method is being used, there is no need for recursive placement. Just use a loop:

var positionElements = function($items, $container) {
    if (0 === $items.length) {
        return;
    }

    // ... $items sorting ...

    while($items.length > 0) {
        $container.append($items[0]); // sorted greatest to least
        $items = $items.not($items[0]);
    }
};

This is much simpler now, and is a bit faster now that there is no recursion because there is only two places where the call stack is touched, rather than two places for every item in the list.

Questions

  Is my algorithm is optimal in terms of performance, or is it just terrible?

There are a few places where this code is not quite optimal. Look at this flowchart of your code:

Iterate through entire list to find highest element
Place that element and remove it from the list.
Go to 1 until list is empty.

It's not very efficient to be iterating through the entire list every time as long as there are still elements inside it. If, for example, there were 10 items in the list, the first you would iterate through 10 items, then 9 items, then 8 item... until you've iterated through 55 elements.

And that's why sorting the array first before working with it will be much faster (in fact, the highest voted question on Stack Overflow is about why processing a sorted array is faster).

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

There are many unit testing frameworks out there. Honestly, I'm not that familiar with jQuery, so my suggestion may not actually be your best bet (although, the jQuery website does make a reference to a unit testing framework: QUnit).

A framework I would recommend is Cheerio. My main reason for this is because it allows to easily load HTML into a virtual DOM and perform any normal DOM operations on it. This means you could load some test components, run your sorting code on them, and use Cheerio to read the DOM and make sure they are properly sorted.


Your getters and setters would be for fields of the class, not passed in.  I'll use your two simplest ones as examples for you to work from.

public String getCustName(JTextField name){
    return name.getText();
}

public String getPhoneNum(JTextField phone){
    return phone.getText();
}

These methods make no sense if you think about them logically.  Your client code will pass in a JTextField that it already has, in order to invoke getText() on it?  Why wouldn't that code just do it itself?

Here's how getters and setters work:

private JTextField myTextField;

public String getMyTextFieldValue() {
    return myTextField.getText();
}

public void setMyTextField(JTextField newTextField) {
    myTextField = newTextField;
}

That's the general principle behind getters and setters.  You should be able to extend that logic to all of the other methods as well once you understand the logic.


The text-to-key problem is one that has multiple solutions. The Map solution is a good one, there's nothing wrong with it. There are two other algorithms that are good too. First, though, please convert the char-to-key to a function. Having such a big loop is a problem.

public static int charToKey(char c) {
    ... do something to return key ....
}

A switch statement is similar to your cascading if's, except it is neater, and faster:

switch (c) {
    case 'A': case 'B': case 'C':
        return 2;
    case 'D': case 'E': case 'F':
        return 3;
    ....
}

Note that I abuse the layout of the switch to have multiple chars on a line.... I sometimes do that for structured inputs like this. Also, note that a case block with a return statement does not need a break - that's really nice when putting switches in to functions - just return, don't break.

A second alternative to a Map, is a mathematical function. The math one is interesting.... because it is fast. It's not that readable, though.....

Consider your keys, most keys have 3 letters, but 7 and 9 have 4 letters. If we treat Z as a special case, we can think of 9 as having just 3, which leaves only key 7 with 4 letters. Now, if we lay those letters on to a number line, where each letter occupies just... 0.32 of a span (we choose 0.32 because 4 of them is just slightly less than 1), and we organize that P is aligned with 7.0 ..... and we also take the integer value of the result... we have:

    double span = 0.32;
    double offset = 7.0 - span * ('P' - 'A');
    for (char c = 'A'; c <= 'Z'; c++) {
        double val = offset + span * (c - 'A');
        int key = (int)val;
        System.out.printf("%s -> %.3f ==> %d\n", c, val, key);
    }

and that produces:

A -> 2.200 ==> 2
B -> 2.520 ==> 2
C -> 2.840 ==> 2
D -> 3.160 ==> 3
E -> 3.480 ==> 3
F -> 3.800 ==> 3
G -> 4.120 ==> 4
H -> 4.440 ==> 4
I -> 4.760 ==> 4
J -> 5.080 ==> 5
K -> 5.400 ==> 5
L -> 5.720 ==> 5
M -> 6.040 ==> 6
N -> 6.360 ==> 6
O -> 6.680 ==> 6
P -> 7.000 ==> 7
Q -> 7.320 ==> 7
R -> 7.640 ==> 7
S -> 7.960 ==> 7
T -> 8.280 ==> 8
U -> 8.600 ==> 8
V -> 8.920 ==> 8
W -> 9.240 ==> 9
X -> 9.560 ==> 9
Y -> 9.880 ==> 9
Z -> 10.200 ==> 10

Note how all the characters have valid values, except Z. Now, there's a trick with that... which is as ugly as anything, but it works really well.... key -= key/10 - subtract an integral 10'th of the value from itself.

What does this mean? Well, it means that your function can be (for valid input):

public static int charToKey(char c) {
    int key = (int)(2.2 + (c - 'A') * 0.32);
    return key - key / 10;
}

If you want to validate the input, something like:

char uc = Character.toUpperCase(c) - 'A';
if (uc < 0 || uc >= 26) {
    return 0;
}
int key = (int)(2.20 + uc * 0.32);
return key - key / 10;

Update

Since this became a benchmarking session comparing various options, and since a new option came up in discussions with @chillworld, it seems an update is in order.

First up, I was reminded that this:

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

is faster than:

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

I checked that, and, in fact, it is true. I consistently get the following benchmark times:

Task Keys -> Calc: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.2914
  Fastest  :   0.2749      Slowest  :   2.3255
  95Pctile :   0.3327      99Pctile :   0.4448
  TimeBlock : 0.315 0.285 0.292 0.285 0.284 0.280 0.293 0.283 0.299 0.297
  Histogram :   999     0     0     1

Task Keys -> Cached: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.2802
  Fastest  :   0.2665      Slowest  :   1.9090
  95Pctile :   0.3212      99Pctile :   0.4237
  TimeBlock : 0.298 0.275 0.284 0.276 0.276 0.269 0.284 0.274 0.283 0.284
  Histogram :   999     0     1

Where the different code paths are just:

public static int calced(String text) {
    int result = 0;
    for (int i = 0; i < text.length(); i++) {
        result *= 10;
        result += charToKey(text.charAt(i));
    }
    return result;
}

public static int cached(String text) {
    int result = 0;
    final int len = text.length();
    for (int i = 0; i < len; i++) {
        result *= 10;
        result += charToKey(text.charAt(i));
    }
    return result;
}

"Caching" the String length has a small (1% in this case) improvement in performance.

More interestingly, the idea @Chillworld had of creating a lookup array for each relevant character is much, much faster. His idea started off as:

private static final int[] cache = new int[91];
static {
    cache[65] = 2;
    cache[66] = 2;
    cache[67] = 2;
    cache[68] = 3;
    cache[69] = 3;
    cache[70] = 3;
    ....

Essentially, build an array with a direct 1-to-1 mapping between the char value, and the phone key number.

Until this point, the fastest transform was by doing a calculation, but comparing that calculation with:

private static int cached(String text) {
    int result = 0;
    for (int i = 0; i < text.length(); i++) {
        result *= 10;
        result += cache[text.charAt(i)];
    }
    return result;
}

Note the direct cache[text.charAt(i)] call. The cached performance (compared with the calc performance), is:

Task Keys -> Calc: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.2914
  Fastest  :   0.2749      Slowest  :   2.3255
  95Pctile :   0.3327      99Pctile :   0.4448
  TimeBlock : 0.315 0.285 0.292 0.285 0.284 0.280 0.293 0.283 0.299 0.297
  Histogram :   999     0     0     1

Task Keys -> rawcache: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.1425
  Fastest  :   0.1328      Slowest  :   1.7173
  95Pctile :   0.1633      99Pctile :   0.2393
  TimeBlock : 0.159 0.142 0.142 0.139 0.138 0.138 0.144 0.137 0.142 0.144
  Histogram :   998     1     0     1

Essentially it runs in half the time.

Validated

Additional thoughts about how I would make the lookup process neat, and how I would include other ideas in my answer as well as other answers, lead me to revised code with the following features:

fast by using a lookup
handles upper case, and lower case characters
handles the raw digits too (like 1800MyPhone)
returns an int array, not an int:

allowing for leading 0 values
allowing for longer-than-9-digit numbers.

strips off unrecognized characters

In essence, the following number 1(800)-My-Phone will translate to [1, 8, 0, 0, 6, 9, 7, 4, 6, 6, 3]

private static int switchKey(char c) {
    switch (Character.toUpperCase(c)) {
        case '0':
            return 0;
        case '1':
            return 1;
        case '2': case 'A': case 'B': case 'C':
            return 2;
        case '3': case 'D': case 'E': case 'F':
            return 3;
        case '4': case 'G': case 'H': case 'I':
            return 4;
        case '5': case 'J': case 'K': case 'L':
            return 5;
        case '6': case 'M': case 'N': case 'O':
            return 6;
        case '7': case 'P': case 'Q': case 'R': case 'S':
            return 7;
        case '8': case 'T': case 'U': case 'V':
            return 8;
        case '9': case 'W': case 'X': case 'Y': case 'Z':
            return 9;

    }
    return -1;
}

private static final int[] KEY_LOOKUP = buildLookup("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

private static int[] buildLookup(String candidates) {
    int max = -1;
    for (char c : candidates.toCharArray()) {
        max = Math.max(max,
                Math.max(Character.toLowerCase(c), Character.toUpperCase(c)));
    }
    int[] lookup = new int[max + 1];
    Arrays.fill(lookup, -1);
    for (char c : candidates.toCharArray()) {
        lookup[Character.toLowerCase(c)] = switchKey(c);
        lookup[Character.toUpperCase(c)] = switchKey(c);
    }
    return lookup;
}

/**
 * Map a phone key character to a phone key number. Return -1 for invalid
 * input characters.
 *
 * @param ch
 *            The character to convert.
 * @return the corresponding number (0 though 9), or -1 for invalid numbers
 */
public static final int lookupKey(final char ch) {
    return ch >= KEY_LOOKUP.length ? -1 : KEY_LOOKUP[ch];
}

/**
 * Parse an input string for characters that are valid phone-key characters,
 * and return the corresponding phone digits as an array.
 *
 * @param text
 *            the text to parse for phone numbers
 * @return the valid phone digits from the input text.
 */
public static int[] parsePhoneNumber(String text) {
    final int length = text.length();
    int[] result = new int[length];
    int size = 0;
    for (int i = 0; i < length; i++) {
        int key = lookupKey(text.charAt(i));
        if (key >= 0) {
            result[size++] = key;
        }
    }
    if (size == length) {
        return result;
    }
    return Arrays.copyOf(result, size);
}


Counting the total value of Card instances given

First a minor note. It is less efficient to create a temporary Array from the result of Zip2. You can use the function map instead of the method map:

map(Zip2(hand, dropFirst(hand))) { ... }.reduce(0, +)

Second, I believe that having such a complex comment describing what your method does, is a sign that your code can be much more understandable. Usually a good replacement for a comment is a well named function. This is how I would implement your function:

func countHand(hand: [Card]) -> Int {
    func iterateTwoCardsAtATime(hand: [Card], block: (first: Card, second: Card) -> ()) {
        for (first, second) in Zip2(hand, dropFirst(hand)) {
            block(first: first, second: second)
        }
    }

    func scoreForConsecutiveCards(first: Card, second: Card) -> Int {
        switch(first.suit, first.rank, second.rank) {
            case (.Hearts, _, .Num(let numRank)) where numRank % 2 == 1:
                return 2 * numRank
            case (.Diamonds, .Num(5), .Ace):
                return 100
            default:
                return 0
        }
    }

    var sum = 0
    iterateTwoCardsAtATime(hand) { (first, second) in
        sum += scoreForConsecutiveCards(first, second)
    }
    return sum
}

Yes, this is definitely more verbose, but the code is much more clear and doesn't require a comment.

First, a new developer looks at the method and sees that there is a function called iterateTwoCardsAtATime. If they want to verify that it works as expected, they can, but most can assume it works and skip that implementation.

Then they get to scoreForConsecutiveCards. This contains all of the complicated scoring logic which is probably the biggest concern when evaluating this method. It is well contained and distinct from the other logic of the method. The other logic is very utilitarian while this logic is important business logic.

Finally, there is a simple understandable block of code written in English like language to sum up the results of all of the scores.

With modern IDEs with features like code folding, clarity is way more important than brevity.


Linq version of the simulated annealing algorithm

You have a lot of small errors here.

What is the purpose of from res in Enumerable.Range(0, 1)? It looks like you did it to force some local variables into 'let' queries, which makes no sense to me.
Instead of using OrderBy(X).First() you should use MinBy(X) (write it yourself if it doesn't exist). There's a significant performance difference.
The value of initial changes every time it is enumerated. Confusing. (You can cache the results with ToArray or ToList to prevent re-enumerating from running more Random.Next calls)
Ensure new Random() is only performed once (do it outside the query). The default seed is the current time, which is highly correlated between calls. You're likely to end up with two instances of Random with the exact same seed.
Random.Next(-10, 10) returns values in [-10, +9]. You probably wanted [-10, +10].


I don't know the Botan library, so I'll stick to some general recommendations.

Don't include whole namespaces at global scope, especially the std namespace.

The only use of Qt in this function is to accept QString arguments, with which we do nothing but convert to standard strings.  So why not remove the dependency, and allow the function to be used in non-Qt projects, by accepting the filenames as const std::string&?  We can keep the interface by providing a (header-only, trivially inlinable) wrapper separately as a convenience for use with Qt:

//encrypt.h
bool EncryptFile(const std::string& source, const std::string& destination);

//encrypt-qt.h
bool EncryptFile(QString source, QString destination)
{ return EncryptFile(source.toStdString(), destination.toStdString(); }

There's certainly no need to use c_str() when passing to the streams' constructors - a std::string is fine (and expected) there.

I'd probably go one further with the overloads, and provide a version that accepts a pair of streams, so that we could use this for network streaming or in-memory encryption:

//encrypt.h
bool EncryptFile(std::istream& source, std::ostream& destination);

bool EncryptFile(const std::string& source, const std::string& destination);
{
    try {
        std::ifstream in(source, std::ios::binary);
        std::ofstream out(destination, std::ios::binary);
        return EncryptFile(in, out);
    } catch (...) {
        return false;
    }
}

Why do we return true, even if writing the output failed?  For example, try passing /dev/full as the destination.  We could fix that:

return in && out;

Alternatively, we could arrange for the streams to throw exceptions:

    in.exceptions(std::ifstream::failbit | std::ifstream::bad);
    out.exceptions(std::ifstream::failbit | std::ifstream::bad);


I dont think mixing html inside PHP the way Tim Penner does in his first example is very readable or maintainable, i'd prefer the way you're trying to do it.

If you're using PHP 5.4+ and do not need the code to be working in earlier php versions i'd recommend you use the short_open_tag <?= to echo out variables easily.

<?php foreach ($userResults as $row) : ?>

<?= $row['user_id']; ?>here

<?= $row['user_name']; ?>here

<?= $row['user_email']; ?>here

<?php endforeach; ?>

This is in my mind more readable and maintainable.


Lists highly divisible numbers, oeis squence: A002182

Consider writing your middle while loop as a separate function - it'll make breaking out of the inner loop easier.

For example, your code could look like this:

def highlydiv(n):
    plist = ...set up plist...
    candidates = divisor_candidates(n, plist)
    ...

def divisor_candidates(n, plist):
    ...set up calcSum, mark, pows, candidates...
    while True:
        ...
        while calcSum > n:
            marker += 1
            if marker > len(pows):
                return candidates
            pows[marker] += 1
            ...
        candidates.append(...)

and you get rid of the breakout flag.

Additionally, this makes the middle part of your program testable.


Checking for a series of uniform non-zero digits

Here are a couple of suggestions for you to implement:

You convert reeks into a string far more frequently than is necessary; just do it once, at the top of the function.
The correct exception to raise if a value is not acceptable is ValueError.
Rather than thing == False, you can use the more readable not thing.
Your approach to the solution seems strange to me; rather than "are all of the digits one, or are all of the digits two, or are all of the digits...", why not "are all of the digits the same as the first digit"?
Python has a style guide, which discourages e.g. redundant parentheses and multi-statement lines:

else:
    return False


You're on the right track trying slice. Here's an example of using it with no loops required.

Initialisation

You could initialise newArray with an element directly in the declaration, removing the need for newArray[0] = ...:

const newArray = [theBoolean ? data[0] : data[1]];

Pushing all other elements from data to newArray:

You could use Array.prototype.slice to get all other elements: data.slice(2).

Using spread operator:

const newArray = [theBoolean ? data[0] : data[1]];
newArray.push(...data.slice(2));

// or, one liner:
const newArray = [theBoolean ? data[0] : data[1], ...data.slice(2)];

Using Array.prototype.concat:

const newArray = [theBoolean ? data[0] : data[1]].concat(data.slice(2));

Using Function.prototype.apply:

const newArray = [theBoolean ? data[0] : data[1]];
[].push.apply(newArray, data.slice(2));


Accessing a list of dictionaries in a list of dictionaries

Your data is slightly wrong - you're using list [] but then putting in keys (0, 1) - I'm going to assume it's a dict of dicts in my examples. However it wouldn't be that different if it was a list of dicts.

data = {
  0: {"name": "hotel1",
         "overall_rating": 4,
         "reviews": [{"rating": 5, "review" : "best place ever"},
                     {"rating": 1, "review" : "toilet was blocked"}],
        },
  1:  {"name": "hotel2",
         "overall_rating": 4,
         "reviews": [{"rating":4, "review" : "welly nice"},
                      {"rating":3, "review" : "I couldn't bring my dog"}],
        }
    }

Your code makes one of the common mistakes that people new to python make, which is to not realise that you can iterate directly over things like lists and dictionaries - rather than having to get the length and then ask for the index of each item.

You can dramatically simplify your code by just iterating over the values in data directly, and then getting the reviews key of each 'child' dict:

ratings = []
reviews = []
for hotel in data.values():
    for review in hotel['reviews']:
        reviews.append(review['review'])
        ratings.append(review['rating'])

Note that this isn't really what most people would think of as processing a nested dict - since although the data is nested, it is all one level deep - so you can just ask for it at that level.

More complex examples are where you want the same data from multiply nested dictionaries, and have to resort to recursion to get it, e.g. getting all 'name' fields from the following family tree:

tree = {
  'name': 'Alice',
  'relation': 'grandmother',
  'child': {
    'name': 'Bob',
    'relation': 'father',
    'child': {
      'name': 'Charlie',
      'relationship': 'me'
    }
  }
}


Non-standard interface to standard function

The obvious criticism of that implementation is that it has a different interface from what the C standard requires:

  §7.20.4.1 The abort function

  Synopsis

#include <stdlib.h>
void abort(void);

  Description

  The abort function causes abnormal program termination to occur, unless the signal
  SIGABRT is being caught and the signal handler does not return. Whether open streams
  with unwritten buffered data are flushed, open streams are closed, or temporary files are
  removed is implementation-defined. An implementation-defined form of the status
  unsuccessful termination is returned to the host environment by means of the function
  call raise(SIGABRT).

  Returns

  The abort function does not return to its caller.

Unreliable implementation of 'crash'

There were systems, notoriously the DEC VAX, where accessing the memory at address 0 did not cause problems (until the programs that were written on the VAX were ported to other platforms that did abort).

Dereferencing a null pointer is undefined behaviour - that means anything could happen, including 'no crash'.

Nitpicks in implementation

If, for some reason, fprintf() returns 0, your program will not abort.  For example:

abort("");

does not abort.  It is also dangerous to use the string as the format string; you should use:

#define abort(msg) (fprintf(stderr, "%s\n", msg) && *((char*)0))

It would be better to use a comma operator in place of the &&:

#define abort(msg) (fprintf(stderr, "%s\n", msg), raise(SIGABRT))

Since the standard library could have defined a macro abort(), you should #undef it before defining it yourself.


Design

Your main issue is design. Without looking at the rest of your code to understand how it works this is a bit of a guess. But it feels like you have a design issue with your larger algorithm. There are much better ways to solve this without scanning way ahead in the input stream.

As pointed out by @JerryCoffin above in the comments shunting yard or recursive descent are things you should look into. Personally I think the shunting yard algorithm would give you the most benefit at this point.

Review of Code

Iterators are supposed to be very simple object that carry little state. So passing them by value should not be an issue. Also is there a need to limit this to string::iterator?

string get_between_brackets(string::iterator& tail_, const string::iterator& end_)

I would have done:
    string get_between_brackets(string::iterator& tail_, const string::iterator& end_)

template<typename I>
std::string get_between_brackets(I tail_, I end_)

That's a great comment.

    brackets_content.reserve(248); //cannot be longer than that

But i don't see that being enforced anywhere.

This switch is broken:

            switch(chr)
            {
                case '(': ++br_cnt; break;
                case ')': --br_cnt; break;
            }

Any character that does not match ')' or '(' leads to undefined behavior. You should must have a default option.

You throw if there is not enough charaters to hold two braces.

else throw std::invalid_argument("brackets tail is not long enough");

But your code works perfectly well if there are no braces in the code. Also I would expect it to throw if the braces were not balanced.

Also rather than building the result slowly character by character as you parse it. It would be simpler (and more effecient) to just remember the beignning and end and return a sub string.

    return std::string(firstBrace, lastBracePlusOne);


Could I dispose IDisposable objects that are part of a Thread?

Strictly speaking, it depends on what InitProcess does.  It may very well work OK as long as it never touches resources in the ProcessThread class which get disposed.

However, even if it works this time, it is a bad idea.  Passing a method group from a class which gets disposed before the thread even starts is asking for trouble.

A better option would be to create a method inside your ServiceTest class that the thread executes.  Inside that thread, you can instantiate a ProcessThread object, call InitProcess, and ensure that Dispose is only called once InitProcess has completed:

protected override void OnStart(string[] args)
{
    m_cProcessThread = new Thread(InitProcess);
    m_cProcessThread.Start();
}

private void InitProcess()
{
    using(var processThread = new ProcessThread())
    {
        processThread.InitProcess();
    }
}

You may also note that I removed the explicit construction of a ThreadStart delegate.  In many cases, you can pass a method group directly where delegates are called for.  I find it a little cleaner to do so.


Finding the longest string and its length using Java streams

You don't need the Pair.  You can get the String with the maximum length by doing

names.stream().max(Comparator.comparingInt(String::length))


Interface

When I see a method named get…(), I expect it to behave like a getter method: it should retrieve data, with no side-effects.  Your getNext(), though, has the side-effect of consuming one random element from the list.  Therefore, next() would be a more appropriate name than getNext().

Once you rename it, you'll see that your RandomStringChooser should probably just implement the Iterator<String> interface.  Java programmers instantly recognize an Iterator and know how one should behave.

Then, you'll see that the Iterator interface says that next() should throw NoSuchElementException when the elements have been exhausted — and that is what you should do too.  In fact, returning "NONE" as a special string to indicate a missing value is a bad practice.

Furthermore, if one of the input strings is in fact null, it shouldn't be the job of your RandomStringChooser to translate it to "NONE".

Consider changing the signature of the constructor to public RandomStringChooser(String... words).  The code will continue to work the same way, but you would also have the option of invoking it as new RandomStringChooser("wheels", "on", "the", "bus"), with multiple string arguments.

Efficiency

Whenever you extract a random element from the list, you call this.wordArray.remove(index).  Removing an element causes all of the subsequent elements to be copied over to fill the gap.  Therefore, if you randomly go through an n-element list, you will perform O(n2) copy operations, which is quite poor for efficiency.

A better idea would be to implement a Fisher-Yates shuffle, which just swaps one pair of elements per output string.

Miscellaneous

wordArray is poorly named: it's actually a java.util.List, not an array.

Your signposting comments are annoying noise to anyone who knows Java.

Suggested implementation

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;

public class RandomStringChooser implements Iterator<String> {

    private Random r;
    private String[] words;
    private int n;

    public RandomStringChooser(String... words) {
        this.r = new Random();
        this.words = Arrays.copyOf(words, words.length);
        this.reset();
    }

    /**
     * Makes all words eligible to be chosen again, even if they have been
     * previously returned by next().
     */
    public void reset() {
        this.n = this.words.length;
    }

    public boolean hasNext() {
        return this.n > 0;
    }

    public String next() {
        if (!this.hasNext()) {
            throw new NoSuchElementException();
        }

        // Fisher-Yates shuffle
        int index = r.nextInt(this.n--);
        String word = this.words[index];
        this.words[index] = this.words[this.n];
        this.words[this.n] = word;
        return word;
    }

    /** This is a main method for testing the class */
    public static void main(String[] args) {
        System.out.println("It should print the words in the array in a random order and then NONE twice");
        RandomStringChooser sChooser = new RandomStringChooser(
            "wheels", "on", "the", "bus"
        );
        //This loop will output the words in `wordArray` in random order, then "NONE" twice
        for (int k = 0; k < 6; k++) {
            System.out.println(sChooser.hasNext() ? sChooser.next() : "NONE");
        }
        //This loop will output the words in `wordArray` in random order, then stop
        sChooser.reset();
        for (int k = 0; k < 4; k++) {
            System.out.println(sChooser.hasNext() ? sChooser.next() : "NONE");
        }
     }

}


Convert international datestring to ISO-format

Neat stuff.

Suggestions:

Changing shortmonths to a dictionary.  This will allow for a pair between numerical months and alphabetical months.  No need to repeat 'jan' for example, as you have it now.

Pythonic: unpack month, year, day in a one liner.

Use datetime's strftime to format dates...makes life easier in case you want to change the format down the road.

import re
import datetime

def ISOdate(date):

    month_d = {'01': 'jan',
               '02': 'feb',
               '03': ['mar', 'mrt'],
               '04': 'apr',
               '05': ['may', 'mei'],
               '06': 'jun',
               '07': 'jul',
               '08': 'aug',
               '09': 'sep',
               '10': ['oct', 'okt'],
               '11': 'nov',
               '12': 'dec'
               }

     pat = r'(\d{1,2})\s?[-\/]?\s?(\w{3})\s?[-\/]?\s?(\d{4})'
     q = re.match(pat, date)

     if q:
         day, month, year = [q.group(idx+1) for idx in range(3)]
         if month.isalpha(): # change from letters to numbers
             month = [k for k, v in month_d.items() if month in v][0]
         out_date = datetime.date(int(year), int(month), int(day))
         return datetime.datetime.strftime(out_date, '%Y-%m-%d')

     else:
         return date


For one, I see your code is a bit over-engineered. So let's go back to the problem: Given a year and month, determine what day that month starts in a year and how many days it has.

To start, I would need 2 functions to keep the code understandable. Trying to jam a lot of functionality into one function would only cause problems in trying to understand things.

function getFirstDayOfMonthAtYear(month, year){...}

function getLengthOfMonthAtYear(month, year){...}

You could go for a constructor to house the month and year value, and the functions be methods on the prototype. Also, your lookup arrays need to come with the constructor, not just some free-floating variable. You can attach them to the constructor, since functions are also objects.

function Calendar(year, month){
  // Default to January 1970
  this.month = month || 0;
  this.year  = year || 1970;

  // Generate the Date object so we don't need to create on every call.
  // Also note that months are zero-indexed. So if we provide the
  // real month number, we need to subtract 1.
  this.date = new Date(year, month - 1, 1);
}

Calendar.prototype.getFirstDay = function(){
  return Calendar.DAY_NAMES[this.date.getDay()];
};
Calendar.prototype.getMonthLength = function(){
  // I'll show you a trick next
};

// We use pseudo-static variables. Essentially we're just attaching
// to the constructor. That way, our lookup comes with the constructor.
Calendar.DAY_NAMES = ['Sun', 'Mon', ..., 'Sat'];

So it comes to getting how long a month is. There's a trick for that. You can construct a Date object with the current year but on the next month with date 0. JavaScript dates that underflows/overflows the months date range automatically increments/decrements the month. Then it's all a matter of doing getDate.

// So the date is March 0, 2004... essentially Feb 29, 2004
var daysOnFeb2004 = (new Date(2004, 2, 0)).getDate(); // 29

In the end:

function Calendar(year, month) {
  this.month = month || 0;
  this.year = year || 1970;
  this.date = new Date(year, month - 1, 1);
}

Calendar.prototype.getFirstDay = function() {
  return Calendar.DAY_NAMES[this.date.getDay()];
};

Calendar.prototype.getMonthLength = function() {
  return (new Date(this.year, this.month, 0)).getDate();
};

Calendar.DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

// Usage
var date = new Calendar(2004, 2);
document.write('First day: ' + date.getFirstDay() + ' Length:' + date.getMonthLength());


The most canonical way of accomplishing what you want is to use the testing framework's functionality for writing data-driven tests, rather than writing a common helper method and then a number of separate tests which pass arguments into it.

Different frameworks do this differently, so I will focus on MSTest first, as that is the framework you use.

In MSTest, there is a DataSource attribute you can supply, which defines how the framework can locate your test data.  Additionally, you supply a TestContext property of type TestContext.

When the tests execute, TestContext will be populated with the data for a single test case, and you can access it by using named indexing into the TestContext.DataRow property.

(Note: I haven't done MSTest in some time, so feel free chime in if there's a better way nowadays)

Example:
(Embedded resource: foo.xml)

<?xml version="1.0" encoding="utf-8" ?>
<Tests>
   <Test>
      1
      2
      <result>3<result>
   </Test>
   <Test>
      2
      2
      <result>4<result>
   </Test>
</Tests>

(test file)

  public TestContext TestContext { get; set; }

  [TestMethod]
  [DeploymentItem ("foo.xml")]
  [DataSource ("Microsoft.VisualStudio.TestTools.DataSource.XML",
               "|DataDirectory|\\foo.xml",
               "Test",
               DataAccessMethod.Sequential)]
  public void TestAdd ()
  {
     var first = (int) TestContext.DataRow ["a"];
     var second = (int) TestContext.DataRow ["b"];
     var expected = (int) TestContext.DataRow ["result"];
     var result = testObject.Add(first,second);
     Assert.AreEqual(expected, result);
  }

Adding more test cases is just a matter of adding  elements with new data and re-building/re-running.

The How-To MSDN page can be found here, and some examples of DataSource configuration strings can be found here.

Just to give you a taste of this in other frameworks:

NUnit TestCase

  [TestCase(1,2,3)]
  [TestCase(2,2,4)]
  public void TestAdd(int first, int second, int expected)
  {
     var result = testObject.Add(first, second);
     Assert.That(result, Is.EqualTo(expected));
  }

NUnit TestCaseSource

  public static IEnumerable<TestCaseData> TestData
  {
     yield return new TestCaseData(1, 2, 3);
     yield return new TestCaseData(2, 2, 4);
  }

  [TestCaseSource("TestData")]
  public void TestAdd(int first, int second, int expected)
  {
     var result = testObject.Add(first, second);
     Assert.That(result, Is.EqualTo(expected));
  }

MbUnit Row

  [RowTest]
  [Row(1,2,3)]
  [Row(2,2,4)]
  public void TestAdd(int first, int second, int expected)
  {
     var result = testObject.Add(first, second);
     Assert.AreEqual(result, expected);
  }


PDO prepared statement to insert data into MySQL

Yes, you did everything right, save for the obvious typo with the extra parameter. You can keep with it all right.

The only improvement (which is the point of this site) I can think of is that you can make this code less bloated, with help of positional placeholders.

$sql = "INSERT into pools (profileid, name, description) values (?,?,?)";
$pdo->prepare($sql)->execute([$profileid, $name, $description]);
redirect_to('/my-pools');

To my taste, this is the most clear and readable approach: now it fits onto screen without horizontal scrolling and you still can visually control the parameter order.


There is nothing wrong with rethrowing an exception of a different type, the problem lies with how you are doing it. According to the PHP docs, you can pass a previous exception as a second argument to the new exception. This preserves the original stack trace. I would also provide a new error message as well:

throw new MyException("A new error summary", $e);

A new take on your switch statement:

public function render($request, Exception $e)
{

    switch (true) {

        case $e instanceof Exceptions\Auctions\AuctionTypeException:
            throw new Exceptions\Notifications\AlertException("An auction type failed to save", $e);
            break;

        case $e instanceof Exceptions\Auctions\AuctionArgumentException:
            throw new Exceptions\Notifications\AlertException("An auction argument was not valid", $e);
            break;

        ////////////////////////////////////////////
        // Custom errors to display in error view //
        ////////////////////////////////////////////
        case $e instanceof Exceptions\Notifications\AlertException:

            return response()->view('errors.notification', ['message' => $e->getMessage(), 500]);
            break;

        //////////////////////////////////////////////
        // Unknown exceptions are rendered normally //
        //////////////////////////////////////////////
        default:
            return parent::render($request, $e);
    }

}


Pairwise combinations of an array in Javascript

Pairing combinations like this is a very common thing to do in any language. There's a very 'idiomatic' way to do this type of operation:

for (int i = 0; i < length; i++) {
    for (int j = i + 1; j < length; j++) {
        // do something with pair (i,j)
    }
}

You will see, and recognize this pattern anywhere.

Because that pattern is so recognizable, I prefer seeing it rather than the slicing and dicing your code does.

Additionally, since the formula for the number of iterations is so readily available, it makes sense to pre-size the output array you use. Pre-sizing the output array will make a significant performance difference.

Further, even though the 'classic' for loop is used here, the performance will be fine. Other systems requiring slices or maps of list subsets will require additional work which, despite being 'idiomatic', will not necessarily be faster:

function pairwise(list) {

    var pairs = new Array((list.length * (list.length - 1)) / 2),
        pos = 0;

    for (var i = 0; i < list.length; i++) {
        for (var j = i + 1; j < list.length; j++) {
            pairs[pos++] = [list[i], list[j]];
        }
    }
    return pairs;
}

var result = pairwise(['a', 'b', 'c', 'd', 'e']);
document.getElementById('output').innerHTML = JSON.stringify(result);


Macro for counting number of elements in an array

We need to protect a when it's an expression - we've put parens around a[0] where we should have put them around a:

(sizeof(a)/sizeof(a)[0])

For the same reason, I think that the second typeof should be

typeof(&(a)[0])

I have to admit that I can't easily contrive an expression of array type where the parens make a difference, but better safe than sorry...


Remarks to your code

Function names should be using camelCase.
Two minor formatting errors: function ElapsedTime (), if(oDiff).
                                               ↑       ↑
You mentioned ES6 in your question, so: var nTotalDiff could be declared using let and var oDiff using const.
You declare oDiff in TimePassed() as a global variable (you forgot var).
oDiff.seconds is declared, but never used.
(new Date()) can be written as new Date().
Specifying 1491685200 in human readable format would be better, I think.Update: suggestion removed due to the problem pointed out in the comment to this answer.
If you leverage power of modulo operator, you can get rid of all these nTotalDiff -= oDiff.██████ * ███.
alert(oDiff.days + 'd ' + oDiff.hours + 'h ' + oDiff.minutes + 'm ') can be written in ES6 using template literals as alert(`${oDiff.days}d ${oDiff.hours}h ${oDiff.minutes}m `), although space after m is unnecessary whatsoever.
Having two functions named ElapsedTime() and TimePassed() seem ambiguous.
Your code is not in strict mode.

My rewrite

const elapsedTime = () => {
  'use strict';
  const since   = 1491685200000, // Saturday, 08-Apr-17 21:00:00 UTC
        elapsed = (new Date().getTime() - since) / 1000;

  if (elapsed >= 0) {
    const diff = {};

    diff.days    = Math.floor(elapsed / 86400);
    diff.hours   = Math.floor(elapsed / 3600 % 24);
    diff.minutes = Math.floor(elapsed / 60 % 60);
    diff.seconds = Math.floor(elapsed % 60);

    let message = `Over ${diff.days}d ${diff.hours}h ${diff.minutes}m ${diff.seconds}s.`;
    message = message.replace(/(?:0. )+/, '');
    alert(message);
  }
  else {
    alert('Elapsed time lesser than 0, i.e. specified datetime is still in the future.');
  }
};

document.getElementById('counter').addEventListener('click', elapsedTime, false);
<button id="counter">Check elapsed time</button>

Remarks

/(?:0. )+/ matches sequences of one or more zero followed by any character and a space. It is used to change potential output that would look like 0d 0h 0m 1s to simply 1s.
In message I added word over, because the calculated time is in fact the least amount of time that could have passed (calculation time, Math.floor(), instantaneous nature of time specification invalidation).


Print combinations of balanced parentheses

It's a nice solution!

One thing that might speed things up a little would be to use a Set; no need for the include? then. Just call to_a on it at the end (or don't, and return a Set - still fits the task).

Also, I'd use p.length.times { |i| ... } instead of a for loop, and make a couple of variable names a little more descriptive (p, for instance, is not a very descriptive name).

require 'set'

def brackets(n)
  return ["()"] if n == 1

  brackets(n-1).each_with_object(Set.new) do |str, set|
    str.length.times do |i|
      set << str.dup.insert(i, "()")
    end
  end.to_a
end

Or, without converting to an array:

def brackets(n)
  return Set.new(["()"]) if n == 1

  brackets(n-1).each_with_object(Set.new) do |str, set|
    str.length.times do |i|
      set << str.dup.insert(i, "()")
    end
  end
end

brackets(3) # => #<Set: {"()()()", "(())()", "()(())", "(()())", "((()))"}>

Might also be nice to avoid the duplicated "()" string. You could make it an argument, so the method can be used for other "pairs", e.g:

def brackets(n, pair = "()")
  return Set.new([pair]) if n == 1

  brackets(n-1, pair).each_with_object(Set.new) do |str, set|
    str.length.times do |i|
      set << str.dup.insert(i, pair)
    end
  end
end

brackets(3, "<>") # => #<Set: {"<><><>", "<<>><>", "<><<>>", "<<><>>", "<<<>>>"}>

Or you can simply make it a constant, like SINGLE_PAIR = "()".freeze.


I like the way you defined numerator and denominator.

I think that using length . show to compute the number of digits is a bit overkill. Do you really need to convert the number to a string to do that? I think that using a logarithm is better.

log10 = logBase 10
numDigits = ceiling . log10 . (+) 1

I don't think that moreDigits is a good name. What about longerThan?

countTrue style doesn't look too functional. What about count :: (a -> bool) -> [a] -> Int? In that way you'll have a function you can use to count the number of items matching a predicate in any list, instead of having to compute first the a list of boolean values.

If you use count you'll need to rearrange change moreDigits :: (Int, Int) -> bool and pe_057.

pe_057 = countTrue moreDigits $
  take 1000 (zip numerator denominator)

I also implemented an alternative solution. The main difference with respect to yours is that I generare a list of (numerator, denominator) pairs instead of having two separate lists.

nextFraction :: (Integer, Integer) -> (Integer, Integer)
nextFraction (n, d) = (2*d + n, d + n)

generator :: [(Integer, Integer)] -> [(Integer,Integer)]
generator (x: xs) = nextFraction x : generator xs

fractions :: [(Integer,Integer)]
fractions = (3,2) : generator fractions

numeratorLonger :: (Integer,Integer) -> Bool
numeratorLonger (n,d) = (numDigits n) > (numDigits d)

numDigits :: Integer -> Int
numDigits n = numDigitsImpl (div n 10) 1

numDigitsImpl :: Integer -> Int -> Int
numDigitsImpl n counter = if next == 0
                             then counter
                             else numDigitsImpl next (counter + 1)
                          where next = div n 10

count :: (a -> Bool) -> [a] -> Int
count f xs = length $ filter id $  map f xs

projectEuler57 n = count numeratorLonger $ take n fractions

main :: IO ()
main = do
  print $ projectEuler57 1000


Is this binary search in TypeScript correct?

That looks jolly complicated.  If you haven't read it, look for Jon Bentley's Programming Pearls article on binary search.  Here's my version:

var bSearch = <T>(xs: T[], x: T, cmp: (p: T, q: T) => number): number => {
    var bot = 0;
    var top = xs.length;
    while (bot < top) { // If x is in xs, it's somewhere in xs[bot..top).
        var mid = Math.floor((bot + top) / 2);
        var c = cmp(xs[mid], x);
        if (c === 0) return mid;
        if (c < 0) bot = mid + 1;
        if (0 < c) top = mid;
    }
    return -1;
}

var cmp = (p: number, q: number) => p - q;

console.log(bSearch([], 3, cmp) === -1);
console.log(bSearch([3], 3, cmp) === 0);
console.log(bSearch([1, 3], 3, cmp) === 1);
console.log(bSearch([3, 4], 3, cmp) === 0);
console.log(bSearch([3, 3], 3, cmp) !== -1);
console.log(bSearch([1, 2, 3], 3, cmp) === 2);
console.log(bSearch([1, 3, 4], 3, cmp) === 1);
console.log(bSearch([3, 4, 5], 3, cmp) === 0);
console.log(bSearch([4, 5, 6], 3, cmp) === -1);


Apart from the first issue below, your code is mostly clean!

What happens if one of the parseInt calls throws an exception? In that case, I'd send a HTTP 500 error as well. This is especially relevant in your scenario where the data comes from an unknown client.
Essentially, the solution boils down to wrapping all the code in a try-catch or employing middleware.

routes.post("/submit", async (request, result) => {
  try {
    /* all the code */
  }
  catch (err) {
    /* log & send a generic HTTP 500 error message as in your code */
    /* Beware that you might not intend to send a HTTP 500 message if
       the code in the try already sent something! */
  }
});

// <=>
routes.post("/submit", wrapSafe(yourCodeExtractedAsAFunction));

// <=>
routes.post("/submit", someMiddleWare(yourCodeAsAFunction));

Catching all exceptions (and not rethrowing ones you cannot handle) is fine in your case since your function is top-level enough for that.
Exactly as you say, if you add middleware, let the exception bubble up and let the middleware take care of it.
Omit the return in an arrow function if it is unnecessary and serves no clarity. So this block:

gapf.documents = gapf.documents.map(doc => {
  return {
    name: doc.name,
    link: doc.link,
    attachedDate: parseInt(doc.attachedDate, 10)
  };
});

Can be updated like this:

// You need enclosing parentheses, so that the parser can
// differentiate between a block statement and an object literal.
gapf.documents = gapf.documents.map(doc => ({
  name: doc.name,
  link: doc.link,
  attachedDate: parseInt(doc.attachedDate, 10)
}));

// convert relevant request strings into integers: Maybe you could describe what constitutes a "relevant request string". Is there a list of them?


There is not much to review, your code is clean.  There are some things that you can do to improve User Experience (UX).

Replace the label, SelectAllButton and UnselectAllButton with a checkbox.
Place a Frame around the Controls
Add a ComboBox to change target workbooks
Add buttons to copy and paste styles between workbooks

And if you want to go buckwild you could add a Preview Button


Here is my list of recommendations:

To make the database object available in the custom functions' scope, pass it as a parameter.  I know your global declaration is commonly used by WPers, but I consider it to be sloppy development.  If you are going to persist with using global, then you should only do it once per custom function.
In bestanswers() to make your SQL easier to read, use newlines, indentation, spaces around operators, ALLCAPS mysql keywords, double-quoting the full string, and single-quoting the values in the string. *That said, for the most secure and consistent project, you should use prepared statements anytime you are supplying variables to your query.

$results = $wpdb->get_results(
    "SELECT *
     FROM wp_comments
     LEFT JOIN wp_custom_scoring
         ON wp_custom_scoring.entryID = wp_comments.comment_ID
     WHERE class = 'point'
         AND comment_post_ID = " . (int)$a . "
         AND type = 'plus'
     GROUP BY entryID
     ORDER BY COUNT(entryID) DESC");

empty() does 2 things.  It checks if a variable !isset() OR loosely evaluates as "falsey". You know that $result will be set because you have unconditionally declared it on the previous line of code. (untested...)

if (!$results)) {
    echo 'Its Empty!';
    return false;
}else{
    return $results;
}

Or if you don't need the echo:

return $results ? $results : false;

In scores(), your $b parameter only determines the WHERE clause, so you can DRY out your code like this:

function score($wpdb, $a, $b) {
    if (in_array($b, ['plus','minus']) {
        $where = "class = 'point' AND type = '{$b}'";
    } else {
        $where = "class = 'fav'";
    }

    $results = $wpdb->get_results(
        "SELECT COUNT(id) as total
         FROM wp_custom_scoring
         WHERE entryID = " . (int)$a . "
           AND {$where}";

    if (!$results || !$results[0]->total) {
        return 0;
    } elseif ($a === 'plus') {
        return "+{$results[0]->total}";
    } elseif ($a === 'minus') {
        return "-{$results[0]->total}";
    } else {
        return $results[0]->total;
    }
}

but again, I urge you to consider using prepared statements as a consistent/stable/secure technique across your whole application.

Ultimately, I don't know what is down in the ...etc. portion of your script, but if you are making two function calls to calculate: score($bests->comment_ID,"plus") + score($bests->comment_ID,"minus") > 0, then it may make better sense to create a single custom function that performs this calculation and returns the sum instead.


SQL Server - Iterate, aggregate, and insert

There's no need for a cursor or recursion, both are not really performant for larger amounts of data.

Simply adjust the CaptureTime to the start of each interval.

declare @UpdateIntervalSeconds integer = 5;
declare @minTime datetime = (select min(CaptureTime) from RawData);
-- if you want to start at exactly `00` instead of `01`,`02` etc.
-- you can modify `@minTime` using another DATEADD/DATEDIFF

with cte as
 ( select
      -- adjust each CaptureTime to the begin of an interval
      DATEADD(SECOND, -DATEDIFF(SECOND, @minTime , CaptureTime) % @UpdateIntervalSeconds, CaptureTime) as StartCaptureTime
     ,Result
   from RawData
 )
select StartCaptureTime
  ,DATEADD(SECOND, @UpdateIntervalSeconds, StartCaptureTime) AS EndCaptureTime
  ,sum(Result)
from cte
group by StartCaptureTime
order by StartCaptureTime


Given bit strings, perform a bitwise addition

Please verify if space complexity is O(n) where n is number of bits, and aux complexity is O(1), since no temporary space was needed. Whatever space was needed was used for return value not for temporary purpose. Rectify my understanding of space and aux complexity if wrong.

Wrong.

Let's use another example. Bubble-sort uses \$O(1)\$ auxiliary space complexity. Bubble-sort does an "in-place sort", it does not require additional space except for a single temp variable.

Auxiliary means "helper". In the case of your code, the "helper" is the return value. The auxiliary space complexity of your code is \$O(n)\$.

Also remember this line:

return sum.reverse().toString();

How could you possibly reverse a string without storing the string in the first place? The space required to store this String is \$O(n)\$

There is an article on Geeks for Geeks explaining this and a question on Stack Overflow about it.

Auxiliary space ignores the size of the input, not the output.


Read a space delimiters settings file in C

You are testing for NULL twice

//if input filename is null
if(!in_filename ||               // This is a test for NULL.   !valid pointer is 0 !NULL is 1
   *in_filename == '\0' ||       // Test for empty string

   in_filename == NULL)          // Test for NULL again.

No Need to do the work twice.
When you declare the variable assign it at the same time:

//open file
FILE *t_fd   = NULL;
t_fd         = fopen (in_filename,"r");

// Easyier to write and read:

//open file
FILE *t_fd   = fopen (in_filename,"r");

Also not keen on the short non-descriptive file name.

You are only allowing comments if the magic character is the first character in the line. That's a bit restrictive (most places allow for the first non white space character on a line to mark a comment).

That's because scanf() easily allows you to ignore white space:

while( (t_firstChar = getc(t_fd)) != EOF )
{
    //skip comment line
    if(t_firstChar == '/' || t_firstChar == '#')

// Easier with:

while(fscanf(t_fd, " %c", & nextChar) == 1)
{
   // Skips empty lines.
   // Returns the first non white space character

You are skipping lines with getline() which reads off the end of line marker ('\n'). The trouble is you are reading the line into a buffer of fixed size but not checking if you spill over that size. fscanf provides an alternative that allows you to read and discard the content.

        long t_currFP = getline(t_fd, t_comment, t_buffSize);

        // Can be replaced with:
        fscanf(t_fd, "%*[^\n]"); // Read up to the '\n character
                                 // But not including it. The star '*' indicates to
                                 // discard the input
        fscanf(t_fd, "\n");      // Read the '\n' character

        // Note you have to do these two lines separately.
        // You can not use the string "%*[^\n]\n"
        //    This is because if there is only a '\n' character (not any comment) then
        //    the first part fails and it would have failed leaving the '\n' on the stream.

But you then doing a seek() to an absolute position. I am not sure how this is working in your code because the seek moves the read point to the absolute position identified by the length of the line just read. So unless the only comment is the first line then this will fail.

// this line should just be removed).
// fseek(t_fd, t_currFP + 1, SEEK_SET);

Your move back one space in the input stream is support directly with a relative seek

       long t_currFP = ftell (t_fd);
       fseek(t_fd, t_currFP - 1, SEEK_SET);

       // replace with:
       fseek(t_fd,-1, SEEK_CUR);

Then you do the real work:

        if(fscanf (t_fd, "%s %s", t_key, t_value) != EOF)

This line will never return EOF as you have just made sure there is at least one character in the stream be rewinding one place. But it can still fail. You should test the result for the number of conversions it performed.
Also if either your key or value exceed the size of the buffer things will horribly wrong. So you need to make sure your don't read past the end of the buffer:
Finally you are not reading off the '\n' character this will leave this on the line for (see above to find about reading the rest of the line).

How to build the conversion string will depend.
You are using the identifier t_buffSize as a buffer size. If this is a macro (which it usually is) then building the string is easy with some macros magic and string compile time concatenation:

#define   DO_QUOTE(X)   #X
#define   QUOTE(X)  DO_QUOTE(X)

#define   CONVERSION_STRING_SIZE(SIZE)   "%" QUOTE(SIZE) "s"

#define   ConvString CONVERSION_STRING_SIZE(t_buffSize) " " CONVERSION_STRING_SIZE(t_buffSize)

// Assuming t_buffSize is 50 this should generate the string:
// ConvString =>  "%" "50" "s" " " "%" "50" "s"
// Consecutive string literals are concatenated at compile time to generate
// "%50s %50s"

On the other hand if t_buffSize is a variable of type int the you will need to build the string dynamically using sprintf()

char ConvString[100]; // Big enough for two integer and 5 characters
sprintf(ConvString, "%%%ds %%%ds", t_buffSize, t_buffSize);

Then you final read is:

        if(fscanf (t_fd, ConvString, t_key, t_value) == 2)
        {
             // Do Stuff
        }
        // Ignore the rest of the line:
        fscanf(t_fd, "%*[^\n]");
        fscanf(t_fd, "\n");

Summary

#define   BUFFER_SIZE   612
#define   DO_QUOTE(X)   #X
#define   QUOTE(X)      DO_QUOTE(X)
#define   ConvString    "%" QUOTE(BUFFER_SIZE) "s %" QUOTE(BUFFER_SIZE) "s"

int ReadConfigFile(char const *in_filename)
{
    char t_key[BUFFER_SIZE];
    char t_value[BUFFER_SIZE];

    //if input filename is null
    if(!in_filename || *in_filename == '\0')
    {
        fprintf(stderr, "Invalid filename\n");
        return -1;
    }

    //open file
    FILE *t_fd   = fopen (in_filename, "r");

    if (t_fd == NULL)
    {
        fprintf(stderr, "Error opening input file: %s\n", in_filename);
        return -1;
    }

    //read individual settings lines
    char t_firstChar;
    while(fscanf(t_fd, " %c", &t_firstChar) == 1 )
    {
        if(t_firstChar != '/' && t_firstChar == '#')
        {
            // Not a comment so read the key value pair
            fseek(t_fd, -1, SEEK_CUR);

            if(fscanf (t_fd, ConvString, t_key, t_value) == 2)
            {
                printf("%s -- %s \n", t_key, t_value);
            }
        }

        // Ignore the rest of the line.
        fscanf(t_fd, "%*[^\n]");
        // Don't need this line as the scanf() in the while will ignore '\n' as white space.
        // But I have left it in for clarity.
        fscanf(t_fd, "\n");
    }

    return 0;
}


To achieve that the first thing for me would be to move your logic away from the view in a MVP way.

With that in place you could use a observer/observable pattern to wrap that logic in a different class that would be triggered when that event happen.

The problem with this is when your onMeasure is triggered before the addObserver is ran, this of course would end up with the decodeAndResizeFromResource() not running on that first call. A way to fix that, if it is an issue, could be using CustomPresenter constructor to make the values manually or use some default values and make that first call.

Something like this:

import java.util.Observable;
import java.util.Observer;

public class CustomPresenter extends View implements Observable {

    private Bitmap mBackground;
    private List observers = new ArrayList();

    public CustomPresenter (Context context) {
        super(context);
    }

    public CustomPresenter (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomPresenter (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        hasChanged();
        notifyObservers();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(mBackground, 0, 0, mPaint);
        super.onDraw(canvas);
    }

    public Map getHugeBitmap(){
        return this.drawable.huge_bitmap;
    }

    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public void notifyObservers() {
        for (Observer ob : observers) {
            ob.update(this);
        }
    }
}

Then the "View"

    public class CustomResizerView implements Observer{
       public void update(Object obj){
           CustomPresenter view = (CustomPresenter) obj;
           mBackground = decodeAndResizeFromResource(view.getResources(),
                   view.getHugeBitmap, view.getMeasuredWidth(), view.getMeasuredHeight());
       }
}

Then the test

public class Test {
    public static void main(String args[]) {
        CustomPresenter view = new CustomPresenter();
        CustomResizerView resizer = new CustomResizerView();
        view.registerObserver(resizer);
    }
}


Hang on a tick... there is a problem here that, weirdly nobody has noticed. I will admit that this is hardly ever used, but still:
In a normal JS prototypal inheritance scenario, you would be able to pull stunts like these:

var Animal = (function()
{
    function Animal()
    {
        this.name = this.constructor.name;
    };
    Animal.prototype.walk = function()
    {
        return this.name + ' is walking';
    };
    return Animal;
}()):
var Cat = (function(parent)
{
    function Cat(name)
    {
        this.name = name || this.constructor.name;
    };
    Cat.prototype = new Animal;
    Cat.prototype.constructor = Cat;
    Cat.prototype.sleep = function()
    {
        return this.name + ' is sleeping';
    };
    return Cat;
}(Animal));
var garfield = new Cat('Garfield');
//code
var newSameClass = new garfield.constructor();

Whereas the extends method you have written causes infinite constructor recursion: you're declaring a new function, that uses the this keyword... but because it's being used with the new keyword, it creates a new instance of itself (temp).
In the constructor of temp, all it does is equate its prototype to its own instance... you create an object that is its own prototype and therefore effectively is not part of any chain (it keeps on pointing to itself) and for some bizarre reason, you expect this to keep track of the constructor? I think what you ought to write is this:

Function.prototype.extends = function(parentClass)
{
    var temp = this.prototype.constructor;
    this.prototype = new ParentClass;
    this.prototype.constructor = temp;
};

Which works just fine, and doesn't require some temp constructor/object at any point.
Just try it with this simple example:

function Animal(){};
function Cow(){};
Cow.extends(Animal);
function Bird(){};
function Chicken(){};
Bird.extends(Animal);
Chicken.extends(Bird);
var dinner = new Chicken();
console.log(dinner instanceof Animal);//true -- sorry vegetarians
console.log(dinner instanceof Cow);//false -- no beef tonight
console.log(dinner instanceof Bird);//true -- mmm, poultry
console.log(dinner instanceof Chicken);//true -- roasted, probably

Which is, I take it, what you wanted.
PS: I would strongly advise you not to augment prototypes you don't own. By that I mean Object, Array, Function, Date and the like... Save for a few cases where the String prototype poses X-browser issues (String.trim wasn't implemented in IE8, for example).
You might encounter issues with other toolkits/libs, future updates, issues depending on the implementation (IE, FF and V8 deal with native prototypes differently in some cases)

All in all, it's best to leave them be... I see no reason why you shouldn't simply write a function, and not attach it to the prototype. Or, if needs must, do what ECMA is doing: all these createObject-like thingies go into one big bin: Object as in Object.getOwnPropertyNames() and Object.getPrototypeOf(). What's so difficult about:

function extend(child, parent)
{
    var prto, Object.getPrototypeOf(child),
        tmp = prto.constructor;
    prto = new parent;
    prto.constructor = tmp;
    return child;//<-- this might be handy
}
//usage:
var garfield = new (extends(Cat, Animal))('garfield');


Simple retrieving sessionId rows from indexed SQL column is slow

I think the bottleneck is in IQueryable<Model.Tracker.MilestonesInSession> GetAll() because it looks like you are executing that query into memory by creating a new Model.Tracker.MilestonesInSession
Try this:

public IQueryable<MilestonesInSession> GetSpecifiedMilestonesInSessionObjects(long sessionId)
{
    var allMilestones = from milestoneSession in
                        _dataContext.Repository<Linq.TrackerMilestonesInSession>()
                        select new {
                                     MilestoneId = milestoneSession.MilestoneId,
                                     CreatedDate = milestoneSession.CreatedDate,
                                     SessionId = milestoneSession.SessionId,
                                     ProductId = milestoneSession.ProductId,
                                     TrackerId = milestoneSession.TrackerId,
                                     StatusId = milestoneSession.StatusId,
                                     BankId = milestoneSession.BankId
                                   };
      var query = from m in allMilestones
                  where m.SessionId == sessionId
                  select new Model.Tracker.MilestonesInSession
                  {
                    MilestoneId = m.MilestoneId,
                    CreatedDate = m.CreatedDate,
                    SessionId = m.SessionId,
                    ProductId = m.ProductId,
                    TrackerId = m.TrackerId,
                    StatusId = m.StatusId,
                    BankId = m.BankId
                  };
      return query;
}


Algorithm to rotate array elements in Ruby

Your algorithm is \$O(N*M)\$ where:
\$N\$ = size of array
\$M\$ = steps

It's possible to do an array rotation that's \$O(N)\$, regardless of the number of steps you specify though.

Start by thinking of the array as two pieces, separated at "steps" indices into the array. For example, if you're going to rotate by 4, then mentally separate it into array[1..5] and array[5..N].

To do the rotation, start by reversing each of those pieces. Then reverse the entire array, something on this order:

for j in 1...steps/2
    temp = array[j]
    array[j] = array[steps-j+1]
    array[steps-j+1] = temp
end

for k in 1...(array.size-steps)/2
    temp = array[steps+k]
    array[steps+k] = array[array.size-k+1]
    array[array.size-k+1]=temp
end

for i in 1...array.size
    temp = array[i]
    array[i] = array[array.size-i+1]
    array[array.size-i+1] = temp
end

Note: I'm more accustomed to C-style arrays, where indexes start at 0 instead of 1. I've tried to compensate appropriately, but I haven't tested this, so I wouldn't be surprised if there were still a few off-by-one errors.

This steps through the entire array twice, regardless of the size of rotation, so it's likely to be slower than yours for steps=1, about the same speed for steps = 2, and faster for steps > 2.


Project Euler problem #14 (longest Collatz chain) in Swift

Some suggestion to improve your code:

The global variables max and originalNum should be named differently to match their purpose, possibly with explaining comments.
The global variable x is used to keep track of the length of the current Collatz chain, this is better done by making the function return a value. That also allows to eliminate the second
originalNumber parameter.
collatzFunc() should just compute the Collatz chain length for a
given number, and the caller of that function should compare that with previously computed values.
Why assign var num = number if that value is then overwritten?
You can simplify that to

let num = number % 2 == 0 ? number / 2 : 3 * number + 1

The indenting is not always correct, and the spacing is not
consistent (e.g. always put a space before opening curly braces).
The challenge asks for a number below 1 million, therefore the
loop must be

for number in 1..<1000000 { ... }

and the singular form number is more appropriate here.

Putting it all together, this is how I would modify your code:

/// Compute the length of the Collatz chain starting at `number`.
func collatzFunc(number: Int) -> Int {
    if number == 1 {
        return 1
    }
    return 1 + collatzFunc(number: number % 2 == 0 ? number / 2 : 3 * number + 1)
}

var maxLength = 0 // Maximal length of Collatz chain found so far.
var maxNumber = 0 // Number for which this length is achieved.

for number in 1 ..< 1_000_000 {
    let length = collatzFunc(number: number)
    if length > maxLength {
        maxLength = length
        maxNumber = number
    }
}

print(maxNumber)

This is perhaps not faster than your version, but definitely better to read and therefore better to maintain.

You can also replace the recursive function by an iterative version

/// Compute the length of the Collatz chain starting at `number`.
func collatzFunc(number: Int) -> Int {
    var length = 1
    var num = number
    while num != 1 {
        num = num % 2 == 0 ? num / 2 : 3 * num + 1
        length += 1
    }
    return length
}

and check if that performs better.

As already mentioned in the comments, caching (or memoization)
increases the performance dramatically. You'll find some caching
solutions in the various answers to
Project Euler problem 14 (longest Collatz sequence) in Swift 3.
Here is a version using an array to cache all results for
number up to a certain limit, this turned out to be quite fast:

var cache = [Int](repeating: 0, count: 1_000_000)
cache[1] = 1

func collatzFunc(number: Int) -> Int {
    if number < cache.count && cache[number] > 0 {
        return cache[number]
    }
    let length = 1 + collatzFunc(number: number % 2 == 0 ? number / 2 : 3 * number + 1)
    if number < cache.count {
        cache[number] = length
    }
    return length
}


What is the most optimal way to concat XML files as one large string/text file?

functions
Your script does a few things

iterate over the files
recursively iterate over the subdirectories
parse the files
concatenate the results

Better would be to separate those in different functions.
The extra advantages is that you can test these functions separately, you can document them with a docstring, and add typing information
comments
You comment what the code does. Python is luckily so expressive that almost anyone can understand what a particular line does. what is more difficult is the why you do certain steps, and why you do them in a certain order. This is what should be commented
global variables
Your big_file method changes the global state of the program. That makes it more difficult to reason about, and also makes it difficult if you want to use this methon on 2 separate directories. Here you append to big_text. If you want to keep it like this, I would pass it on as a function parameter, instead of a global variable
def big_file(path, big_text = None):
    if big_text is None:
        big_text = []

    ...
            big_file(path + '/' + i, big_text=big_text)

pathlib.Path
Most file operations are simpler when using the pathlib  module. It will be a lot more robust than manually concatenating paths like in path + '/' + i
error handling
You have a try-except block with a bare except. Better here would be to catch the errors you expect specifically and handle those, and let other, unexpected error bubble up. Fail hard, fail fast, instead of covering up bugs can help you write more stable and correct software
logging
Instead of using print, you can use the logging module. That way you can make a distinction between different levels of importance, and filter some out if needed
generators
To prevent a MemoryError you can use generators. these are special functions that do their work piece by piece, and can work without keeping the whole structure in memory
You can have 1 generator generate the files
def iterate_files(path: Path) -> typing.Iterator[Path]:
    """Recursively iterates over `path`, yielding all the correct files"""
    for file in path.glob("*"):
        if file.is_dir():
            yield from iterate_files(file)
        else:
            # or a check that the file has a certain suffix
            yield file

Then you feed this iterator to the parser generator
def parse_files(files: typing.Iterator[Path]) -> typing.Iterator[str]:
    """Parse the xml files."""
    for file in files:
        try:
            xml = ET.parse(path + '/' + i).getroot()
            yield ET.tostring(xml, encoding='unicode')
        except <stricter exception>:
            logging.warn(f"error in {file}")
            raise

In the last except, you can have different except blocks with different result
You can then feed this to another generator which writes it to a file:
def write_to_file(
    text_iterator: Typing.Iterable[str], output_filehandle: typing.TextIO
) -> Typing.Iterable[str]:
    for chunk in text_iterator:
        output_filehandle.write(chunk)
        yield chunk

putting it together
if __name__ == "__main__":
    path = Path("PLC 2360")
    files = iterate_files(path)
    parsed_filed = parse_files(files)

    with Path(<output_path>).open("w") as output_filehandle:
        parsed_filed_after_writing = write_to_file(
            text_iterator=parse_files, output_filehandle=output_filehandle
        )
    ...

In that last part, I've opened the file in the main part of the script, taking into account the principles of clean architecture


C++ Implementation of a dictionary data structure

The representation (as a parallel pair of vectors) isn't as good as the alternative (a single vector of pairs), because:

any time the vectors have to grow, there's two separate allocations rather than just one, and
whenever they are used, the data may be in different regions of memory (the code has poorer spatial locality).

Consider instead writing

using value_type = std::pair<T, U>;
std::vector<value_type> entries;

This will change the interface a little - in particular, begin() and end() will now give iterators that access these pairs.  That's more consistent with std::map interface, so I recommend that.

We can reduce duplication a little: in the initializer-list constructor, we can simply call add() for each element rather than re-writing its body:

template <typename T, typename U>
Dictionary<T,U>::Dictionary (std::initializer_list<std::pair<T,U>> store)
{
    for (std::pair<T,U> object : store) {
        add(object.first, object.second);
    }
}

On the other hand, if we've changed our representation as above, we simply have

template <typename T, typename U>
Dictionary<T,U>::Dictionary (std::initializer_list<std::pair<T,U>> store)
{
    for (std::pair<T,U> object : store) {
        entries.push_back(object);
    }
}

The indexing operator is surprising.  If key doesn't exist in the dictionary, then we have undefined behaviour (accessing values out of range).  That's a valid choice, but worthy of a comment (particularly as it diverges from the Standard Library interface).  Since it doesn't create as necessary, and only ever returns a copy of the value (rather than a reference) it probably ought to be declared const.

We should probably check whether key already exists in add().  We can then either ignore it, or update the existing value.  What we have at the moment is the worst possible choice - we add data that can never be used, which only serves to slow future operations.

Some other useful accessors are missing - constant and/or reverse iterators spring to mind as an obvious example, as do methods of removing values.  A swap() member would also be very useful.

The has function can be simplified a bit with the use of a standard algorithm: std::any_of() can replace the loop.

Algorithmic complexity

Our operator[] uses linear search with std::find().  Whilst this works, it will get slower in proportion to the number of elements contained - in "big O" notation, we say that it scales as O(n).  Once we have the interface as we we want, we'll then want to look at changing the data structure to improve look-up times (and we might need to trade against insertion speed).  The good news is that storing items as pairs will work well with whatever storage we choose, and it will be much easier to change the implementation than with separate storage of keys and values.

It may well be worth moving to pair-based storage, and implementing the other review items, and then returning for a performance review of the new code.


Find next bigger number with same combination of digits

You convert number to array can be simplified by first converting the number to a string and then splitting on nothing:

var convertToNumArray = function(num){
    return num.toString().split('')
}

This will of course convert it to an array of strings, but that will work perfectly fine for your purposes (or you can always throw in a map to convert back to ints).

Your first loop (noted with this comment):

// iterate from right most number to find out the
// number which is less than previous one.

You don't need the else { continue }.  It is at the end of the loop, so continuing is guaranteed.  Sometimes explicit is nice but I would say not to the extend of writing code that doesn't actually do anything: that just makes for more code to read through.

Also, I don't think you have accounted for the possibility of a number that doesn't have a next value.  For instance, how does your code handle 54321?  Your swap index will stay at the initialized value of zero.  Either way, I think the smart thing to do is to detect this event happening and exit prematurely, as you already have the answer: there is no room for changes.

Your second for loop looks solid.  I might organize it a little differently but no actual complaints: just a different coding style.

For your last bit, I wouldn't do the sort yourself.  Use the built in javascript sort.  You can slice off the end of the array, use sort() (keep in mind that it sorts asciibetically, but that shouldn't hurt you here), and then splice it back onto the end.


Validating user input
The way that you capture user input is quite brittle. While it will work fine as long as the user knows they should only input integers, it's never safe to assume that users will provide valid input:
What would you like to do?:  hello
Exception in thread "main" java.util.InputMismatchException

We first need to handle this InputMismatchException for cases where the user enters an invalid value, by using try-catch:
try {
    choice = cai.nextInt();
} catch (InputMismatchException exc) {
    System.out.println("Invalid input");
}

This is not quite right yet, though; even though it handles the exception and prevents a program crash, we need to not leave this block until we actually have input we can use. So let's introduce a validation condition and a while loop:
int choice = 0;
boolean inputIsInteger = false;
while (!inputIsInteger) {
    System.out.print("\nWhat would you like to do?: ");
    try {
        choice = cai.nextInt();
        inputIsInteger = true;
    } catch (InputMismatchException exc) {
        System.out.println("Input must be an integer.");
        cai.next();
    }
}

Now, that works pretty well:
What would you like to do?:  hello
Input must be an integer.

What would you like to do?:  1

Addition

You may think: "But, that seems like a lot of code to handle one single user input!"
And you would be right! Fortunately, Scanner has a built-in method hasNextInt() that does this in a much simpler way:
System.out.print("\nWhat would you like to do?: ");
while (!cai.hasNextInt()) {
    System.out.println("Input must be an integer.");
    cai.nextLine();
    System.out.print("\nTry again: ");
}
int choice = cai.nextInt();

This way our Scanner will keep looping until it finds a valid int in the input buffer, making it safe to then call nextInt().

So far, so good. Now, I noticed that you are needing to get integer inputs everywhere in your code... We could save us a lot of copying and pasting of the above code by making a method that does this for us:
private static int getIntInput(Scanner sc) {
    while (!sc.hasNextInt()) {
        System.out.println("Input must be an integer.");
        sc.nextLine();
        System.out.print("\nTry again: ");
    }
    return sc.nextInt();
}

Then, each time we need to scan for an int, we just call it with an instance of Scanner:
System.out.print("\nWhat would you like to do?: ");
int choice = getIntInput(cai);

You should also validate that the input is usable according to your program logic, for instance that the choice is a valid choice (i.e. 1 - 4) otherwise ask the user for valid input. This should be easily done using another while loop or some similar construct.
boolean isValidChoice = false;
int choice = 0;
while (!isValidChoice) {
    System.out.print("\nWhat would you like to do?: ");
    choice = getIntInput(cai);
    if (choice > 0 && choice <= 4) {
        isValidChoice = true;
    } else {
        System.out.println("\nChoose an option from 1 to 4: ");
    }
}

if (choice == 1){
    addition();
}
// etc...

Other things
Here are some other concerns & suggested improvements on the code.

Consider moving your menu selection out of main and into its own method, like calculatorMainMenu() and call that when you need it.

The (One / Two) calculation in your division() method can result in ArithmeticException due to possible division-by-zero error. You should validate Two to make sure that 0 is never acceptable as input.

Consider using a switch statement instead of a lot of if-else for things like your menu, where you're just comparing a variable against some constants.

Naming an instance of Scanner as cai is pretty odd. Writing something like scanner or sc for short is much more commonplace.

The names One and Two are also a bit odd. Something like num1 and num2 would be better, I think, to make it simple and clear that there's no particular significance to them other than the order in which they appear.

"Caluclator" should be spelled "Calculator"

Only the result of an addition is called "sum". To be correct, you should use "difference" for subtraction, "product" for multiplication, and "quotient" for division.


Refactor similar queries but reverse side of inequality operator

From what I can understand you are looking for a way to consolidate this code into one function and specify that the comparrison with minimum can either be less than or greater than or equal to. You could try something like this

public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseAtLeast(this IQueryable<T_COMPANY> query, int minimum, DateTime? date = null)
    {
        WhereTotalTransactionWithCompare(query, minimum, (x, min) => x >= min, date);
    }

    public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseLessThan(this IQueryable<T_COMPANY> query,
                                                                                int minimum,
                                                                                DateTime? date = null)
    {
        WhereTotalTransactionWithCompare(query, minimum, (x, min) => x < min, date);

    }

    public static IQueryable<T_COMPANY> WhereTotalTransactionWithCompare(this IQueryable<T_COMPANY> query,
                                                                                int minimum,
                                                                                Func<int, int bool> compareToMinimum,
                                                                                DateTime? date = null)
    {
        if (date == null)
        {
            query = query.Where(company => (company.Products.Count + company.References.Count) >= minimum ||
                                         (comparer(company.T_RFQs.Count + company.T_POs.Count + company.T_INVOICEs.Count, minimum)));
            return query;
        }
        else
        {
            var notNullDate = date.Value;

            var result = (from company in query
                          let rfqCount = company.T_RFQs.Count(item => item.create_date <= notNullDate)
                          let poCount = company.T_POs.Count(item => item.create_date <= notNullDate)
                          let invoiceCount = company.T_INVOICEs.Count(item => item.create_date <= notNullDate)
                          let productCount = company.Products.Count(item => item.create_date <= notNullDate)
                          let referenceCount = company.References.Count(item => item.create_date <= notNullDate)
                          where (rfqCount + poCount + invoiceCount) >= minimum || comparer(productCount + referenceCount, minimum)
                          select company);

            return result;
        }

    }


Disclaimer: Not a Code Reviewer
Just some comments:

Looks not bad at all;

First thing first, read through PEP8 if you like – I should also do that myself ( ˆ_ˆ )

Name things just a bit more descriptive, I understand that math people code like that and use single variable naming a lot;

Comment concise (one perfect scenario – which does not exist – would be the understandability of the code without any comment);

Use unittest if you like;

Turn on your IDE's spell checking;

Not sure about what we are doing overall, but my guess is that we might be able to start the second loop from the row + 1:

def get_linear_calc(x: float, y: float, coeff: float) -> float:
    """
    param x:float, x coordinate
    param y:flaot, y coordinate
    param coeff:float, parameter of the curve
    """
    return x + (y * coeff)

def get_ordered_sequence(x, y, coeff):
    """
    algorithm:
    Suppose arrays are ordered by their index and NOT the element inside
    Go through an ordering which meets that (one ordering is enough)
    add on the function curr that point to the sequence
    """
    seq = [0.0] * len(x)
    for row in range(len(x) + 1):
        for col in range(row + 1, len(x) + 1):
            for curr in range(row, col):
                seq[curr] += get_linear_calc(x[curr], y[curr], coeff)
    return seq

if __name__ == "__main__":
    x = (1.0, 2.0, 3.0, 2.0)
    y = (2.0, 3.0, 4.0, 1.0)
    coeff = 2.0
    print(get_ordered_sequence(x, y, coeff))

PS: I don't name things well, ignore my naming.