Instead of starting a new thread you can instead create a executor which will take Runnables and reuse threads as needed. you can create a executor usign one of the Executors' static factories.

This code relies on getTrustedTicket() responding correctly to a thread interruption. Which you didn't include so I can't judge it. (A lot of IO functions don't respond to it by default).

The catch-all when waiting on the result is not a great thing. You should instead catch only the specific exceptions you can get and only declare those you throw.

try {
    authTicket = future.get(10000, TimeUnit.MILLISECONDS);
    log.info("authTicket: "+ authTicket);
    return authTicket;
} catch (InterruptedException e){
    log.warning("Current thread interrupted while waiting to get auth ticket: Reason:"+ e);
    future.cancel(true);
    Thread.currentThread().interrupt(); //reset interrupted state or rethrow the exception.
} catch (ExecutionException e){
    log.warning("Exception occured getting the auth ticket: Reason:"+ e.getCause());
} catch (TimeoutException e){
    log.warning("Timeout occurred while waiting to get auth ticket: Reason:"+ e);
    future.cancel(true);
}


Finding the most frequent character in a string

If you are intended to measure the frequency of bytes, as the name of your input string seems to suggest, rather than just lowercase ASCII letters, then your holder array should be 256 elements long.

This also saves you from all the additions and subtractions of the 'magic' number 97. (Seriously, you could have used 'a'.)

Also, your holder array should consist of ints not chars, because if a certain byte appears more than 256 times in your input string the char will wrap around to zero. Also an array of ints will probably perform more efficiently due to memory alignment.


ASP.NEt Core thread safe global variable

Since you use Interlocked.Increment(ref _runCount) than the operation is thread-safe if the value is already initialized.

Interlocked is a class designed just for the case when you need to share primitive type value between threads. Regarding to .NET Framework documentation: "Interlocked Class provides atomic operations for variables that are shared by multiple threads." See the documentation for more details.

You can also see a similar question without ConcurentDictionary aspect on Stack Overflow: C# variable thread safety.

Lazy initialization and ConcurrentDictionary are used here for the scenario when two concurrent threads try to initialize value, however, they both see that the value is not initialized, so they both start to read from a database and initialize the new value.

With lazy initialization in ConcurrentDictionary when concurrent Thread B completes the invocation after Thread A, it discards the value it has created and uses (increments) the value that Thread A already created.

Your code is exactly the same as this one where you can find a more detailed explanation of your code including steps why each part of your code is important.

So, if your question is whether the value _runCount is thread-safe in your code snippet and whether is it the right solution, the short answer is: Yes, it is and all parts of the code are important for your described use case.


There are 2 main changes I would make:

ProductService.addManualProduct seems to require a callback. A way that is more consistent with Angular, and with a number of benefits, would be to return a promise, so you can use it like:

ProductService.addManualProduct(params).then(function() {
  // Do something
});

Using $rootScope should be avoided if there is an alternative, as it's effectively global over the entire app. One way, would be to change the $rootScope.$broadcast to $scope.emit, which can be "picked up" by a directive on some parent element. So you could have a template like:

<div notification-center>
  <div ng-controller="myController">
     <!-- Buttons here to create/unreserve -->
  </div>
</div>

And in myController, $emit an event:

$scope.$emit('notificationCenter::create', someData);

Then in a notificationCenter directive's controller, you can listen to this

{
   controller: function($scope) {
     $scope.$on('notificationCenter::create', function(e, data) {
       // Do something, like display the message
     });
   }
}

An alternative approach would be to have the notificationCenter directive inside the template controlled by myController, and then use $scope.$broadcast to send messages to it.

The "clean" aspect of this is that you could potentially have separate areas of the app, with separate notification areas, if you wish.


If your graph becomes big (or rather if a node has many connections), node_2 in self.array_representation[node_1] might take a long time, because in is O(n) for lists. Therefore I would use a set for the connections of a node. You don't even needed to change a lot:

class Graph:

    def __init__(self, nodes):
        self.connections = [set() for _ in range(nodes)]

    def directly_connected(self, node_1, node_2):
        """Predicate, checks if the two nodes are connected by one edge"""
        return node_2 in self.connections[node_1]

    def connect(self, node_1, node_2):
        """Draws an edge between the node at node_1 and the node at node_2"""
        self.connections[node_1].add(node_2)
        self.connections[node_2].add(node_1)

And while I was at it, I promoted your comments to proper docstrings. Now you can do help(Graph.connect) in an interactive session.

I also changed the name of the internal representation to self.connections.


Just to add to @flodel's comments, here is a properly vectorized version. One can see this is quite a bit faster, outperforming the parallel option (on 7 cores) by a factor 5. This problem is a quite nice demonstration of why is is worth your time to think about vectorized code:

flodel_fizzbuzz <- function(range = 100, fizz = 3, buzz = 5) {
  s <- 1:range
  is.fizz <- s %% fizz == 0
  is.buzz <- s %% buzz == 0

  s[is.fizz] <- 'Fizz'
  s[is.buzz] <- 'Buzz'
  s[is.fizz & is.buzz] <- 'FizzBuzz'
  return(s)
}

Running the benchmarks from @Gerard's answer (note that vectorizedFizzBuzz isn't truly vectorized):

Unit: milliseconds
                      expr       min        lq      mean    median        uq       max neval  cld
      applyFizzBuzz(range) 296.52224 303.19205 315.76901 309.18860 320.01676 384.18786    20   c
 vectorizedFizzBuzz(range) 341.41121 356.82580 374.53857 362.45300 372.81459 461.65169    20    d
   parallelFizzBuzz(range) 117.40058 128.91812 158.66095 153.87976 170.76776 288.99613    20  b
  papasmurfFizzBuzz(range) 292.22177 301.48002 316.31151 307.31605 319.05426 393.53235    20   c
    flodel_fizzbuzz(range)  27.98101  29.15677  29.93554  29.93097  30.84586  32.09304    20 a

I do think functions are a nice way to perform these tasks.
The easiest way to create a range of subsequent integers is with :.

This tidyverse version does about equally well (with ~40 ms):

tidy_fizbuzz <- function(range = 100, fizz = 3, buzz = 5) {
  x <- 1:range
  dplyr::case_when(
    x %% (fizz * buzz) == 0 ~ "Fizz Buzz",
    x %% fizz == 0 ~ "Fizz",
    x %% buzz == 0 ~ "Buzz",
    TRUE ~ as.character(x)
  )
}


Oh woah! xD It's just.. woah! What patience you have to write all those variables.

Well, it's Java so you can use a HashMap.

Write something like this:

String str = "Hello World";
int len = str.length();
Map<Character, Integer> numChars = new HashMap<Character, Integer>(Math.min(len, 26));

for (int i = 0; i < len; ++i)
{
    char charAt = str.charAt(i);

    if (!numChars.containsKey(charAt))
    {
        numChars.put(charAt, 1);
    }
    else
    {
        numChars.put(charAt, numChars.get(charAt) + 1);
    }
}

System.out.println(numChars);

We do a for loop over all the string's characters and save the current char in the charAt variable
We check if our HashMap already has a charAt key inside it

If it's true we will just get the current value and add one.. this means the string has already been found to have this char.
If it's false (i.e. we never found a char like this in the string), we add a key with value 1 because we found a new char

Stop! Our HashMap will contain all chars (keys) found and how many times it's repeated (values)!


Not too much to review as the code uses evhttp to handle HTTP and provide a basic, static reply for each request.

Why is host constexpr, but not the port?

All those using statements, combined with traits and decltype one after the other makes the code very hard to read, almost obscuring the fact that evhttp is being initialized at that point. I would try to rewrite that part in a simpler way.

Why auto main() -> int instead of the simple, classic int main()?


JavaScript event handlers, scope, and the module design pattern

The way I like to use the module partern is in combination with the Oberserver pattern. I've included detailed comments in the code to help explain the two a bit. I would highly recomend you watch this video by Jeffery Way. He does a really nice job of explaining the two and also some custom events, which I think you might be interested in. Also read the links he puts under the video, they'll provide you with a complete understanding of it all.

I explain most of it in the code with comments. Anyways the following code will help you get the picture:

(function ( $, window, document, undefined ) {
   "use strict";

    var PROJ = {
        init: function() {
            //Set up my Observer Pattern
            var o = $( {} );
            $.subscribe = o.on.bind(o);
            $.unsubscribe = o.off.bind(o);
            $.publish = o.trigger.bind(o);

            //By using the object PROJ you can reference it with "this" (i.e. this.whatever();), easy peazy "namespacing"
            //Example:
            this.setUpListeners();
        },

        setUpListeners: function() {
            $('#tools #paintbrush').on('click', function() { PROJ.enablePaintbrush() };
            $('#tools #move').on('click', function() { PROJ.enableMove() };
            $('#tools #select').on('click', function() { PROJ.enableSelect() };
            $('#tools #eraser').on('click', function() { PROJ.enableEraser() };

            //Here is where the Observer Pattern kicks in nicely
            //I'm done with the listeners, and I'm letting everyone that is subscribed know that.
            //You can also namespace easily with "/" like so: ("enable/Select") or ("enable/Move") etc.
            $.publish( "listeners/are/set/up" );
        },

        enableSelect: function() {
           //do some stuff

           //I'm done with "enable", and I'm letting everyone that is subscribed know that.
           $.publish( "enable" );
        },

        enablePaint: function() {
           //do more stuff

           //When enable is published, run enableMove
           $.subscribe( "enable", this.enableMove( //You can pass arguments here to other functions, limiting the scope );
        },

        enableMove: function() {
            //In a callback "this" refers to the element in question, and not to the PROJ object

            //You can cache it out here:
            var self = this

            $("#something").on( "click", function() {
                //To resolve that you can also cache the reference in here
                var self = PROJ

                //this will work
                self.enableMove();

                //this will not work because we are in a callback
                this.enableMove();

                //You can use your Pub/Sub model anywhere, even in callbacks
                $.publish( "done/with/this/baby" );
            });
        },

        enableEraser: function() {
            $.subscribe( "done/with/this/baby", this.enableSelect() );
            //Just like that I've created a loop, by calling enableSelect it goes back and runs it again.
        } //The last closing braquet doesn't have a comma
    }; //Close the PROJ object

    //Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.
    PROJ.init();
})( jQuery, window, document );

Hopefully that provided some insight. If there's any part which needs clarification I'll be happy to explain.


Copy first n lines of each file in a directory

requires / or \ at end.

Your code requires that the user supplied source and destination
directories end in a path name separator. A better approach is
to simply add it. See the comments below on the (</>) operator.

partial functions

When processing the command line arguments you
are using functions which could throw errors, e.g. read, head, !!.
When they fail you'll get a generic error message like Prelude.read: no parse or Prelude.!!: index too large.

Hackage has libraries you can use to parse and validate command line arguments
like cmdargs or any of the optparse- packages. However, it's not too difficult to roll your own like this:

 import Data.Char

 parseArgs (nstr : source : dest : _) =
   if all isDigit nstr
     then ( read nstr, source, dest )
     else error "first argument is not a number"
 parseArgs _ = error "not enough arguments"

main = do
  args <- getArgs
  let (n, source, dest) = parseArgs args
  ...

parseArgs checks that there are at least three command line arguments and
also that the first one consists entirely of digits.

(++)

Currently the FilePath type is a String, so using (++) to join
together path name segments is fine. However, in System.FilePath
Haskell defines the operator (</>) which is meant to be a cross-platform
way to do this - i.e. on Windows it will use \\ and on Posix systems it
will use a /. Moreover using (</>) signals to the reader that you are
working with a path name string.

The module System.FilePath also has utility functions for dealing with
path names such as extracting the base / directory name from a path, extracting and replacing the suffix, etc. which are good to know about and may come
in handy.

A good place to use (</>) is in your listFilesInDir function, e.g.:

listFilesInDir dir =
  getDirectoryContents >>= filterM (\x -> doesFileExist (dir </> x))

Now dir does not have to end in a / or \\ because using (</>) will
add the appropriate separator.

fileList

Note that fileList is an IO-action, so in these lines:

fileSources <-fmap (map (source ++)) $ fileList
fileSinks <-fmap (map (sink ++)) $ fileList

you are repeating the IO-action twice. That is, you are performing
getDirectoryContents twice on the same directory. Instead you
want to perform fileList
only once and use its result to compute fileSources and fileSinks:

leafNames <- listFilesInDir source
let fileSources = map (source </>) leafNames
    fileSinks = map (sink </>) leafNames
zipWithM_ (writeFirstNLines n) fileSources fileSinks

Note I'm using zipWithM_ here - it works just like zipWithM but discards
the results. It's more efficient because zipWithM_ discards the result of
the zip operation immediately, whereas zipWithM saves the results in a
list thus consuming memory for data you'll never look at.

hClose

In Haskell you need to explicitly close your file handles when you are done
with them. Every process has limit on the number of handles which can be open at any one time, so if you never close any handles then eventually openFile will fail when you hit this limit.

A basic way to make sure your file handles always get closed is to use
the withFile function:

withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r

withFile creates a file handle by opening a path with the specified IOMode
and passes the handle to an IO-action. It will ensure that the handle is
closed when the IO-action completes - whether it returns normally
or if an exception is thrown.

Using withFile your writeFirstNLines would look like:

writeFirstNLines n source sink = do
  withFile source ReadMode (\hin -> do
    withFile sink WriteMode (\hout -> do
      ... copy from hin to hout ...
    )
  )

Now both hin and hout will automatically get closed when the copy action
completes.

replicateM

Note that replicateM_ n action will always execute action
exactly n times - no more and no less. So this is not a good way
to write a loop which could be executed a variable number of times.

As an example of how inefficient using replicateM_ here could be,
suppose that n is 1000 and you are operating on a 3 line file.
Then:

replicateM_ n readAndWrite

will execute readAndWrite 1000 times even though the last
997 calls won't copy any lines.

Here is a recipe for a loop which is executed at most n times
with the possibility of breaking out early:

loop n | n <= 0 = return ()
loop n = do quit <- condition       -- check condition
            if quit
              then return ()        -- break out early
              else ... do stuff...
                   loop (n-1)       -- perform next iteration

You can use this to copy the first n lines by substituting:

condition        =  hIsEOF hin
...do stuff...   =  hGetLine hin >>= hPutStrLn hout


Let me know what I can improve on or what I'm doing poorly.

If you are going to do animations with those lines, you will want to keep track of them. I am assuming that is why you have an array of LINES. However, in createLine you create the SVG element and just return it, you do not keep a reference to it. So it will be hard to animate those lines, you would have to query the DOM to find them back.

I suggest you have an object that creates SVG elements, a factory so to speak. And then another object that tracks lines you have created so far, mostly to do animations and other fun stuff.

The factory object could be something like

SVG = {
  createCanvas : function( width, height, containerId ){
    var container = document.getElementById( containerId );
    var canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    canvas.setAttribute('width', width);
    canvas.setAttribute('height', height);
    container.appendChild( canvas );
    return canvas;
  },
  createLine : function (x1, y1, x2, y2, color, w) {
    var aLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    aLine.setAttribute('x1', x1);
    aLine.setAttribute('y1', y1);
    aLine.setAttribute('x2', x2);
    aLine.setAttribute('y2', y2);
    aLine.setAttribute('stroke', color);
    aLine.setAttribute('stroke-width', w);
    return aLine;
  }
}

Initially the lines object could be as simple as

var lines = [];
lines.addLine = function( line ){
 this.push( line );
 return line;
}

Your start function would then be something like

function start() {
  var canvas = SVG.createCanvas( 1000 , 400 , 'container' ),
      lineElement, i, x1;

  for (i = 1; i < 11; i += 1) {
    x1 = Math.floor(Math.random() * 500 / 2),
    lineElement = lines.addLine( SVG.createLine(x1, 0, 200, 300, 'rgb(0,0,' + x1 + ')', i) );
    canvas.appendChild( lineElement );
  }
}


Count number of previous elements greater than its element at present index

I don't think there is a logic error in what you have posted. And even though there are details that would make it nicer (the cycle can for example run from i=1, questionable use of bits/stdc++.h header, long variable scopes and similar), it should do its job.

I suggest to think about time complexity of the algorithm. Your brute force approach will have quadratic complexity and may be too slow when the input is large.

There are different approaches that you can try. For example, I see you tagged your post with binary-search tag. Why? You could for example keep your vector sorted as the user enters the values. When adding a new number, find where it belongs (you can do it by bisection - with logarithmic complexity). All numbers to the left are smaller, the ones on the right are larger. Then insert the number and repeat. How to do it exactly is up to you, if you're allowed to use C++ algorithms, std::lower_bound and std::vector::insert will do the hard work for you.

You can of course craft some tree structure of your own to do something along those lines.


It's clear, nicely formatted, and passes http://www.shellcheck.net/# with flying colors. I have only minor nitpicks.

The variable name command_line is too generic.
If you make it more descriptive,
for example start_command,
then the purpose of the pgrep line becomes easier to understand:
it should match whatever was used to start the command.

This maybe a matter of taste, but I like to place the ;; in case statements at the same indent level as the body of the statement, for example:

case "$1" in
    start)
        start
        ;;       # aligned with the commands, not the label
    stop)

I'm not really aware of a standard, but for what it's worth,
Vim's auto-indent function (and auto-reindent with gg=G) indents this way.
This writing style is also practical when folding is enabled in Vim,
making long case statement blocks appear like this:

case "$1" in
    start)
        --- # folded lines
    stop)
        --- # folded lines
    restart|force-reload)
        --- # folded lines

Well, this is really a nitpick, and a matter of taste,
your way is perfectly fine too.


First of all, the Lexicon class reinvents Counter from collections. Maybe subclassing can help.

Second, I'd separate persistence from the class because it's completely orthogonal to the Counter functionality (see below about shelve).

Pickle/unpickle does not represent any memory leaks. As soon as noone uses the dict, it's gone.

Then, using file (with pickled data) is not thread-safe. Depending on how you wish to implement storage for the counter, you may be interested in file locking.

There is also shelve module in Python, which may help with storing lexicons (though, it is not thread-safe).

Hard to say what is your case now or in the future, but you may want to use some special purpose file-based storages, which are designed for performance and concurrency. For example, sqlite.

Minor notes:

in Python, it is possible to make equality comparison by defining __eq__ method (and the mentioned Counter class just does it - no need to make any special provisions), same for the size - in Python it's usually len(), and in case of a Counter there is no need to make another method - size (may need __len__ method if Lexicon is not inherited from some dict)
thread-safety of the add (if you still use it) can be fixed by using setdefault method with consequent += 1 (actually, not sure - you may need thread lock - https://stackoverflow.com/questions/23547604/python-counter-atomic-increment ). Atomicity of collections Counter's update needs to be checked and wrapped.
as for performance, you can check with Python's timeit

If you insist on preserving your add method, you can consider a rewrite:

self.dictt.setdefault(token, 0)
self.dictt[token] += 1

(again, check if this is faster than self.dictt[token] = self.dictt.get(token, 0) + 1 ). Also this discussion may be relevant: It provides defaultdict implementation, which looks even simpler than the Counter one.

Note on concurrency: It's a bit fragile to assume multi-threading-only. For example, some misconfiguration can make your application multiprocess one. In that case you will have arbitrary results in the file, even if you will have both thread locks and file locks. Maybe, this concern is not a problem in your settings, but if you care about having terms counted right, you may need to make only single process to control the file, all others just requesting adds to that process. Actually, a counter is something, which despite simplicity of the operation (just add one!), may cause concurrency problems and inefficiency problems with high-velocity data. All kinds of optimizations may be needed to implement a high-performance counter correctly (just one of the first examples google gives: three components in the solution, uses relational database and memcached). But elaborating on that is out of scope in this answer.


A Sub-string Extractor with Specific Keywords Parameter Implementation in C#

I tend to have the "error handling" code at the beginning of the method, which usually makes the rest of the method more simple.
private static string GetTargetString(string input, string startKeyword, string endKeyword, StringComparison comparer)
{
    if (!string.IsNullOrEmpty(startKeyword) && input.IndexOf(startKeyword, comparer) < 0) return "";
    if (!string.IsNullOrEmpty(endKeyword) && input.IndexOf(endKeyword, comparer) < 0) return "";

    var startIndex = string.IsNullOrEmpty(startKeyword)
        ? 0
        : input.IndexOf(startKeyword, comparer) + startKeyword.Length;

    var endIndex = string.IsNullOrEmpty(endKeyword)
        ? input.Length
        : input.IndexOf(endKeyword, comparer);

    if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex) return "";

    return input.Substring(startIndex, endIndex - startIndex).Trim();
}


I think you must change your die/echo mechanism to something another. Like a throw exception or return a status from the function.

if ( ! $stmt->execute() ) {
  echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

And in this part you must not echo error, but return/throw it. Because if you just print it, your code will work further.

Also you must rewrite updateDataIntoTable like this:

function updateDataIntoTable($mysqli, $tableName, $databaseName, $array ,$idFeildName , $idFeildValue) {
  $dataArrayCount = count($array);
  if ( 0 == $dataArrayCount ) {
      return;
  }
  ...
}

This is called guard statement. Better to keep all returns at top or bottom function.


Generate a matrix of booleans from another one

You can make this function more generic so that you can use reuse it where necessary and with any type. Currently your code is doing three things:

Loop over the matrix.
Checking a condition.
Modifying the elements.

This can be separated and encapsulated. You first create a general-purpose extension that just loops over any matrix, checks the passed predicate and calls the action:

public static T[,] ForEach<T>(
    this T[,] m,
    Func<T, bool> predicate,
    Action<T, int, int> action
)
{
    for (int x = 0; x < m.GetLength(0); x++)
        for (int y = 0; y < m.GetLength(1); y++)
            if (predicate(m[x, y])) action(m[x, y], x, y);

    return m;
}

Example:

Assuming you have these two matrices

var m1 = new[,]
{
    { false, false, false, false },
    { false, true, false, true },
    { true, true, false, false },
    { false, false, true, true }
};

var m2 = new[,]
{
    { false, true, true, false },
    { false, true, false, true },
    { true, true, false, false },
    { false, false, false, false }
};

you call the new ForEach extension like this where you first filter the items with !m so that you get only those where m = false, then you update the second matrix at the coordinates [x, y] with the value m of the first matrix.

m1.ForEach(m => !m, (m, x, y) => m2[x, y] = m);


I want reduce the time complexity for this ladder problem to find the minimum ladders required

Applied few minor optimisations to the code from the OP's answer. Also fixed naming issues (locals name starts from a lower-cased letter).
class Program
{
    static void Main(string[] args)
    {
        int t = int.Parse(Console.ReadLine());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < t; i++)
        {
            int n = int.Parse(Console.ReadLine());
            int[] numOfStairs = new int[n + 1];
            int floorsMarked = 0;
            string[] str = Console.ReadLine().Split();
            for (int j = 0; j < str.Length; j++)
            {
                int length = int.Parse(str[j]);
                int reach = j + length > n ? n : j + length;
                while (floorsMarked < reach)
                {
                    floorsMarked++;
                    numOfStairs[floorsMarked] = numOfStairs[j] + 1;
                }
                if (reach == n)
                    break;
            }
            int q = int.Parse(Console.ReadLine());
            for (int j = 0; j < q; j++)
            {
                int target = int.Parse(Console.ReadLine());
                sb.Append(numOfStairs[target]).AppendLine();
            }
        }
        Console.Write(sb);
    }
}


Check if an XML file exists then change URLs in it

I reworked your VBScript a bit with comments, see below. In response to the comment from Konrad, I can agree with him for 90% of the cases. VBScript stays interesting for system management, logon scripts, etc., but I myself am replacing it with Ruby which isn't a big step up from VBScript, and on the other hand it has almost all the goodies from python. If you want to compare, take a look at e.g. http://yagni.com/rosetta-stone/#0 (what happened to https://rosettacode.org/ ?). You'll see that the Ruby code is most of the time the smallest and the most comprehensible.

The adapted VBScript version:

Option explicit 'always use this
'declarations first, be concise
Const ForReading = 1, ForWriting = 2, ForAppending = 8, CreateIfNeeded = true
Dim objFSO, objFile, textToReplace, textReplacement, strNewText, strText
Dim errorFileSys, errorLogTxt, urlsinfo
Set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FileExists(urlsinfo) Then 'indent
  textToReplace   = "http://www.yahoo.com"
  textReplacement = "http://www.google.com"
  urlsinfo = "C:\urlsinfo.xml"
  Set objFile = objFSO.OpenTextFile(urlsinfo, ForReading)
  strText = objFile.ReadAll
  objFile.Close
  strNewText = Replace(strText, textToReplace, textReplacement)
  Set objFile = objFSO.OpenTextFile(urlsinfo, ForWriting)
  objFile.WriteLine strNewText
  objFile.Close
Else
  Set errorFileSys = CreateObject("Scripting.FileSystemObject")
  Set errorLogTxt = errorFileSys.OpenTextFile("C:\urlsinfoError.log", ForWriting, CreateIfNeeded)
  errorLogTxt.WriteLine(Now &"     urlsinfo.xml file did not exist in directory C:\. ")
  errorLogTxt.Close
  Wscript.Quit 1 'you could use quit here to give an errorlevel back to the OS
End If

'Exit Script 'no need for obvious comments
'WScript.Quit() 'no need for this at the end of the script
'also quit is a sub, no need for the ()

And the same script in Ruby:

urlsinfo, urlsinfoError = "C:/urlsinfo.xml", "c:/urlsinfoError.log"
textToReplace, textReplacement = "http://www.yahoo.com", "http://www.google.com"

begin
  File.write(urlsinfo, File.read(urlsinfo).gsub(textToReplace, textReplacement))
rescue
  File.write(urlsinfoError, "#{Time.now}      urlsinfo.xml file did not exist in directory C:\. ")
end


Logging class in Qt library for foreign language calls

It would be great to be able to discern what outside requirements and what are requirements that you are imposing because you are imagining a specific way to solve this problem. You don't post the Handler class. If you want a logger per Handler why not have the handler class create the logger ?

With regard to RAII, all objects destructors will be called at the end of the program, unless you need to open and close these files for other reasons, is there really an upside to make things more complicated than they already are ?

But yes that solution with the pointer and the copy doesn't look good, it smells like you trying to enforce a specific way of dealing with things that just doesn't fit the semantics of the code. The copy constructor in the logger is only there because of the way you want to create the logger, there doesn't seem to be any outside requirement that says that copy constructor is needed.
If you need to detect two different error conditions from exceptions you can just throw two different exception types, when you create your handler.

Unless there is a specific reason for having the initializeHandler function you could as well handle most of the logic you have in that function in the constructor and do the errorhandling in various catch blocks.
if you throw the exceptions in the constructor you don't have to check in the constructor if the preceding operations succeeded, that is one of the advantages of throwing exceptions for error handling. Also think about how often you expect the file open function to fail, if you expect this to be a regular occurrence then the handling would be different than if this is an 'exceptional' occurrence.

Here is one option how handler initialization could be handled.

QPointer<Handler> handler;
try {
    handler = new Handler(x, y, "Handler.txt");
  }
  catch (FileOpenException e) {
    // Handle file Open Exception
  }
  catch (HandlerException e) {
    // Handle Handler failure
  }
}

if (! handler.isNull())
{
  doProcessing();
}

Unless there are other requirements that force you to copy the logger, get rid of the copy constructor, then you don't have to use the QSharedPointer in your logger class. Instead you can just use plain stack members.


To clean the main render, we can extract the below JSX into a method and render that method into the main render.

<View style={styles.container}>
          <View style={styles.border}>
          <Image source={{uri: URI}} style={styles.image}/>
          </View>
      </View>)

For image url, instead of assigning it directly into the <Img > tag, we can declare a static property or even in the constructor or state, then can use accordingly.

Further refactoring can be done by extracting the StyleSheet into a separate Style.js.

All the colors used can be used from a single file.

Modified Code:

  export default class App extends React.Component {
  static URI = 'https://images.unsplash.com/photo-1579551356536-e2d17fe1c7fa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'

  defaultView = () => {
   return(
     <View style={styles.container}>
          <View style={styles.border}>
          <Image source={{uri: URI}} style={styles.image}/>
          </View>
      </View>)}

  render() {
    return (
      {this.defaultView()}
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    padding: 8,
  },
  border:{
    width: 200,
    height: 300,
    borderTopEndRadius: 50,
    borderBottomStartRadius: 50,
    borderRadius: 15,
    backgroundColor: 'red',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    shadowRadius: 8,
  },
  image:{
    width:'100%',
    height: '100%',
    borderTopEndRadius: 50,
    borderBottomStartRadius: 50,
    borderRadius: 15,
  }
});


Django turn ChoiceField into a submit button

If you want the options to appear on the page, I would recommend using the RadioSelect widget instead. You will still need to click a separate button to submit however.

class PortfolioForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(PortfolioForm, self).__init__(*args, **kwargs)

        portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]

        self.fields['portfolios'] = forms.ChoiceField(
                    widget=forms.RadioSelect(),
                    choices=portfolios,
                    required=False,
                    )

If you would like your own custom widget instead, you can inherit one of the existing widgets and apply your own template.

# widgets.py
class ButtonSelect(ChoiceWidget):
    template_name = 'widgets/button_select.html'
    option_template_name = 'widgets/button_select_option.html'

# templates/widgets/button_select.html
{% include "django/forms/widgets/multiple_input.html" %}

# templates/widgets/button_select_option.html
""""
Will need custom widget option code here.
Take a look at https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/input_option.html
"""

Then you can use it in your PortfolioForm

from widgets import ButtonSelect

class PortfolioForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(PortfolioForm, self).__init__(*args, **kwargs)

        portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]

        self.fields['portfolios'] = forms.ChoiceField(
                    widget=ButtonSelect(),
                    choices=portfolios,
                    required=False,
                    )


In makefiles you can have spacing around equals signs, making the code slightly easier to read. For example PREFIX = ./node_modules/.bin.
UPPER_CASE variables are generally used for things that the end user might want to change when running, while lower_case is for internal use variables. The user is presumably not supposed to change for example the source directory, so SRC should really be src.
Single-use internal variables like BIN make the code harder to read for no tangible benefit. Introduce a variable when you need to reuse the value.
Any target which has a name that doesn't correspond to an actual file created by that target should IMO be marked as .PHONY (because it is).
Conversely, targets which do generate result files from their dependencies should be named for the files they generate, so that the Magic of Make™ can kick in and skip targets when they are up to date.
BIN_MAKE would be much easier to understand as either commands in a target or as a separate script.
The default target of a Makefile is the first one, by definition. That makes it redundant to have two phony targets (all and default) to do the default thing.
Some more space between the targets would be nice.
The comments are a bit verbose. Most of the time I find it's possible to make the code understandable enough (especially by naming things carefully) that comments become redundant.
There should be an end user variable for each command you run that's assumed to be on the PATH, for example CP = /bin/cp. This may be considered overkill, especially for common tools, but it allows people who have tools off the PATH (for example after building it themselves) to run your Makefile without modifying it. A common use case (just like with RVM or Virtualenv) is if you want to test your Makefile with a tool version not installed on your base system.

RM is an implicit variable at least in GNU Make for just this purpose.


Generating an ordinal number for the day of the month

The problem of formatting an ordinal number is a general one that applies to more than just 31 days of a month.  You also have repetition of much of the string @"Today is the %lu?? day of the month".  Therefore, I suggest defining a separate function for handling this problem.  Taking inspiration from NSNumberFormatter and 'th' 'st' 'nd' 'rd' (ordinal) number endings, I would write:

NSString* const ordinalNumberSuffix(NSUInteger num) {
    if ((num / 10) % 10 == 1) {
        return @"th";       // Special cases 11th, 12th, 13th
    }
    switch (num % 10) {
        case 1:  return @"st";
        case 2:  return @"nd";
        case 3:  return @"rd";
        default: return @"th";
    }
}

Then you can call

NSLog(@"Today is the %lu%@ day of the month", day, ordinalNumberSuffix(day));


Renaming form controls and underlying code

You've basically implemented (parts of) a rename refactoring.

The problem is that the VBIDE API only gives you strings to work with, so you essentially have a "smart find & replace", but it's still a find & replace.

A LOT of things can go wrong when processing code without a symbol table.

Imagine a control named MyButton that you want to rename to SomeButton. Then you have this code in the module:

Dim MyButtonForeColor As Long
MyButtonForeColor = vbBlack

Your code will rename MyButtonForeColor too, because it contains MyButton - but did you mean to? In this case, probably.

UserForm controls are Public, so you can have code outside the form that does this:

With New UserForm1
    .Show vbModal
    ActiveSheet.Cells(1, 1) = .SomeTextBox.Text
End With

And that code will break when you rename SomeTextBox to anything else.

Or, you could have conflicting but unambiguous names in different scopes, that a simple find & replace will break:

UserForm1.SomeButton.Caption = UserForm2.SomeButton.Caption

Naming is hard. Renaming is even harder.

Having worked on Rubberduck for over two years, I can assure you that there is absolutely no way to implement any kind of rename refactoring without a symbol table - and that means lexing, parsing and resolving the VBA code you want to refactor.

Ctrl+H isn't a refactoring tool. Rubberduck is. I don't mean to sound like an ad, but your code needs to know exactly which code across the entire project is referencing the control you're renaming - and that simply isn't possible to implement reliably in VBA. Heck, Rubberduck has a proper parser and resolver, and still struggles with a number of edge cases.

I give you this code to play with - it's EVIL beyond words, I know... but it's 100% legal VBA code, and Rubberduck sorts it all out:

'Project Name = MyProject
'Module Name = MyModule
Option Explicit

Private MyVar As MyProject
Private MyVar1 As MyModule

Private Type MyProject
  MyModule As String
  MySub As String
End Type

Private Type MyModule
  MyVar As String
  String As MyProject
End Type

Private Type MySub
  MyVar As MyModule
  MyVar1 As MyProject
End Type

Private Type MyVar
  MyProject As MyModule
End Type

Sub MySub()

  Dim MyProject As MyProject
  Dim MySub As MySub
  Dim MyVar As MyVar

  MyVar.MyProject.MyVar = "Smith"
  MySub.MyVar1.MySub = MyProject.MySub

  'My brain hurts....

End Sub

Your strategy (I know you're only looking at controls, but the principle is the same) will fail to correctly rename MySub here (whichever you pick).

Your code looks great though - good naming, clean code, nice spacing, indentation, casing, a bit large for a single procedure though, but as I said I don't think any of it is relevant, since there's no way any identifier-renaming VBA macro can work [in all cases] simply by looking at context-less strings.


Recursive BFS solution for tree traversal

You're off to a good start.  In cases like this, most of my comments come down to best-practices for coding standards.  I break down a few areas, starting from nitpicks to almost-bugs:

1. Spacing

In the python world it is worth familiarizing yourself with PEP8, which sets suggested standards for code formatting across the python world.  Yours looks pretty close to most of the standards, but one thing you are missing is your indentation.  2 spaces is pretty small: I would go for 4, which is the PEP8 recommendation.  Also, a space between parameters is recommended.  I.e. tree, level instead of tree,level.  Believe it or not, these things matter: in almost all cases, code is read more than it is written.  As a result, it is important for long-term maintenance to write code that is consistent and easy-to-read.

2. Doc strings

Doc strings are the preferred way of commenting your code.  Comments themselves should be used sparingly (you don't have any, which for a function of this size is fine), but doc strings should be used pretty much everywhere.  These are a formatted block of text, inside a comment, that comes right before your function definition (also classes and modules).  It describes the parameters, what the function does, and what it returns.  See here:

https://stackoverflow.com/a/24385103/1921979

3. Guard conditions

Instead of putting all of your code inside an indented block, this is one of many cases where a guard clause will make your code more readable.  At the top, put conditions on cases where you don't need to do any processing, and exit early.  I.e.:

if not level:
    return []
// everything else here

4. Recursion

Recursion here is perfectly fine.  You didn't overthink it or overdo it.  It actually fits perfectly in this case, and recursion is usually a harder concept to grasp, so anything that helps you practice it (without making the code a tangled mess) is a good choice.

5. Default parameter values

Your default value for the level parameter only works for your given example.  As a result, it is best to kill it.  Just make it a required positional parameter.

6. Error detection

Your code assumes that it is passed in a valid tree.  This is not a crazy assumption, but it will likely be a wrong assumption at some point in time.  In your current case, if someone passes in a broken tree, it will generally lead to an exception being raised.  This can be a good thing or bad thing depending on your viewpoint.  There are three ways I normally consider handling such an event (in order of preference):

Detect and raise an exception
Ignore and let python raise an exception
Silently ignore it

Here is a simple example of a tree that will fail:

tree = {"A" : ["C", "D"]}

Your current code opts for Option #2 above.  With the above example, python will raise a KeyError with a rather cryptic message: KeyError: 'C'.  This is not necessarily a bad thing.  Garbage In=Garbage Out.  However, the problem is that it might not be obvious what caused the error.  As a result I like to detect and raise my own exceptions to make it easier on whoever is using your method (Option #1):

for vertex in level:
    if tree not in vertex:
        raise ValueError('Broken tree: branch %s is referenced but not found in the tree' % (vertex))
    sub_level += tree[vertex]

This gives the user better information on where to start looking for the problem: most importantly, not in your function.  The third option would be to silently ignore such errors.  That would look something like this:

for vertex in level:
    if vertex not in tree:
        continue
    sub_level += tree[vertex]

This can be appealing because it makes your code play nicer if a broken tree comes its way.  The problem is that this can often end up hiding bugs, which just cause problems farther down the stack.  The farther your code gets before it crashes, the harder the problem tends to be to resolve.  So my default is to quit loudly if something is off.  That is what logging is for.


Rails Grape API Endpoint optional params validation in update

user.assign_attributes(params)
user.save

model.assign_attributes(hash) allows you to assign a key value hash to your ActiveRecord object. The only caveat is that the keys passed must correspond to your columns or an exception will be raised. You will need to call .save to persist the changes.

If you want to assign and save in one fell stroke, use model.update(hash).

http://api.rubyonrails.org/classes/ActiveRecord/AttributeAssignment.html


Simple calculator which can operate on more than two numbers

reduce

Whenever you need to fold an operation across a list, like you're doing, you want to use reduce(). That takes a function, an iterable, and an optional initializer, and performs the operation across all of them. So:

reduce(f, [x, y, z])

is equivalent to:

f(f(x, y), z)

This is precisely what we want. The operator library additionally gives us all the mathematical operators, so we don't have to write them ourselves. So the various operations are:

+: reduce(operator.add, numbers) # or just sum(numbers)
-: reduce(operator.sub, numbers, 0)
*: reduce(operator.mul, numbers)
/: reduce(operator.floordiv, numbers, 1)

Simplifying the logic

We could directly translate the above into a dictionary of operators and a dictionary of initializers:

operators = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv
}

initializers = {
    '-': 0,
    '/': 1
}

result = reduce(operators[operation],
    numbers,
    initializers.get(operation, None))

This will additionally fix your bug where for subtraction you're really adding.

List Comprehensions

It's more direct to simply initialize your numbers directly:

numbers = [int(input("Number: ")) for _ in range(amount)]

Note that x is not a good name. Prefer more descriptive names.

Division

All of your numbers are ints. Which means that when you divide, you're going to end up with 0 as soon as you have any number that isn't 1. That isn't particularly interesting, so I'd suggest using floating point numbers instead.


Handling errors when using PDO to connect to a database instead of MySQLi

From a first pass over - all you are doing are if else without any throw or inspection as to what possible errors that the PDO might be tossing out.

Thats bad because on production servers - I would assume that you won't be turning on error/warning reporting but will be logging them.

Also as @Alex L mentioned - you are missing a IF statement that checks if $pdo == null then throw exception. However its better with a try/catch

try {
    $pdo = new PDO($dns, $username, $password, $options);
} catch (PDOException $e) {
    throw new pdoDbException($e);
}


Printing every 10th result in an alternating ± series

The first thing you can do to make the sign change obvious is to use operand = -operand, this way you avoid the need for the multiplication operator. Also changing the operand name to sign can help.

You also don't need counter as it will be equal to i before the test. Just change the test to use the modulo (%) operator instead of reseting counter.

And using augmented assignment for result can lead to a more readable line too:

result = 0
sign = 1
for i in range(1, 101):
    result += sign * i
    sign = -sign
    if i % 10 == 0:
        print(result)

Now, this probably need to be made more reusable, this means building a function out of this code and avoiding mixing computation and I/Os:

def alternating_sum(start=1, stop=100, step=10):
    result = 0
    sign = 1
    for i in range(start, stop+1):
        result += sign * i
        sign = -sign
        if i % step == 0:
            yield result

Usage being:

for result in alternating_sum(1, 100, 10):
    print(result)

Also, depending on the problem at hand, you can leverage the fact that every two numbers add-up to -1. So every 10 numbers add-up to -5. If you don't need much genericity, you can simplify the code down to:

def alternating_every_ten(end=100):
    reports = end // 10
    for i in range(1, reports + 1):
        print('After', 10 * i, 'sums, result is', -5 * i)


You could just combine the logic into one statement, assuming there is not other things occurring during your if-else blocks and stuff.
If there is, then this won't necessarily work for you, and you should post the real code, because a lot of times these problems are subjective to the code.

I guess one lesson to possibly learn from this is just to realize the end result, and build a condition that matches the necessary conditions to do something.

if (somecondition && (name == null || someothercondition))
{
    //'Add' to list
}

Edit: To expand upon the OPs full code being posted.

My original answer is still valid you would write it like this:

for (int i = 0; i < typelist.Length; i++)
{
    if (typelist[i].BaseType.Name == "Controller" && (ControllerName == null || typelist[i].Name == ControllerName))
    names.Add(new AppController
    {
        ControllerName = typelist[i].Name,
        ActionName = typelist[i].GetMethods()
        .Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
        .Select(s => s.Name).ToList()
    });
}

However, now that you have actual code to review, I will also point out that there is no reason to be using a for loop vs a foreach loop. I would write that as follows.

foreach (var t in typelist)
{
    if (t.BaseType.Name == "Controller" && (ControllerName == null || t.Name == ControllerName))
    names.Add(new AppController
    {
        ControllerName = t.Name,
        ActionName = t.GetMethods()
        .Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
        .Select(s => s.Name).ToList()
    });
}

At this point I am recognizing that we are iterating through a list, and conditionally doing one thing. This appears to be the perfect candidate for using some linq.

using Where and some lambda we can make this statement to return an IEnumerable<Type> which only contains Types we need to add.

typelist.Where(t => t.BaseType.Name == "Controller" && (ControllerName == null || t.Name == ControllerName))

On our newly created IEnumerable<Type> we can Select what we want to add to the names list.

.Select(t => new AppController
{
    ControllerName = t.Name,
    ActionName = t.GetMethods()
    .Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
    .Select(s => s.Name).ToList()
});

Now if this was a time where names was an existing list we only needed to append to we could use names.AddRange() but because this list was created here for this purpose (I think).
we can just ToList() our results and save them as the list.

At this point you could have a few different variables, or you could make your code look awesome and confusing and one-line it all. because I see now that typelist is only being referenced once. (Btw it should probably named typeList, with a capital L, but we're getting rid of it anyway).

So in the very end you can have this beautiful chunk of code. Note: I am also going to use string.IsNullOrWhiteSpace instead of just checking if it is null.

private List<AppController> GetControllerActions(string ControllerName = null)
{
    return
        System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "Project.Web.Controllers", StringComparison.Ordinal))
        .Where(t => t.BaseType.Name == "Controller" && (string.IsNullOrWhiteSpace(ControllerName) || t.Name == ControllerName))
        .Select(t => new AppController
        {
            ControllerName = t.Name,
            ActionName = t.GetMethods()
            .Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
            .Select(s => s.Name).ToList()
        })
        .ToList();
}


Basic sign-up method, testable and with try/catch

For try/catch, statements you should ask yourself: what are you trying to achieve? Do you need to handle the error differently in one controller compared to the rest of the application? If yes, then wrap the entire contents of your method.

If no, Laravel implements a global error handler. You simply need to throw your exceptions and Laravel handles the display of the errors.

As for you unit testing, I am only learning PHPUnit at the moment. Judging by your code, I believe you should take some particular emphasis on learning the S.O.L.I.D principles.

When you abide by these principles you will ensure your code is testable. To be testable your methods and objects need to have a single responsibility, such as taking requests (controller), validation (Request objects in Laravel and saving data (Models).

As for Doc blocks, refer to something like this.

Comment you code often. For methods I always specify in the first line a description of what the method does. (it should have a single responsibility).
Then any parameters/arguments it takes (@param). Then any data it returns (@return). Specify the data type or 'void' if it returns nothing. Then finally any exceptions the method throws.


Not very familiar with Android development, so some of this may be totally off the rails.

Depending on how educational you want this to be, you could visually demonstrate simple algorithms to teach how various operations work (e.g. animations). Also, since you're targeting little kids, I'm not sure double is necessary.

Kid-friendly algorithms you could demonstrate below. You could step through each stage of an operation, e.g. by moving animals from pile to pile. You could skip demonstrations if the numbers are large, or make them run in the background/interruptable.

public int add(int left, int right)
{
    if (right == 0)
    {
        return left;
    }
    return add(left + 1, right - 1);
}

public int subtract(int left, int right)
{
    if (right == 0)
    {
        return left;
    }
    return subtract(left - 1, right - 1);
}

public int multiply(int left, int right)
{
    if (left == 0 || right == 0)
    {
        return 0;
    }

    if (left == 1)
    {
        return right;
    }
    else if (right == 1)
    {
        return left;
    }

    if (left < right)
    {
        return multiplyByAdding(right, left, 0);
    }

    return multiplyByAdding(left, right, 0);
}

private int multiplyByAdding(int baseNumber, int timesLeft, int productSoFar)
{
    if (timesLeft == 0)
    {
        return productSoFar;
    }

    return multiplyByAdding(baseNumber, timesLeft - 1, productSoFar + baseNumber);
}

//division by zero needs to be handled at UI level to explain why it doesn't work
//you might want to do something other than throwing an exception here
public int divide(int dividend, int divisor) throws ArithmeticException
{
    if (divisor == 0)
    {
        throw new ArithmeticException();
    }
    return divideBySubtracting(dividend, divisor, 0);
}

private int divideBySubtracting(int dividend, int divisor, int quotientSoFar)
{
    divident -= divisor;
    if (dividend <= 0)
    {
        return quotientSoFar;
    }
    return divideBySubtracting(divident, divisor, quotientSoFar + 1);
}

//division explains this, so we can cheat here
public int modulo(int dividend, int divisor)
{
    return dividend % divisor;
}

In the code you posted, you have UI and logic mixed together. You probably want to separate them into different modules to keep them clean.

The following is rough pseudocode for how I might organize things. I've left out a lot of stuff that would need to be filled in to make this work, of course.

public enum Operation
{
    Addition,
    Subtraction,
    Multiplication,
    Division
}

public class Calculator
{
    public int calculate(int left, int right, Operation op)
    {
        switch(op)
        {
            case Operation.Addition:
                return add(left, right);
            case Operation.Subtraction:
                return subtract(left, right);
            case Operation.Multiplication:
                return multiply(left, right);
            case Operation.Division:
                return divide(left, right);
            default:
                throw new UnsupportedOperationException(operation.toString() + " not implemented.");
        }
    }
}

public class MyActivity extends Activity
{
    Operation operation;

    //...

    void calculate()
    {
        a = calculator.parse(leftAmount);
        b = calculator.parse(rightAmount);
        answer = calculator.calculate(operation, a, b);
        if (operation == Operation.Division)
        {
            remainder = calculator.modulo(a, b);
        }
        update();
    }

    //called when leftOp, rightOp, and/or answer change
    //numbers greater than 10 could just be printed numbers
    void update(int leftOp, int rightOp, int answer)
    {
        remainderView.clear();

        if (leftOp != previousLeftOp)
        {
            leftView.setContent( ImageFactory.getImageByNumber(leftOp), leftOp );
        }

        if (rightOp != previousRightOp)
        {
            rightView.setContent( ImageFactory.getImageByNumber(rightOp), rightOp );
        }

        if (answer != previousAnswer)
        {
            answerView.setContent( ImageFactory.getImageByNumber(answer), answer );
            if (operation == Operation.Division && remainder != 0)
            {
                remainderView.setContent( ImageFactory.getImageByNumber(remainder), remainder );
            }
        }
        previousLeftOp = leftOp;
        previousRightOp = rightOp;
        previousAnswer = answer;
    }
}


Returning items that meet a minimum value

As @Alan suggested in his comment, this method is doing 2 different things that can be separated into 2 methods.

This looks strange:

            count[c] =  count.get(c, 0)
            count[c] = count[c] + 1

Why not:

            count[c] = count.get(c, 0) + 1


First off your methods are not extension methods as the name RequestsExtensions would indicate. Not sure if this intentional or. If you want to make them true extension methods then I'd consider passing the Url parameter as Uri rather than as string.

Other things I noticed:

The use of a magic number here: req.Timeout = 100000; - This should be a parameter (maybe with a default value) you can pass in.
Your naming convention is a bit weird. Standard naming convention for methods in C# is PascalCase. Also local variables are normally camelCase (your Out variable is not while other variables like req are).
In HTTP_POST you use a block-wise read to get the response while in HTTP_GET you simply read to the end of the response stream - why the difference? The HTTP_GET version seems much simpler so why not do it the same way? In fact both those method get a response and read it and deal with the exceptions - this is duplicated code which you should move into a dedicated function which you can then call from both main methods like this:

private static string GetResponse(System.Net.WebRequest request)
{
    string result = "";
    try
    {
        System.Net.WebResponse resp = req.GetResponse();
        using (System.IO.Stream stream = resp.GetResponseStream())
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
            {
                result = sr.ReadToEnd();
                sr.Close();
            }
        }
    }
    catch
      ....

    return result;
}

The way you handle exceptions is less than ideal. The caller of your methods has no easy way to find out if the call actually succeeded or not - except for parsing the return value of the method.

A better way to deal with it is to let exceptions bubble up to the caller and let the caller decide what to do (e.g. terminate the process, retry later, etc.). In addition you could log the exception (requires passing in some kind of logger)

Alternatively you could make the return value an out parameter and return a bool indicating if the call was successful instead if you really want to hide the exceptions from the caller. In this case I'd rename the methods to something like TryHttpPost and TryHttpGet


Yes, use CSS and some HTML to put things where they belong. Theres is nothing special about ASP.NET controls just check the generated HTML markup on the client side.


Mysql PDO Wrapper that throws Unique Constraint Exception

This code is so good that it's the first time I have nothing to say.
Your approach to the problem is absolutely correct and you should keep using it.
There could be only microscopic nuances, such as one mentioned by Sam. Or, the fact that your constructor would override the configuration settings passed in the $options array. Say, if someone would want to use FETCH_ASSOC as a default fetch mode, your class won't let them. I would rather make it this way
$defaults = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
    PDO::ATTR_EMULATE_PREPARES   => false, // I would throw in this one too
];
$options = array_merge($defaults,$options);
parent::__construct($dsn, $username, $passwd, $options);

So this way you would have your preferred defaults that, however, could be overwritten, making your class flexible, without artificial restrictions.


File-to-fully qualified class name function

My current assumption is that the string returned by file.getPath is going to look something like ..\solutions\some-parent-dir\some-scala-file.scala

If this is the case then you can try the following function:

def makeFqClassName(file: File): String = {
  val fileName :: _ = file.getName.split('.').toList
  val upDir :: upUpDir :: _ = file.getParent.split(File.separator(0)).toList.reverse
  s"$upUpDir.$upDir.$fileName"
}

I've introduced a smidgen of strange syntax just to show you a possibility. As a way of explaining what is going on, consider that the following are functionally equivalent:

  val foo :: _ = List(0, 1, 2, 3)
  val goo = List(0, 1, 2, 3).head

From the POV of operations performed they're unequivalent.
foo is defined from the result of a pattern match that discards the tail of the list. goo as you know is the result of the invocation of the head method. (I suppose it could be the case that the compiler is smart enough to translate a pattern match on a list that only takes the head of the list into an invocation of the head method, but lets just ignore that for now :^) And a final example:

val a :: b :: c :: d :: ez = ('a' to 'z').toList

Here a , b , c , and d  are assigned the expected character values and ez is a list consisting of the characters e through z.

If I've misunderstood what your asking for please let me know and I'll update this accordingly.


I can only think of two good reasons for using base 10:

The purpose of the code is to teach, and the person (could be yourself) or people being taught are more comfortable with base 10 than base 2.
The underlying representation of the integers is in base 10.

Note that case 2 is extremely unlikely. And since you're asking about speed, I assume that case 1 doesn't apply either (although see below). Therefore you should probably be using a base which is a power of 2. The only case in which this isn't true is where profiling showed that the bottleneck was converting your final output to base 10 for printing and so you chose to write a custom big integer implementation which uses a base which is a power of 10: I have personally encountered this situation, and chose to work base 1000000000 so that the base would fit in a 32-bit integer and the product of two digits fit within a 64-bit integer.

Note that working with a base which is a power of 2 means that all of the power operations can be done with bitshifts, or if you're able to access the internal data structure of a big integer then by index adjustments.

Note also the reference to big integers above. Working (isize, isize) -> isize, there's no point using Karatsuba except for teaching purposes. It would be faster to use *.


Histogram of Maxwell-Boltzmann distribution

Static classes

You've (correctly) marked Normalization as static. You should do the same for every other class in your program - they are all currently being used as statics.

Expression bodies

C# has a wonderful bit of syntactic sugar - expression bodies - that lets you rewrite this:

public static double MaxwellVariance(double mass, double temperature)
{
    return Math.Sqrt(KB * temperature / mass);
}

as

public static double MaxwellVariance(double mass, double temperature) =>
    Math.Sqrt(KB * temperature / mass);

Classes

You're in C#, so you're stuck without the ability to have global functions. It's somewhat similar to Java in this way: it really pushes you to think about your code in an OOP style.

Going down this path, you would make a class to encapsulate your graph, which would take most of the code out of your Main. Potentially, everything up to and including the initialization of your point list could go in the constructor, and the PlotForm calls could go in a plot method. There are some advantages to this approach, including reusability, re-entrance, and testability.

As for MaxwellBolzman - I think you should refactor it to be a non-static class, with members for mass and temperature. random can be accepted as an optional parameter or the class could instantiate it itself. That will simplify many things:

Variance will turn into a one-line property with an expression body
Component and Speed will turn into parameter-less properties

Names

This is minor, but I find the Maxwell prefixes in all of the methods of MaxwellBolzman to be redundant; I think they would be even more legible if you simply named them Variance, Component and Speed.

Loops

I would find Speed more legible as

double sum = 0;
for (int i = 0; i < 3; i++) {
    double comp = Component;
    sum += comp*comp;
}
return Math.Sqrt(sum);


Putting this as an anwer, because it took a while to find it:

I took your code, and put it through some tests..... I made the tests up based on the 'rules'. This is the sort of thing any interviewer will do:

public static void main(String[] args) {
    String[] positive = {"12345abc", "1a2b3c4d", "1234567890ab", "1234a"};
    String[] negative = {"", "1", "1a", "123567890", "abcdefghij", "abcdEfgh1", "abcabc123", "123a", "1234567890abc"};

    PasswordValidator validator = new PasswordValidator();

    for (String pos : positive) {
        ValidationResult result = validator.validateWithMessages(pos);
        if (!result.isValid()) {
            System.out.println("Claims that '" + pos + "' is not valid!: " + result.getMessages());
        }
    }

    for (String neg : negative) {
        if (validator.validate(neg)) {
            System.out.println("Claims that '" + neg + "' is valid (but it is not)!");
        }
    }
}

When I ran that test, it passed the password: "1234567890abc" which is 13 characters long, and the rules say the limit is 12.

Checking your Regex, I see you mis-typed the range-limit on the match: ".{5,15}"

Hate to be the bearer of bad news, but an interviewer could look at this as being an indication that you are not 'detail-oriented', and dismiss the application immediately.

For what it's worth, I look at your code and feel it has a strong structure, a reusable and extensible model. Generally good. Perhaps overkill, but that's OK.

But, bottom line, if your code does not meet the specification, you can expect to be moved down the pile of applicants ......

P.S. It also blew up on a null password, which I removed from my test because I did not think it was 'fair', but regardless, you should handle null input gracefully.


A few quick remarks:

In your second using statement, you declare a SqlCommand variable named cmdDelete. In the body of that using statement, however, you call ExecuteNonQuery on a variable named deletePolicyFromTdm. I don't see a declaration for deletePolicyFromTdm in your code, so I wonder if it should be cmdDelete instead.
I'm not sure where testNumber is coming from, but your approach potentially opens the door for SQL injection. I recommend defining it as a parameterized query (e.g. DELETE FROM table WHERE TestNumber = @TestNumber); it's a very small amount of work and will be one less thing to do when you switch to a sproc later.
Your brace style is not consistent. The braces following using are on the same line; the brace following try are on a separate line.


I will go through your code line by line and give feedback. We will skip the general advice on don't use CGI as it's actually suited for what you are trying to do here.

I wrote this answer in two stages, so some of the things here might have been said by other people. I'm attempting to provide full feedback, and I'm not copying from others. If several of us give the same feedback, it must probably make some sense.

#!/usr/bin/perl -T

The -T flag turns on taint mode. I am not sure you intended to do this, or just copied it from somewhere else. Taint mode essentially makes sure that data coming into your program from the outside must be validated before it's being used. But you are not untainting the variable $f. That could bite you in the back.

use strict;
use warnings;

This is good! Well done. Your code should always start with strict and warnings.

use CGI qw/:all/;

You are importing a lot of stuff into your namespace, but all you use is param. Instead, consider importing only :cgi, which will give you less stuff, or only import param and header. That also makes it easier to remember where that function came from.

use CGI qw(param header);

my $f = param("f") || '';

$f is not the greatest variable name. Use descriptive variable names, like $filename.

If the file is called zero 0, or 0000, this will fail. Read more about that at the end of this post.

($f eq '') && die;

While some people like to use logical operators for flow control, this is really weird to read. If you want concise syntax without blocks, use a post-fix if or unless.

Also, provide an error message as to why this failed. It's CGI, so this will show up in your server log. You don't want it to say Died at line 10, do you?

I prefer to use the q{} quoting operator for empty strings, as it shows the intent of giving an empty string more clearly.

die "No filename given" if $f eq q{}.

open(PATH, "<$path") || die;

Don't use a GLOB as a file handle. It's global to all of your program, including other modules and namespaces. If another module was to use the same PATH name for a handle, this would conflict. Instead, use a lexical file handle. The convention is to name file handles $fh.

This has the added benefit that Perl will take care of closing the handle for you as soon as the variable goes out of scope. In this case, that's when the program ends. So you don't have to use close explicitly.

Use the three-argument form of open, where the second argument is the mode. In your case, that's < for reading. This makes file operations more secure, as your $path could for example start with a pipe |, which would change the meaning. Especially if part of your file name comes from the user (and you didn't even untaint it), this is crucial advice.

Don't use binary or || for flow control as it has tight binding. Use or instead, which binds very loosely, so you don't need to put the parentheses after open. It will also read more like actual English.

Include a meaningful error message with your die, especially the error $! that was returned from the open call.

open my $fh, '<', $path or die "Error opening '$path': $!";
binmode $fh;

print header(-type => "application/pdf",
         -target => "$f");

Indent your code properly. This looks weird. You have indented the second line 9 spaces. Looks like one full tab in vim, and one space. Instead, break it around properly, and align everything. On average, code is read ten times more than written. Prepare for that.

Don't quote variables if there is no interpolation needed. If it's only one var, leave out the quotes.

print header(
    -type   => "application/pdf",
    -target => $filename,
);

print;

This line will print the current value of $_. I am not sure what that is at this time in the execution of the program. It's probably not intended. Get rid of it.

while (<PATH>) {
    print($_);
}

If you intend to use the loop variable, name it. The topic $_ is really useful for short one-liners, map and such, but a while loop is rarely such a case.

while ( my $buffer = <$fh> ) {
    print $buffer;
}

You can also use the aforementioned post-fix notation for that. Again, you don't need to use the topic, because it's implicit.

print while <$fh>;

But you can also just get rid of that completely, and simply use the fact that print is list context, and the diamond operator <> returns the full file as an array in list context.

print <$fh>;

I said earlier that your check for $filename with || will fail if the name is a false value. Remember that Perl has no actual true and false, just values that evaluate truthy, and values that don't. There are very few things that are false in Perl. 0, undef, the empty string q{} and the empty list () are such cases.

my $filename = param('f');
die unless $filename;

This would be similar, but again, 0 would be cast out.

my $filename = param('f');
die unless defined $filename;

If there was no param f, the param function returns undef. So we can avoid that by saying unless defined. That lets 0.pdf through. But what about the empty string?

Essentially you need to decide whether a file named $basepath/.pdf is valid. That's up to you. If you don't want that, you have to do additional checks.

You could also check if that file exists in general, with -e.

die "No such file" unless -e $path;

However, open will check that anyway, so it's not needed.


Print numbers in a spiral from the center

Not too advanced myself - so take with a grain of salt.

Foremost I would separate the logic for constructing the grid and printing. Especially extract the function to construct the grid.  Currently its wrapped in printClockwise  IMHO it should be prominently its own function.
There are a few definitions in printClockwise  (emptyGrid, directionOrder and the printing) that I would consider reusable and would make them top level.
You only use lens in one place. lens is quite an expensive import - there just was an interesting post.  I suppose your intend was to learn lens and therefore it's used - but just for the code I would consider removing the dependency.
the fixed "%4s" in printing - it's easy to estimate the required width for larger numbers. Or just make it that max n is 999.

Some stuff to consider that is really personal choice - no need to follow if you disagree:

changing the data type to strict mutable array or similar.
adding a walk that takes larger strides.
split the walk function into one stream of positions in the spiral, and separately setting the values in a second step.  This could solve the issue that the input needs to be a perfect square - just take the first n positions.

As last remarks:

whenever I see such a spiral I think Ulam spiral. If you want to expand I would consider adding functionality to the printing to allow highlight - in this case for primes.
I also checked whether the coordinates are on OEIS - they are A174344. And your algorithm agrees with the algorithm they post along side (the Julia implementation is almost the same, the other use some shenanigans with sin and cosine).


List of lists of arrays, zipping, modifying in place

1. Code review

There's no documentation! To make your code maintainable, it's vital to explain the purpose of each function. What does it do, what arguments does it take, and what does it return?
The function rand_mat seems useless. It's a very thin wrapper around numpy.random.normal so instead of writing:

random_like(old_know)

write:

np.random.normal(0, 0.01, old_know.shape)

This would allow you to get rid of the rand_mat and random_like functions, which would be two fewer things to understand and maintain.
The numbers 0 and 0.01 should have names. They should perhaps also be parameters to the reset_layers function.
The name layer_nums_to_reset is misleading as it is list of Booleans, not a list of layer numbers. A name like layers_to_reset or maybe just reset would be better.
The assert only checks the length of layer_nums_to_reset against orig[0], but you wrote, "All the inner lists have the same lengths." It would be clearer to assert the stronger condition.
The reset_layers function does not really need to know what is in the layers (whether knowledge or whatever does not matter). In fact, it is confusing to bring this irrelevant detail into the function. Separation of concerns is an important technique for making maintainable code.
The arguments to reset_layers do not correspond to the return value. The caller must pass the layers as individual arguments, but gets back a list of layers. It would be clearer to pass a list of layers and return a list of layers.
You go to some effort to process the layers in an unnatural order: that is, to process the first element of each layer, then the second element of each layer, and so on. I guess you do this so that you only have to iterate over layer_nums_to_reset once. But this seems like a false economy if it makes the function more complex and harder to understand. Keep things simple!

2. Revised code

import numpy as np

def reset_layers(reset, layers, mean=0, std=0.01):
    """Return a list of lists of arrays that contains the same arrays as
    layers but with some replaced by arrays of the same shape
    containing normally distributed random numbers.

    layers -- a list of lists of arrays. The inner lists all have the
              same length, n.
    reset -- an array of Booleans of length n. The replaced arrays are
             at the positions given by the True values in this array.
    mean, std -- the mean and standard deviation of the random numbers.

    """
    assert(all(len(reset) == len(layer) for layer in layers))

    def reset_layer(layer):
        """Reset arrays in a single layer."""
        for res, old in zip(reset, layer):
            if res:
                yield np.random.normal(mean, std, old.shape)
            else:
                yield old

    return [list(reset_layer(layer)) for layer in layers]


Count wins and losses for each team in a league

Please always use 4 spaces to indent when using Python.

Rather than the verbose name team_wins_and_loses we could use team_results.

Rather than adding both values of the tuple we should focus on adding 1 win to the winning team, and 1 lose to the losing team.
winner[0] += 1
loser[1] += 1

We can change your turnery to pick the wining or losing team, and then extract the value with the correct default.
winning_team, losing_team = (
    (team1, team2)
    if int(score1) > int(score2) else
    (team2, team1)
)
if winning_team not in team_results:
    winner = team_results[winning_team] = [0, 0]
else:
    winner = team_results[winning_team]
# same for losing team

We can use dict.setdefault to remove the need for the if.
winner = team_results.setdefault(winning_team, [0, 0])

We can use collections.defaultdict to make interacting with team_results much cleaner, rather than using dict.setdefault.
def default_scores():
    return [0, 0]

team_results = collections.defaultdict(default_scores)
# ...
team_results[winning_team][0] += 1

import collections

def default_scores():
    return [0, 0]

team_results = collections.defaultdict(default_scores)
number_of_games = int(input("Enter the total number of Games: "))
for _ in range(number_of_games):
    team1, score1, __, team2, score2 = input("Enter the game results(Note that the name of the team must be a single word, without spaces):").split()
    winner, loser = (
        (team1, team2)
        if int(score1) > int(score2) else
        (team2, team1)
    )
    team_results[winner][0] += 1
    team_results[loser][1] += 1
    print(team_results)


Counting e-mails in a mailbox for each hour

Formatting

Please follow PEP8, the Python style guide.
Most noticeably,
use 4 spaces to indent.

Working with files

The recommended way to work with files is using with ... as, like this:

with open(fname) as fh:
    for line in fh:
        if not line.startswith("From "):
            continue
        words = line.split()
        time.append(words[5])

This way, you don't have to remember to close the filehandle when you're done using it.

Naming

Use plural names for collections.
time is really odd for a list of time strings.
And I suppose that's part of the reason for naming the loop variable i here:

for i in time:
    i.split(":")
    hours.append(i[:2])

When it would have been so much more natural as:

for time in times:
    time.split(":")
    hours.append(time[:2])

Pointless statements

i.split here is completely pointless. It splits the string, but then the result is never used:

for i in time:
    i.split(":")
    hours.append(i[:2])

This is the same thing:

for i in time:
    hours.append(i[:2])

Use list comprehensions

The hours list can be created simply as:

hours = [time[:2] for time in times]

Use collections.Counter

Instead of this:

for h in hours:
        hr[h]=hr.get(h, 0)+1

You could create hr a lot simpler:

from collections import Counter

hr = Counter(hours)

(Of course, the import statement should be at the top of the script.)

Sorting

Instead of this:

l = list()
for k, v in hr.items():
    l.append((k, v))
l.sort()
for k, v in l:
    print(k, v)

You could use the builtin sorted, and greatly simplify:

for hour, count in sorted(hr.items()):
    print(hour, count)

Notice that I renamed the loop variables. How much easier to read that!

Use functions

Rather than just a sequence of statements,
it would be better to decompose your logic to functions.

Suggested implementation

With the above suggestions applied (+ PEP8, do read that!), and then some more:

from collections import Counter

DEFAULT_FILENAME = 'filename.txt'

def input_filename():
    filename = input("Enter file:")
    if not filename:
        filename = DEFAULT_FILENAME
    return filename

def read_times(filename):
    with open(filename) as fh:
        for line in fh:
            if line.startswith("From "):
                yield line.split()[5][:2]

def main():
    filename = input_filename()

    hour_counts = Counter(read_times(filename))

    for hour, count in sorted(hour_counts.items()):
        print(hour, count)

if __name__ == '__main__':
    main()


Data retrieval from Dynamic HTML page with time-out (Web scraping w. Python)

Currently you only get one new name per page request. However, the page contains all people known by that person. So I would implement a queue of yet to be visited people and a set of people already visited. If there are no more people left to visit, you have found all people (assuming there are no disjoint sets of people and that this is your actual goal).

In addition, using requests is usually a bit more user-friendly than using urllib directly.

import requests
from bs4 import BeautifulSoup, SoupStrainer
import re

STRAINER = SoupStrainer("a")

def get_name(url):
    match = re.match(r"http://py4e-data.dr-chuck.net/known_by_(.*).html", url)
    if match is not None:
        return match.groups()[0]

def find_all_people(start_url):
    with requests.Session() as session:
        queue = set([start_url])
        visited = set()
        while queue:
            url = queue.pop()
            visited.add(url)
            print(len(visited), "/", len(visited) + len(queue), url)
            response = session.get(url)
            soup = BeautifulSoup(response.text, "lxml", parse_only=STRAINER)
            queue.update(a["href"]
                         for a in soup.select("a")
                         if a["href"] not in visited)
        return list(map(get_name, visited))

if __name__ == "__main__":
    url = "http://py4e-data.dr-chuck.net/known_by_Kory.html"
    people = find_all_people(url)
    print(len(people))

This uses a request.Session to keep the connection alive, speeding it up a tiny bit. It also has a if __name__ == "__main__": guard to allow importing from this script from another script without the code running, a bs4.SoupStrainer to only parse the parts of the page needed and it uses the faster lxml parser.

It still takes quite some time to find all people. Finding that there are probably 5754 people takes only a few seconds.


The implementation of your move decorator is a little schizophrenic. On the one hand, it carefully allows any and all arguments to be passed to it by declaring itself def wrapper(*args, **kwargs). However it then requires exactly two positional arguments which it then passes on to the wrapped function. Keyword arguments are accepted but ignored and dropped. I would suggest changing this to be all at one end or all at the other end of this spectrum. Given the annotations elsewhere, I would expect you to prefer changing the function to def wrapper(x, y) (or maybe to def wrapper(x, y, **kwargs) but then also passing **kwargs to f).

It might make sense to incorporate check_range into the wrapper as well, simplifying most of the move generators. It might also make sense to skip the decorator and instead call the filter in your move generators: return filter_move((x, y), moves).

As a side note, it would be interesting to see if there are any performance advantages to either the current approach of checking for (x,y) and conditionally removing it or to unconditionally doing a set difference: return f(x, y) - {(x, y)}.

The rest of your code is fairly straightforward, if perhaps a bit too clever. Clever is typically bad for other readers, or for debugging misbehavior. The two things that stand out to me is the name of your lambda possible (which seems more like a diagonal_moves_of_distance or simply diagonal), and the approach used for direction. Given the limited number of possible move deltas, bringing in trigonometry to handle it seems like overkill; I'd almost expect a simple if/else tree instead. As is, it will have problems classifying a knight's move.


it is possible to handle null pointer exception using Comparator.comparing static method. If you want to comparing loanAmount fields in your objects and you want that every not null value is greater than null you can use Comparator.nullFirst method in combination with Comparator.comparing like the below code:

Comparator.comparing(LoanAccount::getLoanAmount,
                     Comparator.nullsFirst(Comparator.naturalOrder()))

NaturalOrder is a method returning a comparator that compares Comparable objects in natural order.
You can also combine more comparators in a chain with method Comparator.thenComparing like the code below:

Comparator.comparing(LoanAccount::getLoanAmount,
                Comparator.nullsFirst(Comparator.naturalOrder()))
                .thenComparing(LoanAccount::getCreationDate,
                Comparator.nullsFirst(Comparator.naturalOrder()))
                .compare(o1, o2);

Now you can rewrite your comparator with equal behaviour shortly:

public class LoanAccountAmountComparator implements Comparator<LoanAccount> {
    @Override
    public int compare(LoanAccount o1, LoanAccount o2) {
        if (o1 == null && o2 == null) return 0;
        if (o1 == null) return -1;
        if (o2 == null) return 1;
        return Comparator.comparing(LoanAccount::getLoanAmount,
                Comparator.nullsFirst(Comparator.naturalOrder()))
                .thenComparing(LoanAccount::getCreationDate,
                Comparator.nullsFirst(Comparator.naturalOrder()))
                .compare(o1, o2);
    }
}

Note: the use of class Date is discouraged, it is better if you use instead the java.time package classes for time related code.


Class method with begin transaction and return errors

I think this is going to be a first, but yes. If I had to work on a project, and come across this code, I'd be happy. The only thing I'd change, perhaps, is the name of the PDO instance: $this->done doesn't say I am a DB connection, IMO. The catching of the exception is required here, but the fact that you're not re-throwing it, or throwing a new, more generic exception is debatable. I'll briefly explain why, but that's entirely up to you to decide

Other than that, I'd say you're pretty much on the money.
A couple of suggestions, though:

Type-hinting
You're assuming the user of your code will be so kind as to pass an array of strings to your function. He/she would have to look at your method to determine what arguments you're expecting. An easier way of doing this would be:

public function foo(array $queries)
{//this method clearly expects an array, pass something else, and it will crash
}

Strings
You're also assuming the array argument will be an array of strings, whereas there is no guarantee that'll be the case. If I were you, I'd do some checking/filtering:

$queries = array_filter($queries, 'is_string');

That will filter out any non-string elements from the argument array.

Notice: undefined variables
The array you're returning uses both the $commitCode and $errorInfo variables. Why? If the commitCode variable was set, then there will be no errorInfo. Include a return statement in the try block, or return true. If there was an error, then return the errorInfo.

return $this->db->commit();
//in catch:
return array('errorInfo' => $e->getMessage(), 'rollback' => $this->db->rollBack());

Or better still, rethrow the exception possibly contained within a more generic/custom exception object. The caller should be allowed to handle exceptions. The caller should know what was passed to your method, therefore any resulting exception is his responsibility:

catch (PDOException $e)
{
    throw new RuntimeException(
        'Not commited: '. $this->db->rollBack(),
        0,
        $e
    );
}

Prepared statements, no binds
Of course, this isn't your actual code, I take it, but you're creating prepared statements and then execute them with no (room for) binds.

If the query strings come from a trusted source, there's no need to create an instance of PDOStatement, IMO:

foreach($queries as $query)
{
    $this->db->exec($query);
}

will do, and it'll increase performance, too

Allow binds
You'll soon find this method lacking in usability, though. If I wanted to execute a number of SELECT * FROM tbl WHERE ... or UPDATE or INSERT or any query with parameters for that matter, I can't use your method.
Don't worry, though, for that's an easy fix:

public function foo(array $queries)
{
    try
    {
        foreach($queries as $query)
        {
            if (is_array($query))
            {
                $stmt = $this->db->prepare($query['prepare']);
                $stmt->execute($query['bind']);
            }
            else
            {
                if (is_string($query)) $this->db->exec($query);
            }
        }
        return $this->db->commit();
    }
    catch (PDOException $e)
    {
         return array(
             'errorInfo' => $e->getMessage(),
             'rollbackCode' => $this->db->rollBack()
         );
    }
}

That way, I'm able to call this method like so:

$instance->foo(
    array(
        'SELECT * FROM someTable',
        array(
            'prepare' => 'SELECT * FROM anotherTable WHERE someField = :field',
            'bind'    => array(':field' => $val)
    )
);

Of course, this implementation still depends on the user being kind enough to pass the correct arrays to your method. If I were you, I'd create an "Argument class":

class QueryArgument
{
    private $query = null;
    private $bind = null;
    public function __construct($query = null, array $bind = null)
    {
        if (is_array($query))
        {//allow user to pass array('prepare' => '', 'bind')
            $bind = isset($query['bind']) && is_array($query['bind']) ? $query['bind'] : null;
            $query  = isset($query['prepare']) ? $query['prepare'] : null;
        }
        $this->query = is_string($query) ? $query : null;
        $this->bind = null;
    }
    //this is just to make life easier
    public function getTransactionFormat()
    {
        if ($this->bind)
        {
            return array(
                'prepare' => $this->query,
                'bind'    => $this->bind
            );
        }
        return $this->query;
    }
    //implement getters and setters
    public function setBind(array $bind)
    {
        $this->bind = $bind;
        return $this;
    }
    public function getBind()
    {
        return $this->bind;
    }
}

Now you can use this like so:

public function foo(array $queryArgs)
{
    $queries = array_filter($queryArgs, array($this, 'filterQueries'));
    try
    {
        foreach($queries as $query)
        {//same as before
            if (is_array($query)) {/* ... */}
            else {/* ... */}
        }
    }
    catch (PDOException $e) {}
}
//filter out only those elements that are instances of QueryArgument
//convert them to array or string
private function filterQueries($instance)
{

    if ($instance instanceof QueryArgument) return $instance->getTransactionFormat();
    return false;
}


Combination aggregate/greatest-n-per-group SQL query on simplified data set

A common solution is based on Window Functions, as all three are based on the same window they're calculated in a single step:

SELECT url, page_count, word_count, article_id
FROM
 (
   SELECT
      url,
      article_id,
      -- both aggregations rewritten as Group Aggregates
      count(*)         over (partition by article_id) as page_count,
      sum(word_count)  over (partition by article_id) AS word_count,
      -- find the minimum page number
      page_number =
      min(page_number) over (partition by article_id) as is_min_page
   FROM page
 ) as dt
WHERE is_min_page; -- return minimum page only

See fiddle


Splitting a list into overlapping sub-lists

Using ++ to concatenate lists is a bad idea for performance, and it's a sign that you are not using recursion smartly.

Here's what I came up with:

chunk :: Int -> [a] -> [[a]]
chunk n xs =
  if   length chunk' < n then []
  else (chunk' : chunk n (tail xs))
    where chunk' = take n xs