This is the final result of what was done with this code, though the code pertaining to the root question remained unchanged.

Function ContainsWhatMonths(OriginalStartDate As String, _
    OriginalEndDate As String) As Variant

    Dim MonthSet As Variant
    Dim AryCounter As Integer, ISOOffset As Integer
    Dim StartYear As Integer, EndYear As Integer
    Dim StartWeek As Integer, EndWeek As Integer
    Dim StartDay As Integer, EndDay As Integer
    Dim StartWeekStartDate As Date, StartWeekEndDate As Date
    Dim EndWeekStartDate As Date, EndWeekEndDate As Date
    Dim FormattedStartDate As Date, FormattedEndDate As Date
    Dim TotalMonths As Integer, OutputMonths As String

    StartYear = Val(Right(OriginalStartDate, 4))
    StartWeek = Val(Left(OriginalStartDate, 2))
    EndYear = Val(Right(OriginalEndDate, 4))
    EndWeek = Val(Left(OriginalEndDate, 2))

    If StartYear <= EndYear Then

        ' Using the calculation from wikipedia. Honestly, I'm not sure that
        ' I understand this bit, but it seemed to work for my test cases.
        ISOOffset = Weekday(CDate("1/4/" & StartYear), vbMonday) + 3
        StartDay = (StartWeek * 7) - ISOOffset ' Adding 0 for start of week
        EndDay = (EndWeek * 7) + 6 - ISOOffset ' Adding 6 for end of week

        ' Set the starting day for each month, depending on leap year.
        If StartYear Mod 4 = 0 Then
            MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
        Else
            MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
        End If

        For AryCounter = 11 To 0 Step -1
            If StartDay > MonthSet(AryCounter) Then
                ' Using MM/DD/YYYY format - this may be different for you
                StartWeekStartDate = CDate(AryCounter + 1 & _
                    "/" & StartDay - MonthSet(AryCounter) & "/" & StartYear)
                StartWeekEndDate = StartWeekStartDate + 6

                If Month(StartWeekStartDate) <> Month(StartWeekEndDate) Then
                    FormattedStartDate = DateSerial(StartYear, Month(StartWeekEndDate), 1)
                Else
                    FormattedStartDate = DateSerial(StartYear, Month(StartWeekEndDate) + 1, 1)
                End If

                Exit For
            End If
        Next AryCounter

        If EndYear Mod 4 = 0 Then
            MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
        Else
            MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
        End If

        For AryCounter = 11 To 0 Step -1
            If EndDay > MonthSet(AryCounter) Then
                EndWeekStartDate = CDate(AryCounter + 1 & _
                    "/" & EndDay - MonthSet(AryCounter) & "/" & EndYear)
                EndWeekEndDate = EndWeekStartDate + 6

                If Month(EndWeekStartDate) <> Month(EndWeekEndDate) Then
                    FormattedEndDate = CDate(Month(EndWeekEndDate) & "/1/" & EndYear) - 1
                Else
                    FormattedEndDate = CDate(Month(EndWeekEndDate) & "/1/" & EndYear)
                End If

                Exit For
            End If
        Next AryCounter

        ' Switch the commenting on these two lines to return the string
        'ContainsWhatMonths = Array()
        ContainsWhatMonths = vbNullString

        TotalMonths = (Year(FormattedEndDate) - Year(FormattedStartDate)) * 12 + _
            Month(FormattedEndDate) - Month(FormattedStartDate)

        If TotalMonths >= 0 Then

            For AryCounter = 0 To TotalMonths
                OutputMonths = OutputMonths & "," & _
                    Format(DateAdd("m", AryCounter, FormattedStartDate), "MM/YYYY")
            Next

            OutputMonths = Right(OutputMonths, Len(OutputMonths) - 1)

            ' Switch the commenting on these two lines to return the string
            'ContainsWhatMonths = Split(OutputMonths, ",")
            ContainsWhatMonths = OutputMonths
        End If

    End If

End Function


Right-justifying a number with dot leaders

In terms of efficiency, the second form is probably slightly better, as it creates fewer string objects:

def float_rjust(value, width, precision=2, fillchar=' ', separator='', sign=''):
    #[sign][#][0][width][,][.precision][type]
    spec = '{{:{1}{2}{3}.{4}f}}'.format(  # 1
        sign,
        width,
        separator,
        precision
    )  # 2
    value = spec.format(value)  # 3 - slight refactor for clarity
    return value.rjust(width, fillchar)  # 4

vs.

def float_rjust(value, width, precision=2, fillchar=' ', separator='', sign=''):
    #[[fill]align][sign][#][0][width][,][.precision][type]
    spec = '{{:{0}>{1}{2}{3}.{4}f}}'.format(  # 1
        fillchar,
        sign,
        width,
        separator,
        precision
    )  # 2
    return spec.format(value)  # 3

In general terms, I would use e.g. rjust only where that was the only formatting I required; it seems awkward to split the formatting into two steps.

However, I would probably rearrange this completely. You have combined two steps that I think should probably be separate: creating a specification, and applying it to an object.

Using format(value, spec) rather than spec.format(value) (i.e. the format function vs. the str.format method) lets you simplify the spec (getting rid of the extra braces):

def float_spec(width, precision=2, fillchar=' ', separator='', sign=''):
    """Create a specification for formatting floats."""
    return '{}>{}{}{}.{}f'.format(fillchar, sign, width, separator, precision)

You can now inline the format call:

>>> print format(123.456, float_spec(width=10, fillchar='.'))
....123.46

For greater efficiency, as float_spec would return equal (but not identical) strings for the same inputs, you could add memoization/caching. You could also add validation (of either the parameters or created specs) to ensure that it outputs a valid specification for format.


Programming Pearls -- Column 1: Sorting unique numbers with bitfield

use declarations
use std::env;
use std::fs::File;
use std::io::*;

That's a sneaky way to import io::{Error, Result}.  For the sake of
readability, it may be beneficial to spell out io:: each time.  Also
see the Error handling section below.
use declarations can be condensed.  For example:
use std::{env, fs::File, io};

Allocation
let args: Vec<_> = env::args().skip(1).collect();

This is an unnecessary allocation.  The main function can be
rewritten in terms of iterators using peekable:
fn main() -> Result<()> {
    // ...

    let mut args = env::args().skip(1).peekable();

    if args.peek().is_none() {
        // read from stdin
    }

    for arg in args {
        // handle arg
    }

    // ...
}

Error handling
Instead of unwrapping the result of parse, you can propagate the
error.
For a larger program, I would suggest using the anyhow crate
for error handling, which reduces a lot of boilerplate.
Miscellaneous
Don't write return Ok(()); at the end of a function — just use
Ok(()).
I think you meant >= here: if num > MAXNUM.
In print_sorted, you wrap the writer in a BufWriter.  What if the
writer is already buffered?  I would leave the decision to the caller.
You can use let mut bitfield = [0_u8; MAXNUM >> 3]; for less
duplication.
Using a crate like bit-set might be good for readability.


jQuery plugin authoring: Vertical Center example

Interesting question, from a once over:

Consider a 'use strict' after (function( $ ){
You are mixing lowerCamelCase and snake_case, you should stick to lowerCamelCase
I am not a fan of remove_style, it might cause all kinds of unintended consequences, it would be better to store the original values of element and parent and then restore them if we don't center.
I am also not a fan of having 1 listener function per element ( however, if you were to keep the original css info in a closure, then that's fine )
The code would probably be cleaner if you let center_element determine the parent.
The newlines before closing curly braces make the code a bit too sparse towards the end

I would probably try something like this:

(function($){
  'use strict';
  $.fn.verticalCenter = function(options) {

    var settings = $.extend({
      min: 0,    // Minimum width of the viewport for centering to take effect
      max: 10000 // Maximum width of the viewport
    }, options);

    var centerElement = function(element,parent){

      parent.css({ position:'relative' });
      element.css({
        position: 'absolute',
        top: "50%",
        marginTop:-element.height() / 2
      });
    };

    var determine_action = function(element){

      var parent = element.parent(),
          originalParentStyle = parent.style(['position']),
          originalElementStyle = element.style(['position','top','marginTop']);

      $(window).on('load resize orientationchange', function() {

        var windowWidth = window.innerWidth;

        if (windowWidth > settings.min && windowWidth < settings.max) {
          centerElement(element, parent);
        }
        else {
          parent.css(originalParentStyle);
          element.css(originalElementStyle);
        }
      });
    };

    return this.each(function(){
      determine_action($(this));
    });
  };
})(jQuery);


Pythonic way to flatten lists or arbitrary depth using assignment expressions

Welcome to Code Review.

Follow the PEP8 guide for naming conventions. Functions and variables would be snake_case.

When checking for empty list, you don't need to find the length. Empty lists/strings/sets are all falsy values in python.

Use better/fuller names. hd/tl -> head/tail.

There are a few inbuilt utilities in python, which might help you:

itertools.chain
itertools.chain.from_iterable
functools.reduce


Inner product of random floats written to file

If you're going to use C++11, you should firstly look at throwing out rand, and using the newer features found in <random>. The setup is a bit more complex, but the distributions are generally much better statistically. Also, instead of generating numbers one at a time, we're going to generate them in a batch:

template <typename Cont = std::vector<double>>
Cont generate_rand(std::size_t n)
{
    Cont results;
    results.reserve(n);

    std::random_device rd;
    std::mt19937 generator(rd());
    std::uniform_real_distribution<> dist;
    auto random = [&]() { return dist(generator); };
    std::generate_n(std::back_inserter(results), n, random);
    return results;
}

With this, we can generate a set of random values into a vector:

// Read into num however many values we want to generate from args
auto vec = generate_rand(num);

Working with an actual matrix is a bit easier, so let's generate that (instead of an n * n length vector):

std::vector<std::vector<double>> matrix;
for(auto i = 0; i < num; ++i) {
    matrix.emplace_back(generate_rand(num));
}

Something to hold our results, with the size correctly reserved:

std::vector<double> result;
result.reserve(num);

The algorithm library already has a function that will do what you want: std::inner_product:

for(auto it = matrix.begin(); it != matrix.end(); ++it) {
    auto v = std::inner_product(std::begin(vec), std::end(vec), std::begin(*it), 0.0);
    result.push_back(v);
}

Alternately, this is the place where a library like Eigen comes in really handy; with the correct includes, this can be written as follows:

#include <Eigen/Core>

typedef Eigen::MatrixXd Dynamic2d;

int main()
{
    // Initialize num from program args
    auto x = Dynamic2d::Random(num, num);
    auto y = Dynamic2d::Random(1, num);
    auto res = y * x;
}

(Note however that Random gives a range between [-1, 1] when called like this, so you'd need to potentially do a bit of work to get that distribution back to [0, 1]). This is likely to give you the maximum performance, as libraries like Eigen have had a lot of time spent on making them highly efficient.


The Java implementation of pow is implemented for double, rather than long, and probably uses logarithms. This makes direct comparison difficult - pow should have a more or less constant factor time, but double precision arithmetic can be expensive.

Otherwise, it seems reasonably straightforward.

If you're looking for speed, did you try using bit shifts rather than divides? It's possible that the compiler optimizes a divide by 2 to a bit shift, put possibly not. Though, the bit shift is probably somewhat less readable than the divide - and it is possible to be too clever.


You are using one explicit pass over the list (for i in list), and one implicit pass over the list (k - i in list).  This means your algorithm is \$O(N^2)\$.

Note: You can reduce your implementation to one line:

return any(k - i in list for i in list)

But you have a bug.   is_sum_of_2nums_in_list_k([5], 10) returns True.

A one pass algorithm

starts with an empty set,
takes each number in the list,

tests if k-i is in the set,

return true if it is,

adds i to the set.

returns false


Proof that two lines intersect each other at precisely one point in Idris

It still may be far from perfect, but I asked a question on Stackoverflow related to this, and received an excellent answer from xash.

I have attempted to cure my Boolean blindness. If I understand correctly, the operator == asks the question "Is the left hand side equal to the right hand side?" Instead, I want to say: "I have a proof that this holds."

To fix this, I changed a lot of my functions like colinear to more closely match the (=) signature:

colinear : point -> point -> point -> Bool

becomes:

Colinear : point -> point -> point -> Type

Also, I removed a /= b and instead replaced it with Not (a = b).

Here was the resulting code:

interface Plane line point where
  -- Abstract notion for saying three points lie on the same line.
  Colinear : point -> point -> point -> Type
  Coplanar : point -> point -> point -> Type
  Contains : line -> point -> Type

  -- Intersection between two lines
  IntersectsAt : line -> line -> point -> Type

  -- If two lines l and m contain a point a, they intersect at that point.
  intersection_criterion : (l : line) ->
                           (m : line) ->
                           (a : point) ->
                           Contains l a ->
                           Contains m a ->
                           IntersectsAt l m a

  -- If l and m intersect at a point a, then they both contain a.
  intersection_result : (l : line) ->
                        (m : line) ->
                        (a : point) ->
                        IntersectsAt l m a ->
                        (Contains l a, Contains m a)

  -- For any two distinct points there is a line that contains them.
  line_contains_two_points : (a : point) ->
                             (b : point) ->
                             Not (a = b) ->
                             (l : line ** (Contains l a, Contains l b))

  -- If two points are contained by l and m then l = m
  two_pts_define_line : (l : line) ->
                        (m : line) ->
                        (a : point) ->
                        (b : point) ->
                        Not (a = b) ->
                        Contains l a ->
                        Contains l b ->
                        Contains m a ->
                        Contains m b ->
                        (l = m)

  same_line_same_pts : (l : line) ->
                       (m : line) ->
                       (a : point) ->
                       (b : point) ->
                       Not (l = m) ->
                       Contains l a ->
                       Contains l b ->
                       Contains m a ->
                       Contains m b ->
                       (a = b)

  -- There exists 3 non-colinear points.
  three_non_colinear_pts : (a : point ** b : point ** c : point **
                           (colinear a b c = False,
                           Not (a = b),
                           Not (b = c),
                           Not (a = c)))

  -- Any line contains at least two points.
  contain_two_pts : (l : line) ->
                    (a : point ** b : point **
                    (Contains l a, Contains l b))

-- If two lines intersect at a point and they are not identical, that is the o-
-- nly point they intersect at.
intersect_at_most_one_point : Plane line point =>
  (l : line) -> (m : line) -> (a : point) -> (b : point) ->
  Not (l = m) ->
  IntersectsAt l m a ->
  IntersectsAt l m b ->
  (a = b)

intersect_at_most_one_point l m a b l_not_m int_at_a int_at_b =
  same_line_same_pts
  l
  m
  a
  b
  l_not_m
  (fst (intersection_result l m a int_at_a))
  (fst (intersection_result l m b int_at_b))
  (snd (intersection_result l m a int_at_a))
  (snd (intersection_result l m b int_at_b))


Simplifying Macro-Generating Racket Macro

Starting at the top, you have a lot of unused imports. Fortunately, DrRacket can tell you which imports are unused, since it will highlight them in red when you hover your mouse over them. Additionally, if you click the Check Syntax button, it will color all the unused imports red. Using that, we can trim the import list down to the following set:

(require (for-syntax racket/list
                     racket/syntax
                     syntax/parse))

Next, let’s take a look at the bulk of your code, generate-debug-version. First of all, it’s a bit odd that you’re using syntax-case for the outer macro, but syntax-parse for the inner one. Just use syntax-parse everywhere; there’s really no reason to ever use syntax-case in Racket.

Furthermore, the syntax/parse/define module provides a nice define-syntax-parser abbreviated form, which helps to simplify things slightly and remove some redundancy:

(require (for-syntax racket/list
                     racket/syntax)
         syntax/parse/define)

(define-syntax-parser generate-debug-version
  [(_ function-name)
   (with-syntax ([new-name (format-id this-syntax "~a/debug" #'function-name)])
     #'(define-syntax-parser new-name
         (...
          [(_ id [pattern value] ...)
           (with-syntax ([(n ... )
                          (clauses->numbers #'([pattern value] ... ))])
             (syntax/loc this-syntax
               (function-name
                id
                [pattern
                 (begin
                   (displayln (format "Matched case ~a" (add1 n)))
                   value)]
                ...)))])))])

Note the replacement of explicit uses of stx with uses of this-syntax, which always refers to the current piece of syntax being matched within a syntax-parse form.

Now with this in mind, we can start to refactor the bulk of the macro itself. There are a few things that could be improved, staring with the uses of with-syntax. Conveniently, syntax/parse permits #:with clauses after patterns themselves, which act sort of like wrapping the body with with-syntax, but they can use syntax-parse patterns, and the parser will backtrack if they fail. This lets us simplify the code even further:

(define-syntax-parser generate-debug-version
  [(_ function-name)
   #:with new-name (format-id this-syntax "~a/debug" #'function-name)
   #'(define-syntax-parser new-name
       (...
        [(_ id [pattern value] ...)
         #:with (n ...) (clauses->numbers #'([pattern value] ...))
         (syntax/loc this-syntax
           (function-name
            id
            [pattern
             (begin
               (displayln (format "Matched case ~a" (add1 'n)))
               value)]
            ...))]))])

However, there’s actually an issue here, which is that the use of format-id really shouldn’t use this-syntax at all. Instead, it should pull lexical context from #'function-name itself, since the provided identifier should control where the generated identifier’s lexical context comes from. (For an example of where this can be important, try using the define-tracing-match* form from the end of this answer without this change, and you’ll see what the issue is.)

(define-syntax-parser generate-debug-version
  [(_ function-name)
   #:with new-name (format-id #'function-name "~a/debug" #'function-name)
   ; ...
   ])

Another thing we can improve is that we can use the id syntax class for the function-name pattern, which will ensure that the generate-debug-version macro is actually provided an identifier, and will raise a syntax error if it isn’t. Additionally, function-name really isn’t a great name for that pattern, since match is not a function, it is a form. Let’s fix that:

(define-syntax-parser generate-debug-version
  [(_ form-id:id)
   #:with debug-id (format-id #'form-id "~a/debug" #'form-id)
   #'(define-syntax-parser debug-id
       ; ...
       )])

While we’re discussing names, generate-debug-version isn’t a very good one. For one thing, it doesn’t just generate a debug form, it defines one. For another, it specifically generates debug versions of match-like forms, nothing else, so that should probably be included in the name, too. I picked the name define-tracing-match, but you could pick a similar name if you wished.

Okay, what now? Well, while clauses->numbers works, it could honestly be better. It’s really nice that we can use syntax patterns to write such a declarative style of macro, but clauses->numbers isn’t declarative at all, it’s completely procedural. To help fix that, we can write a splicing syntax class which will number the clauses for us, lifting out the procedural component into a separate piece. That looks like this:

(begin-for-syntax
  (define-splicing-syntax-class numbered-clauses
    #:attributes [[pattern 1] [value 1] [n 1]]
    #:description #f
    [pattern {~seq [pattern value] ...}
             #:with [n ...] (range (length (attribute pattern)))]))

You can read more about what syntax classes do and how they work in the extensive documentation, but the basic idea here is to extract out some procedural logic into a reusable pattern than syntax-parse can understand. The #:attributes and #:description options are optional here, but the former helps readability, and the latter helps with error messages.

With that syntax class in place, we can further simplify the main macro by using it:

(define-syntax-parser define-tracing-match
  [(_ form-id:id)
   #:with debug-id (format-id #'form-id "~a/debug" #'form-id)
   #'(define-syntax-parser debug-id
       (...
        [(_ id clause:numbered-clauses)
         (syntax/loc this-syntax
           (form-id id
             [clause.pattern
              (begin
                (displayln (format "Matched case ~a" (add1 'clause.n)))
                clause.value)]
            ...))]))])

This makes our main macro completely declarative (save for the small use of format-id, which is pretty harmless), and it’s pretty much entirely built out of patterns and templates. This is what the Racket macro system is so good at: it lets you pretty much just write what you mean, and you still get great error reporting for when things go wrong.

With all these changes in place, here’s what the final code looks like:

#lang racket

(require (for-syntax racket/list
                     racket/syntax)
         syntax/parse/define)

(begin-for-syntax
  (define-splicing-syntax-class numbered-clauses
    #:attributes [[pattern 1] [value 1] [n 1]]
    #:description #f
    [pattern {~seq [pattern value] ...}
             #:with [n ...] (range (length (attribute pattern)))]))

(define-syntax-parser define-tracing-match
  [(_ form-id:id)
   #:with debug-id (format-id #'form-id "~a/debug" #'form-id)
   #'(define-syntax-parser debug-id
       (...
        [(_ id clause:numbered-clauses)
         (syntax/loc this-syntax
           (form-id id
             [clause.pattern
              (begin
                (displayln (format "Matched case ~a" (add1 'clause.n)))
                clause.value)]
            ...))]))])

A bit more concise, and hopefully a bit clearer, too.

Now for a couple of extras. You mentioned that you wanted to write a generate-debug-versions macro. This wouldn’t be too hard to do with the new version of generate-debug-version by using some well-placed ellipses, actually, but it would probably be even easier to just define a new generate-debug-versions macro (or, since we changed the name, a define-tracing-match* macro) that defers to the existing one.

The easiest way to do this is probably to use the define-simple-macro form, also from syntax/parse/define, which is basically syntax-rules mixed with all the syntax-parse enhancements. The macro itself is trivial:

(define-simple-macro (define-tracing-match* form-id:id ...)
  (begin (define-tracing-match form-id) ...))

Now, it’s extremely easy to define both match/debug and match*/debug at the same time:

(define-tracing-match* match match*)

One final additional thing you can do is adjust the format-id call to copy source location information and syntax properties from the provided form-id, like this:

#:with debug-id (format-id #'form-id "~a/debug" #'form-id
                           #:source #'form-id #:props #'form-id)

By doing this, when you hover your cursor over a use of match/debug in DrRacket, it will draw an arrow to the identifier used with define-tracing-match to generate the debug version in the first place, which is useful.

However, if you wanted to get even fancier, you could skip that step and use the 'sub-range-binders syntax property to convey even more fine-grained information to DrRacket. Specifically, you can adjust the outer macro for define-tracing-match to attach the property as follows:

(define-syntax-parser define-tracing-match
  [(_ form-id:id)
   #:with debug-id (format-id #'form-id "~a/debug" #'form-id)
   (syntax-property
    #'(define-syntax-parser debug-id
        (...
         [(use-id id clause:numbered-clauses)
          (syntax/loc this-syntax
            (form-id id
                     [clause.pattern
                      (begin
                        (displayln (format "Matched case ~a" (add1 'clause.n)))
                        clause.value)]
                     ...))]))
    'sub-range-binders
    (let ([id-len (string-length (symbol->string (syntax-e #'form-id)))])
      (vector (syntax-local-introduce #'debug-id) 0 id-len 0.5 0.5
              (syntax-local-introduce #'form-id) 0 id-len 0.5 0.5)))])

This will make DrRacket draw an arrow for part of the match/debug identifier, the part that shares the same name as the provided one. The best way to illustrate what this does is with a screenshot:

(This is the technique the built-in struct macro uses to get the special binding arrows for its field accessors.)

Admittedly, however, this is pretty advanced macrology, and I probably wouldn’t do something this fancy unless I was distributing it as part of a library, so no worries if you leave that part out.


Addition function for two Big Integers represented as std::string

Memory management

There are no leaks, which is great!

However, there is an unnecessary copy being made:

//I think keeping the assignment and declaration of addend in
// multiple lines prevents copy constructors, right?
std::string addend;
addend = a.size() > b.size() ? b:a;

Well, the comment is correct in that the copy constructor doesn't get called, but the copy assignment operator - and that one not only creates a copy of the right hand side operand, but also needs to clean up the original state.

A better way would be to use a reference instead:

const std::string &addend = a.size() > b.size() ? b : a;

Now, no copy is being made, but you can still easily access the smaller operand.

Performance

The simplest way to improve performance would be to chose better data structures/data representations.

The current implementation with std::string has one slight advantage (it is a string, i.e. directly human readable), and some disadvantages:

It wastes a lot of memory (1 byte per decimal digit = 25.6x more memory usage than necessary).
It operates in really small steps (1 byte at a time).
There are some unnecessarily complicated repeated checks.
Inserting a new leading digit (because of carryover) requires all digits to be moved in memory, plus a likely reallocation.

For better performance, these issues should be addressed.

  NOTE: For the best performance, you need to have a look at how the target processor works and understand how you can apply that knowledge to your advantage. That will likely include having to use embedded assembly (e.g. for x86 platforms, having access to the CPU carry flag can be really helpful) and similar tricks.

  But this question is targeting C++, so I'll try to give an example that can be portably done within C++ with not too much overhead.

So, we need to address the issues mentioned above. Let's go through them one at a time:

  Inserting a new leading digit (because of carryover) requires all digits to be moved in memory, plus a likely reallocation.

This can be amended by storing the digits in reverse order (new digit gets inserted at the back instead of the front) and by switching to a std::vector for storage (with maybe some extra capacity to prevent the reallocation).

std::vector<char> BigInt::add(const std::vector<char> &a, const std::vector<char> &b) const
{
    // Some helper variables
    auto min_size = std::min(a.size(), b.size());
    auto max_size = std::max(a.size(), b.size());

    std::vector<char> result(a.size() > b.size() ? a:b);
    const std::vector<char> &addend = a.size() > b.size() ? b : a;

    char carry = 0;
    char adder = 0;

    for(int cnt = 0; cnt < max_size; ++cnt)
    {
        adder = result[cnt] - '0' + carry;

        if(cnt < min_size)
        {
            adder += addend[cnt] - '0';
        }

        result[cnt] = adder%10 + '0';
        carry = adder/10;
    }

    if(carry)
    {
        result.push_back(carry + '0');
    }

    return result;
}

Already looks a lot cleaner, doesn't it?

  There are some unnecessarily complicated repeated checks.

Some of the complicated length calculations already got taken care of, but there is one part that is needlessly repeated:

        if(cnt < min_size)
        {
            adder += addend[cnt] - '0';
        }

Why needlessly? Well, actually we know that this condition will be true for the first min_size iterations of the for loop, and false afterwards. With that knowledge, we can move that check one level higher, and replace the for loop with:

    for(int cnt = 0; cnt < min_size; ++cnt)
    {
        adder = (result[cnt] - '0') + carry + (addend[cnt] - '0');
        result[cnt] = adder%10 + '0';
        carry = adder/10;
    }

    for(int cnt = min_size; carry && cnt < max_size; ++cnt)
    {
        adder = result[cnt] - '0' + carry;
        result[cnt] = adder%10 + '0';
        carry = adder/10;
    }

Of course, now the loop bodies are nearly identical, but that can easily be fixed with some refactoring. Full code:

std::vector<char> BigInt::add(const std::vector<char> &a, const std::vector<char> &b) const
{
    // Some helper variables
    auto min_size = std::min(a.size(), b.size());
    auto max_size = std::max(a.size(), b.size());

    std::vector<char> result(a.size() > b.size() ? a:b);
    const std::vector<char> &addend = a.size() > b.size() ? b : a;

    char carry = 0;

    auto add_digits = [&](char lhs, char rhs)
    {
        auto adder = lhs + rhs + carry;
        carry = adder / 10;
        return adder % 10;
    };

    for(int cnt = 0; cnt < min_size; ++cnt)
    {
        result[cnt] = add_digits(result[cnt] - '0', addend[cnt] - '0') + '0';
    }

    for(int cnt = min_size; carry && cnt < max_size; ++cnt)
    {
        result[cnt] = add_digits(result[cnt] - '0', 0) + '0';
    }

    if(carry)
    {
        result.push_back(carry + '0');
    }

    return result;
}

  It wastes a lot of memory (1 byte per decimal digit = 25.6x more memory usage than necessary).

  It operates in really small steps (1 byte at a time).

Fixing this requires an increase in the digit "size": Before, we were using base-10 digits stored in chars. This can easily be improved to base-256 digits stored in chars (assuming 8 bit char, could be larger!).

But that's basically just calculating on the chars themselves. Most processors can work directly with bigger numbers, like ints (which are usually the largest integer type the target CPU can handle natively). So, why not use ints as "digits"?

  Sadly, ints aren't exactly portable themselves; signed integers can be handled very differently on different processors (e.g. one's complement or two's complement). But: Unsigned intergers are thoroughly specified by the C++ standard, so we can use those.

Also, we can instruct the result vector to preallocate space in case we need space for a new leading digit.

This can easily be added upon the code above for this:

bool check_overflow(unsigned int lhs, unsigned int rhs)
{
    return lhs > std::numeric_limits<unsigned int>::max() - rhs;
}

std::vector<unsigned int> BigInt::add(const std::vector<unsigned int>& a, const std::vector<unsigned int>& b) const
{
    auto min_size = std::min(a.size(), b.size());
    auto max_size = std::max(a.size(), b.size());

    auto result = std::vector<unsigned int>();
    result.reserve(max_size + 1);

    const auto& larger = (a.size() > b.size() ? a : b);
    const auto& smaller = (a.size() > b.size() ? b : a);

    auto carry = 0u;

    auto add_digit = [&](unsigned int lhs, unsigned int rhs)
    {
        auto sum = lhs + rhs + carry;
        carry = (check_overflow(lhs, rhs) || (sum == 0 && carry)) ? 1 : 0;
        return sum;
    };

    for(auto i = 0; i < min_size; ++i)
    {
        result.push_back(add_digit(larger[i], smaller[i]));
    }

    for(auto i = min_size; i < max_size; ++i)
    {
        result.push_back(add_digit(larger[i], 0));
    }

    if(carry) result.push_back(carry);

    return result;
}

  Of course, this isn't perfect performance yet, much can be improved by using knowledge about the target architecture, e.g. by using SSE instructions or similar. Still, this should be quite a lot faster than the original approach, and should be fully portable between different platforms.


Unit Test to verify number of times lazy initialization logic is executed for a data member

Delegate the computation of a and b to a method, say, .compute(). Since we want to spy this method's execution, we will suppose that we have Guava and its useful @VisibleForTesting annotation, and make the method protected:

@VisibleForTesting
protected String compute(String a, String b) { // code here }

Now, code written using Mockito and TestNG (with test file in same package than class A, so that the compute() method is visible):

@Test
public void computationOfCHappensOnlyOnce()
{
    final String a = "whatever";
    final String b = "you want";

    final A spy = spy(new A(a, b));

    for (int i = 0; i < 10; i++)
        spy.getC();

    verify(spy, times(1)).compute(eq(a), eq(b));
}

Note: the way your class is currently written, it is NOT thread safe. The quick, coarse way to fix it is to make .getC() synchronized.

EDIT Discussion on a different design to get the value of c

This requires a creation of a new factory class for instances of class A; it would have the responsibility to create new instances and compute c:

// if the class is a singleton...
final FactoryForA factory = FactoryForA.getInstance();

final A a = factory.newA(a, b);

// This calls back to the factory to compute c:
a.getC();

The A class needs to implement .equals() and .hashCode() (on fields a and b but obviously not c!). Also, it has a constructure which is now package private (so that the factory can access it) and whose prototype is:

final String a, b;
final FactoryForA factory;
// No `c` member, see below

A(String a, String b, FactoryForA factory)
{
    this.a = a; this.b = b; this.factory = factory;
}

public getC()
{
    return factory.computeC(this);
}

Now for the factory itself: it has an ExecutorService and a Map<A, FutureTask<String>>. Here is the code of computeC():

// instance variables of the factory
private final ExecutorService service
    = Executors.newFixedThreadPool(5); // for example
private final Map<A, FutureTask<String>> map = new HashMap<>();

// package private
String computeC(final A a)
{
    FutureTask<String> task;
    // Synchronized map access
    synchronized(map) {
        // If there is no task created for that instance of A, create it
        // and submit it for execution
        task = map.get(a);
        if (task == null) {
            task = createFutureTask(a); // TODO, but nothing too complicated
            // IMPORTANT! If you don't do this, the task is not executed
            // and .get() below will block indefinitely
            service.execute(task);
            map.put(a, task);
        }
    }
    // A FutureTask will keep its status! We can therefore call .get()
    // as much as we like; the computation will only have happened once
    return task.get();
}

One advantage is that if two instances created for A are equal (ie, the same a and b parameters), computation for c happens only once!


Javascript - Find a deepest node in a binary tree

Here are my thoughts:

Don't mutate function parameters unless there is good reason to do so.

node.depth = level;

The above statement basically breaks the contract of the function. The function claims to locate the deepestNode, but in fact it does findDeepestNodeAndSetDeepestPropOnAllNodes (silly, but you get the idea). This could lead to confusing, subtle bugs for the client of your module and is a serious issue.

If you want to return the level in addition to the node itself, that's easily done by returning a {node, level} object pair which doesn't corrupt the reference to node. However, since the test suite disregards the level, I'd omit it since the function name makes no mention of this and it's not typically valuable information.
Always use braces for blocks of code:

if (deepestLeft.depth > deepestRight.depth)
    return deepestLeft;
else
    return deepestRight;

is clearer and less error-prone as:

if (deepestLeft.depth > deepestRight.depth) {
  return deepestLeft;
}

return deepestRight;

Use default parameters:

function deepestNode(node, level) {
    if (!level)
        level = 0;
...

can be

function deepestNode(node, level=0) {
...

Avoid excessive conditionals; it's possible to simplify 6 branches to 2, reducing the cognitive load required to understand the code. Re-write negative conditionals to be positive when possible.

For example,

if (!node.left && !node.right)
    return node;

can be eliminated. As a rule of thumb, I try to operate only on the current node when writing recursive functions unless I'm forced to do otherwise.
Avoid excessive references and intermediate variables. Consider:

let deepestLeft, deepestRight = node;
/* ... various conditionals that may or may not change where
   `deepestLeft`, `deepestRight` and `node` points to ... */

// later on, unclear state

As with conditionals, when you begin relying on aliases for objects, it becomes difficult to keep track of what's pointing where. Code like this should only be written if there's no way around it, which isn't the case here.

In fact, this line causes crashes when node.right is the only child of a node. You may have meant:

let deepestLeft = deepestRight = node;

Adding more thorough tests to your suite would help detect bugs like this.

As an aside, prefer const instead of let unless you have to reassign the variable.
Don't crash on undefined/null parameters if it's trivial to prevent.

node.depth = level; // boom if `node` is undefined

Here's a re-write. I wrote this as browser code, but you can dump it into module.exports:

const deepestNode = (node, deepest={level: -1}, level=0) => {
  if (node) {
    if (level > deepest.level) {
      deepest.node = node;
      deepest.level = level;
    }

    deepestNode(node.left, deepest, level + 1);
    deepestNode(node.right, deepest, level + 1);
  }

  return deepest.node;
};

class TreeNode {
  constructor(val, left=null, right=null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

const root = new TreeNode(1,
  new TreeNode(2,
    new TreeNode(4)
  ),
  new TreeNode(3)
);

console.log(deepestNode(root));

This function can also be written iteratively in a clean way, avoiding call stack overflow errors and function call overhead:

const deepestNode = node => {
  let deepest = {level: -1};
  const stack = [[node, 0]];

  while (stack.length) {
    const [curr, level] = stack.pop();

    if (curr) {
      if (level > deepest.level) {
        deepest = {node: curr, level: level};
      }

      stack.push([curr.left, level + 1], [curr.right, level + 1]);
    }
  }

  return deepest.node;
};


Whitelist HTML tags Microsoft Sanitizer and custom Regex

You could simplify the declaration of the tags you want to keep, as it is very structured:

var whitelist = new List<string>(new string[] { "p", "h1", "br" });

foreach (var w in whitelist) {
  txt = txt.Replace("<" + w + ">", "&lt;" + w + "&gt;")
           .Replace("<" + w + "/>", "&lt;" + w + "/&gt;"));
}

var remove = Sanitizer.GetSafeHtmlFragment(txt);

foreach (var w in whitelist) {
  remove = remove.Replace("&lt;" + w + "&gt;", "<" + w + ">")
                 .Replace("&lt;" + w + "/&gt;", "<" + w + "/>"));
}

var again = RegexHelpers.StripHtmlAttributes(remove);

var tt = again;


DFT (Discrete Fourier Transform) Algorithm in Swift

I think your code is doing DFT (Discrete Fourier Transform) and not FFT. You are doing \$O(n^{2})\$ operations in the 2 for loops. The FFT is supposed to be \$n*\log(n)\$.

First thing to do is remove repeated multiplications. The terms Double(n)*2*M_PI/Double(N) can be calculated (as initial step) for every \$n\$ in \$0:(N-1)\$. Make a map for each \$n\$ to this value and use it to calculate \$q\$.

Then, see if using properties of \$\sin(2x)\$, \$\sin(\frac{x}{2})\$, \$\cos(2x)\$, \$\cos(\frac{x}{2})\$, etc. are  faster than actually calling those functions.

For example:

$$\begin{align}
\sin(2x) &= 2\sin(x)\cos(x) \\
\cos(2x) &= \cos^{2}(x) - \sin^{2}(x)
\end{align}
$$

or

$$\begin{align}
\sin\left(\frac{x}{2}\right) &= \sqrt{\frac{1-\cos(x)}{2}} \\
\cos\left(\frac{x}{2}\right) &= \sqrt{\frac{1+\cos(x)}{2}}
\end{align}
$$

If these are faster, you will reduce the complexity significantly.


Is there any way to simplify it further?

Sure, but what's more important: Create some useful methods. Your class is single shot only: read data, classify, output. This is a bad start, a method should do one thing only. So you need three methods.

You classify into 4 categories and this is a clear case for an enum:

enum TriangleType {
    EQUILATERAL, INVALID, ISOSCELES, SCALENE
}

This is the only interesting method:

static TriangleType classify(int a, int b, int c) {
    if (a <= 0 || b <= 0 || c <= 0) return INVALID; // added test
    if (a == b && b == c) return EQUILATERAL;
    if (a >= b+c || c >= b+a || b >= a+c) return INVALID;
    if (b==c || a==b || c==a)) return ISOSCELES;
    return SCALENE;
}

Note that I'm violating the "braces everywhere" rule. I can't help myself.

In case of ISOSCELES, there's no need for checks like a==b && b!=c as we already know that not all sites are equal.

In case of SCALENE, there's no need for any test, as we know that there are no two equals sides.

You're using a bit too many parentheses, but feel free to keep them if you feel you need them.

Be consequent with your spacing, there are rules for it, which help to make it more readable:

single space between "if" and "("
(but no space between a method name and "(")
no space after "("
no space before ")"

The addition is subject to overflow as Ryan noted, but let's ignore it for now. You should know about it and do a corresponding test if needed, but in general, overflow is impossible to check for everywhere.

Here it's trivial, just replace a >= b+c by a >= (long) b+c. The latter means a >= ((long) b) + c, which is equivalent to ((long) a) >= ((long) b) + ((long) c).


Lets start with the time complexity of your current algorithm:

for (int i = 0; i < A.length; i++) has a time complexity of O(M) (Length of array 'A' is 'M')
Arrays.sort(I) has a time complexity of O(N*log(N))1
Arrays.fill(I, I[I.length - 1]) has a time complexity of O(N) (The number of counters)

That means the complexity of your current algorithm is O(N^2 * log(N) * M).

You can replace the sorting by keeping track of the maximum value for all counters like this:

public int[] maxCount(int[] A, int N)
{
    int[] I = new int[N];
    //Initialize the max value to 0
    int max = 0;

    for (int i = 0; i < A.length; i++)
    {
        if (A[i] == N + 1)
        {
            Arrays.fill(I, max);
        }
        else
        {
            I[A[i] - 1]++;

            if (I[A[i] - 1] > max)
            {
                //Update the max value
                max = I[A[i] - 1];
            }
        }
    }
    return I;
}

The time complexity of this version is now O(M * N). This version is also using if statements to control the flow of the program as opposed to exceptions which is an anti-pattern2.

UPDATE: I've used the suggestion of Mees de Vries from his comment to implement a data structure for the problem. The complexity of the function reading the instruction incrementCounters() is O(n).

public class SynchronizedCounters
{
    private int[] counters;
    private int size;
    private int base = 0;
    private int max = 0;
    private final int INSTRUCTION_OFFSET = 1;

    public SynchronizedCounters(int size)
    {
        this.size = size;
        this.counters = new int[size];
    }

    public void incrementCounters(int[] instructions)
    {
        for (int instruction : instructions)
        {
            int instruct = instruction - INSTRUCTION_OFFSET;

            if (instruct >= size)
            {
                base = max;
            }
            else
            {
                normalizeCounter(instruct);

                counters[instruct]++;

                if (counters[instruct] > max)
                {
                    max = counters[instruct];
                }
            }
        }
    }

    public Integer getCounterValue(int counter)
    {
        normalizeCounter(counter);
        return counters[counter];
    }

    private void normalizeCounter(int index)
    {
        counters[index] = java.lang.Math.max(counters[index],base);
    }
}

Example using the class:

public static void main(String[] args)
    {
        SynchronizedCounters synchronizedCounters = new SynchronizedCounters(5);
        synchronizedCounters.incrementCounters(new int[]{1, 1, 1, 3, 2, 1, 1, 6, 2, 3});
        System.out.println("Value of first counter: " + synchronizedCounters.getCounterValue(0));
    }

Output:

Value of first counter: 5

1 https://stackoverflow.com/questions/21219777/the-running-time-for-arrays-sort-method-in-java

2 https://web.archive.org/web/20140430044213/http://c2.com/cgi-bin/wiki?DontUseExceptionsForFlowControl


Customized class crawler to harvest names and phone numbers from a webpage

In some sense, you are reinventing what Scrapy web-scraping framework provides from out-of-the-box. Take a look how Scrapy spiders are written and you may find something similar, but better organized with less boilerplate code. Since, you've been doing quite a lot of web-scraping, I would go ahead and give Scrapy a try here.

Some notes about the code:

naming. Remember: code is much often read than written. YelPage can be replaced with a more explicit YellowPageScraper; next_page actually means next_pages since you locate multiple of them - etc. (please refer to the code below for the other improved variable names)
as I've mentioned before, you can reuse a session by having a session instance as your instance variable
comments before each of the methods should be transformed to proper method documentation strings

Improved code:

import requests
from lxml import html

class YellowPageScraper:
    base_url = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=Los+Angeles%2C+CA"
    url = "https://www.yellowpages.com"

    def __init__(self):
        self.vault = []
        self.session = requests.Session()

    def crawl(self):
        self.get_urls(self.base_url)
        self.process_links(self.base_url)

    def get_urls(self, link):
        """Going to the main page for collecting links leading to the target page."""
        response = self.session.get(link)
        tree = html.fromstring(response.text)

        for item in tree.xpath("//div[@class='info']"):
            item_links = item.xpath(".//a[@class='business-name'][not(@itemprop='name')]/@href")
            for page in item_links:
                self.target_page(self.url + page)

    def process_links(self, link):
        """Creating links leading to the next page."""
        response = self.session.get(link)
        tree = html.fromstring(response.text)

        next_urls = tree.xpath("//div[@class='pagination']//li/a/@href")
        for next_url in next_urls:
            self.get_urls(self.url + next_url)

    def target_page(self, urls):
        """Scraping required data reaching this target page."""
        response = self.session.get(urls)
        tree = html.fromstring(response.text)

        for post in tree.xpath("//*[@id='main-header']"):
            name = post.findtext(".//div[@class='sales-info']/h1")
            phone = post.findtext('.//p[@class="phone"]')

            records = name, phone
            if records not in self.vault:
                self.vault.append(records)

    def __str__(self):
        return self.vault

if __name__ == '__main__':
    crawler = YellowPageScraper()
    crawler.crawl()
    for item in crawler.vault:
        print(item)


MVVM Calling command by name from CommandBindings

I might not fully understand how your commands are meant to be used, but the following things strike me as rather cumbersome:

Requiring a separate class for each command.
Command (class) names must be globally unique.
Having to pass context to a command.

Alternative

An alternative is to create a single RelayCommand class that wraps an Action:

public class RelayCommand : ICommand
{
    public RelayCommand(Action action) { ... }
    ...
}

In your view models, you can expose commands as bindable properties:

public class MyViewModel
{
    private ICommand _saveDataCommand;
    public ICommand SaveDataCommand
    {
        get { return _saveDataCommand ?? (_saveDataCommand = new RelayCommand(SaveData)); }
    }

    private void SaveData()
    {
        ...
    }
}

And in your views, you can bind to these commands:

<Button Command="{Binding SaveDataCommand}" />

Now, you no longer have to create separate classes, just separate methods (and ICommand properties, but see below). Because those methods live in a specific view model, they likely already have access to the context they need, and their name only needs to be unique within that view model, not globally.

A possible further improvement

I've successfully been using the above approach in WPF, but having to create all those ICommand properties was still cumbersome. Initially I made a code snippet to make them easier to write, but eventually I settled on a different approach.

The data binding system in WPF (and perhaps also UWP, I'm not sure) not only uses reflection, it also checks if a data context implements ICustomTypeDescriptor, and if so, it'll use the GetProperties methods to detect additional 'properties'. I used that to create a view model base class that generates such a 'property' for each method that is marked with a custom [Command] attribute.

This took some work, but in the end it simplified things to just this:

public class MyViewModel : ViewModelBase
{
    [Command]
    public void SaveDataCommand()
    {
        ...
    }
}


Filling a memory segment with a bit pattern

You have some unnecessary comments. For example, this comment:

# Move that length to CTR register
mtctr r4

Anyone who knows this instruction set should be easily able to know what that line is doing.

Comments are supposed to explain why, not how because "how" is very easy to find out on one's own.

You did not specify what assembler you were using, but if your assembler allows for creating macros, I recommend that you make macros for those "random" numbers that are in your code.

These "random" numbers are called magic numbers; they've just appeared out of no-where.

In the NASM assembler, you can do something like this:

%define BIT_PATTERN 0x55

Then, in the line where you are working with the bit pattern, you write:

addi r3, r0, BIT_PATTERN

And now there is no confusion about where that number came from and you can remove that comment from above this line.

You should see if you can create macros for this bit pattern like I showed you, and for the memory segment addresses.

Note: I could not find a PowerPC assembler any where on the internet so my recommendations from here on may be slightly flawed in some places.

These lines can be simplified:

addis r2, r0, 0x0000
ori r2, r2, 0x7FFF

All you seem to be trying to do here is stick the value 0x7FFF into the register r2. However, you are taking two instructions to do this:

Move 0 into r2
Make r2 become 0x7FFF with ori

This seems a little unnecessary; why can't you just put 0x7FFF into r2 to begin with, like you did when you put the bit pattern into r3? A much simpler way of writing this would be:

li r2, 0x7FFF

which is directly equivalent to

addi r2, 0, 0x7FFF

Note: This assumes that r0 was 0 to being with, which I think it was.

The above will put the value 0x7FFF into r2. You can do this same thing for when you are putting the size of the memory segment into r4, and when you are putting the bit pattern into r3.

It didn't look like you specifically needed to actually use the addis instruction, which seems unnecessarily complicated for simply putting a value into a register.

However, if you did, just change the instruction to:

lis r2, 0x7FFF

You are using the registers incorrectly.

According to this page, the registers r2, r3, and r4 are for the table of contents pointer, the return of a function/subroutine, and (commonly) a function/subroutine argument, respectively.

I think you should be using the register r4 through r10 because, since you are not using a subroutine, these registers can now be used for general purpose. You might be okay with using r3, but you definitely should not be using r2.

Putting it all together:

li r4, 0x7FFF
li r5, 0x55
li r6, 0x1000

mtctr r6

loop:
    stbu r5, 1(r4)
    bdnz

If you notice any bugs, notify me.


Finding the largest word in the given String

Before I give you my answer, a bit of critique regarding your code:

Naming convention in JS use camelCase.
What is sen? By itself, it doesn't tell me what it is. Name your variables meaningfully, one that tells you what it does the first time you read it.
Be consistent with whitespace. Usually, there should be spaces before and after operators (ie. a = b, foo = [] etc.)
Indention. Always have proper indention.
By sorting, you already fail the criteria of "first longest word prevails" because of sort instability.

You can simply use reduce. Carry around the longest word through the array, replacing it when you find something longer.

function findLongestWord(sentence) {
  return sentence.split(' ').reduce(function(longestWord, word){
    return word.length > longestWord.length ? word : longestWord;
  });
}

var str = "The quick brown fox jumps over the lazy dog";

document.write(findLongestWord(str));


Counting words from standard input in Swift

Regarding standard input, see Martin's answer below.

As for splitting strings into words and returning them as a sorted dictionary with word counts, that sounds like a useful thing to have around as a String extension. This is simple to implement unless you insist on pure Standard Library solution:

import Foundation

public extension String {

    public var wordCounts: [String:Int] {
        var d: [String:Int] = [:]
        enumerateSubstringsInRange(characters.indices, options: .ByWords) { word, _, _, _ in
            guard let word = word?.lowercaseString else { return }
            d[word] = (d[word] ?? 0) + 1
        }
        return d
    }

    public var sortedWordCounts: [(word: String, count: Int)] {
        return wordCounts.sort{ $0.0 < $1.0 }.map{ (word: $0, count: $1) }
    }
}

Usage as follows (to produce the same output as your code):

if let input = readLine() {
    let report = input.sortedWordCounts.map{"\($0) \($1)"}.joinWithSeparator("\n")
    print(report)
}

For example, the following input ↓

Baa, baa, black sheep,/ Have you any wool?/ Yes, sir, yes, sir,/ Three bags full

...yields the following output ↓

any 1
baa 2
bags 1
black 1
full 1
have 1
sheep 1
sir 2
three 1
wool 1
yes 2
you 1

Edit

As Martin points out in the comment, your Ruby code reads multiple lines, or even multiple files… Here is a version that would do something like that, though you’ll of course need to adapt it to your needs. Note that I’ve added that eof so that we can play with this in the Xcode.

public func += <T> (inout lhs: [T:Int], rhs: [T:Int]) {
    for (k, i) in rhs {
        lhs[k] = (lhs[k] ?? 0) + i
    }
}

print("Type your terminating token or just type return if an empty line works for you:")
let eof = readLine()
print("Enter your lines:")

var wordCounts: [String:Int] = [:]

while let line = readLine() where line != eof {
    wordCounts += line.wordCounts
}

let report = wordCounts
    .sort{ $0.0 < $1.0 }
    .map{"\($0) \($1)"}
    .joinWithSeparator("\n")

print(report)


Convert Ternary Expression to a Binary Tree

You can delete the BST class. You don't use it anywhere.
Error handling looks weird to me. I suggest throwing an exception if the input is invalid. You also don't check all possible cases. For instance, you code prints a tree ? | a | b | for the input ??a:b, which is clearly invalid. I'd recommend either adding proper error handling or just dropping it altogether (the problem statement says that the string is a ternary expression, anyway).
Comments should not repeat the code. If you have something like // if it is a valid character, it's a good indicator that the following check should be moved to a separate method with a proper name (something like private boolean isValidCharacter(Node node, String expression, int index).


Functional translation of dice simulation

Let me first present my solution and then comment below: Let me point the code is more verbose than needed, in order to be more descriptive.

import scala.annotation.tailrec
import scala.collection.SortedSet
import scala.util.Random

//=========Neat reusable methods=============

//Infinite iterator of the results of a dice throw
def diceResultIterator(sidesCount: Int): Iterator[Int] = {

  case class Dice(rnd: Random, sidesCount: Int, upside: Int)
  //Gets a dice, returns a dice, functional "mutation"! For more, search State monad
  def roll(initDice: Dice) = {
    val newSide = initDice.rnd.nextInt(initDice.sidesCount) + 1
    Dice(initDice.rnd, initDice.sidesCount, newSide)
  }
  val someDice = Dice(new Random, sidesCount, 1)
  val diceIterator = Iterator.iterate(someDice)(roll)
  diceIterator.map(_.upside)
}

//Infinite iterator of the results of the given function
def simulateManyTimes[T](f: => T) = Iterator.iterate(f)(_ => f)

//A usual general function to calculate and average
def average(values: Iterable[Int]): Option[Double] = {
  val (total, len) = values.foldLeft((0, 0)) { case ((sum, cnt), value) => (sum + value, cnt + 1) }
  if (len > 0) Some(total.toDouble / len) else None
}
def averageResultsOfIntSimulations(f: => Int, repeat: Int) = {
  average(simulateManyTimes(f).take(repeat).toIterable)
}
//===================Problem specific part======================

//Similar to OP method, just encapsulated the recursion
def countThrowsUntilAllSidesSeen(diceIter: Iterator[Int], sidesCount: Int): Int = {
  @tailrec
  def recursiveHelper(seen: SortedSet[Int], count: Int): Int = {
    if (seen.size == sidesCount)
      count
    else
      recursiveHelper(seen + diceIter.next(), count + 1)
  }
  recursiveHelper(SortedSet[Int](), 0)
}
def simulationWrapper(sides: Int, simRepeat: Int) = {
  averageResultsOfIntSimulations(countThrowsUntilAllSidesSeen(diceResultIterator(sides), sides), simRepeat).get
}

simulationWrapper(6, 1000000)

Generally, creating a new Randomfor each throw is a bad practice since it may produce less random results than expected. My proposed solution reuses the same Random in a functional way for each simulation.

I am in favor of the school that says code should be self documenting, and your second method tries to fit too many things in one place, adding obscurity.

val runs = Iterator.fill(nsim)(SortedSet[Int]())
runs.map( x=> nthrows(x, 0, nsides) ).reduceLeft(_+_) * 1.0 / nsim

For example there is no good reason why you would fill an iterator with SortedSets then use then with map, instead of just runs.map( _ => nthrows(SortedSet[Int](), 0, nsides)) Counter-intuitive code is bad code. In production, the dev next to you would certainly tap your shoulder to ask you to explain your code, generally not too happy that he had to do so.

As general advice, tune the code to your audience, like with all forms of communication. For example, the diceResultIterator in my solution is purposefully verbose, to make the concept clearer. When you are comfortable with it, you can see that it is rather trivially refactored to ~half the lines. Scala has a trap to chain operations into obscurity, be mindful about this ;)

When you see recursiveHelper inside countThrowsUntilAllSidesSeenwith arguments seen: SortedSet[Int], count: Int, it's purpose is already quite clear, so the most important piece of information was to say that it is there just to encapsulate recursion.

Lastly, I added explicit return type is the functions that I felt it added clarity. Think of them like training wheels: Just remove them when they feel useless.


Project Euler #5 - Smallest multiple using Factor Table

Truly choose your language

Although a C compiler won't accept the program as a whole (due to the using directive and choice of headers) the actual code here is all really C. I'd make up my mind and either write C in a way that's acceptable to a C compiler, or else write C++ that makes good use of the language. The combination you've used is (IMO) pretty much a pit of despair.

For the remainder of this review, I'm going to go with the tag, and assume you really wanted to write good C++.

Avoid C's variadic I/O functions

Although some parts of the C library are fine, C's variadic I/O functions such as scanf and printf are quite problematic in one respect: they provide essentially no type safety. As shown by dozens (probably hundreds, if you looked carefully) of questions on Stack Overflow, mismatches between the formatting argument and the other arguments frequently cause problems. There are a few cases where you're reading or writing highly formatted data that it might be worth at least considering using these functions anyway, but the I/O format specified here doesn't provide any such justification.

Use the right types

In C++, there's rarely much reason to use a built in array such as your M. You're usually better off with a std::array or std::vector instead.

Likewise, the values we need for inputs up to 40 can exceed the range of a 32-bit number. We probably want to use unsigned long long (or something on the same general order) to support the specified range.

Names

As @NullException hinted at in the comments, most of the variable names in this code border on meaningless. I consider it perfectly acceptable to use a name like i for a subscript in a loop, but for longer-lived things like your M, a more meaningful name would be extremely helpful.

Consider a more recognizable algorithm

When you get down to it, what we're dealing with here is computing the least common multiple (LCM) of some numbers. There's a well-known method of computing the LCM of numbers: LCM(a, b) = a * b / gcd(a, b). This can be extended to three or more numbers quite easily:

LCM(a, b, c) =
    L = lcm(a, b);
    result = L * c / gcd(L,c)

Since this defines the LCM of three numbers in terms of the LCM of two numbers, we can extend it indefinitely.

Define functions where suitable

In this case, our definition of LCM depends on the GCD. Computing the GCD of two inputs is a well-defined operation that should probably be defined as a function.

Consider a greedy algorithm

In this case, we have only 40 possible inputs. We also have an algorithm for computing LCMs, where each result depends on the previous result. It's probably easiest to start by computing the LCM for every possible input from 1 to 40, then read the actual inputs, and just print out the result for each.

Result

Putting those suggestions together, we might get code something like this:

#include <map>
#include <vector>
#include <iostream>

template <class T>
T GCD(T u, T v) {
    while (v != 0) {
        T r = u % v;
        u = v;
        v = r;
    }
    return u;
}

int main() {
    using T = unsigned long long;

    std::vector<T> LCMs{ 1 }; // The LCM of 1 is 1

    // Compute succeeding LCMs based on existing one(s)
    for (T i = 2; i < 40; i++) {
        auto prev = LCMs.back();
        LCMs.push_back(prev * i / GCD(prev, i));
    }

    int test_count;
    std::cin >> test_count;

    for (int n = 0; n < test_count; n++) {
        int input;
        std::cin >> input;

        std::cout << LCMs[input-1] << "\n";
    }
}


1. Bug

If the city contains two identical buildings then skyline raises an exception:

>>> skyline(deque([(1, 2, 3), (1, 2, 3)]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr66776.py", line 97, in skyline
    delete(heapq.heappop(buildings_by_R)[1])
  File "cr66776.py", line 87, in delete
    buildings_by_H[b[1]].remove(b)
KeyError: 2

This is because the code represents buildings by tuples of numbers, and that means that two identical buildings get stored just once in a set, so when you come to remove the second building, it's not there. To fix this, buildings need to be represented such that each building is unique. One way to do this would be to use a Building class, as objects are always unique unless they implement an __eq__ method.

2. Review

It's not clear to the reader how the data is represented. The variable b represents a building, but what are b[0], b[1] and b[2]? These are the building's left x-coordinate, height, and right x-coordinate respectively, so it would make the code a lot easier to read if these were b.left, b.height, and b.right. It's easy to do this using a class, or collections.namedtuple.
It's not clear exactly what the helper functions add_point, insert, delete do. In particular, add_point doesn't always add a point to the skyline list: sometimes it updates the last point in the list. The insert function adds a building to the buildings_by_R and buildings_by_H collections, but also calls add_point. These functions could do with comments explaining what exactly it is that they do.
Some of the operations could do with a comment to explain their purpose. For example here:

h = buildings_by_H.iloc[-1] if buildings_by_H else 0

It would be worth noting that this finds the height of the highest building currently standing.
The insert and delete helper functions are only called once, so there's no particular advantage to making them into functions. The code might be clearer if these functions were inlined at the point of use.
The insert function contains the following lines of code that manipulate the vaguely named sets parameter:

def insert(b, sets=[set()]):
    s = buildings_by_H.setdefault(b[1], sets[0])
    s.add(b)
    if s == sets[0]:
        sets[0] = set()

It looks as if there was a concern that if the code were written in the obvious way:

def insert(b):
    buildings_by_H.setdefault(b[1], set()).add(b)

then a set() object would be created and immediately discarded each time a building was inserted at a position for which buildings_by_H already had an entry. This is a valid concern, but the following would seem to be a clearer way to handle it:

def insert(b):
    try:
        s = buildings_by_H[b[1]]
    except KeyError:
        buildings_by_H[b[1]] = s = set()
    s.add(b)

It's worth making a little effort to avoid using libraries that are not built into Python. Having to install sortedcontainers is a small but genuine barrier to running code (and might partly account for the time this question has languished without being reviewed). In this case, SortedDict is used to maintain the collection of currently standing buildings, such that (i) the height of the highest building can be found via buildings_by_H.iloc[-1]; and (ii) the set of buildings at a given height can by located via buildings_by_H[b[1]] and so a building can be removed.

However, we can implement (i) by storing the buildings in a heap, because as it says in the heapq documentation:

  The interesting property of a heap is that its smallest element is always the root, heap[0].

Python heaps are min-heaps but we want the highest building, so we have to reverse the comparison order on buildings. If buildings are represented by objects, as recommended in §1 above, then this can be done by implementing a __lt__ method on the Building class.

How do we implement (ii)? You can't easily delete elements from a heap. The insight here is that we don't have to delete the building from the heap, we can leave it in the heap but mark it as finished (if buildings are represented by objects, as recommended in §1, above then this can be done by setting an attribute). We only care about the highest standing building, which is at the root of the heap, so we can just check that one to see if it is finished and pop it if so.
There's a lot of complexity in the add_point function. This complexity is due to the fact that when add_point(x) is called, we don't know whether or not we've processed all the buildings that start or end at x, so when we construct a point (x, h) we don't know whether we're done with it, or whether we might have to revise it later.

It would simplify this code considerably if we could be sure that all the buildings that start or end at x have been processed. Then we would know that the point would not need to be revised, and we could just yield it.

3. Revised code

from collections import defaultdict, namedtuple
from heapq import heappop, heappush

class Building:
    def __init__(self, height):
        self.height = height
        self.finished = False

    def __lt__(self, other):
        # Reverse order by height, so that when we store buildings in
        # a heap, the first building is the highest.
        return other.height < self.height

# An event represents the buildings that start and end at a particular
# x-coordinate.
Event = namedtuple('Event', 'start end')

def skyline(buildings):
    """Given an iterable of buildings represented as triples (left, height,
    right), generate the co-ordinates of the skyline.

    >>> list(skyline([(1,9,3), (1,11,5), (2,6,7), (3,13,9), (12,7,16),
    ...               (14,3,25), (19,18,22), (23,13,29), (24,4,28)]))
    ... # doctest: +NORMALIZE_WHITESPACE
    [(1, 11), (3, 13), (9, 0), (12, 7), (16, 3), (19, 18), (22, 3),
     (23, 13), (29, 0)]
    >>> list(skyline([(1, 3, 2), (1, 3, 2)]))
    [(1, 3), (2, 0)]

    """
    # Map from x-coordinate to event.
    events = defaultdict(lambda:Event(start=[], end=[]))
    for left, height, right in buildings:
        b = Building(height)
        events[left].start.append(b)
        events[right].end.append(b)

    standing = []               # Heap of buildings currently standing.
    last_h = 0                  # Last emitted skyline height.

    # Process events in order by x-coordinate.
    for x, event in sorted(events.items()):
        # Update buildings currently standing.
        for b in event.start:
            heappush(standing, b)
        for b in event.end:
            b.finished = True

        # Pop any finished buildings from the top of the heap.
        while standing and standing[0].finished:
            heappop(standing)

        # Top of heap (if any) is the highest standing building, so
        # its height is the current height of the skyline.
        h = standing[0].height if standing else 0

        # Yield co-ordinates if the skyline height has changed.
        if h != last_h:
            yield x, h
            last_h = h

4. Performance comparison

Test case (this is an order of magnitude bigger than the largest case specified in the problem description):

>>> from timeit import timeit
>>> import random
>>> R = lambda n:random.randrange(n) + 1
>>> buildings = sorted((x, R(10000), x + R(1000)) for x in (R(10000) for _ in range(50000)))

Original code:

>>> queue = deque(buildings)
>>> timeit(lambda:skyline(queue), number=1)
1.46421534800902

Revised code:

>>> timeit(lambda:list(skyline(buildings)), number=1)
0.9026356039103121

The revised code is about 40% faster than the original.


An important thing about sorting is that it has to be fast and that it does not fill your entire heap space. That's why quicksort often is prefered before merge sort.

And I think that your code is eating way more memory than it should.

You don't need the recursion in lsdSort, I think it makes it more complex and less efficient. You may get unexpected stackoverflow exceptions as well for long strings.
At each iteration you are creating new instances for everything you need. The char matrix and your list of lists. You may reuse the same copies each iteration if you throw away the recursion.
Don't use List or any implementation of it when you exactly know the size and you aren't interacting with any other methods. (as you probably may know there is an overhead)
List<char[]> currList = idx.get(currVal); followed by a nullcheck seems to make no sense for your code? List<E>.get()

How would I do it:
The best implementation I've seen so far is from a book of Robert Sedgewick.

/**
 * Rearranges the array of W-character strings in ascending order.
 *
 * @param a the array to be sorted
 * @param W the number of characters per string
 */
public static void sort(String[] a, int W) {
    int N = a.length;
    int R = 256;   // extend ASCII alphabet size
    String[] aux = new String[N];

    for (int d = W-1; d >= 0; d--) {
        // sort by key-indexed counting on dth character

        // compute frequency counts
        int[] count = new int[R+1];
        for (int i = 0; i < N; i++)
            count[a[i].charAt(d) + 1]++;

        // compute cumulates
        for (int r = 0; r < R; r++)
            count[r+1] += count[r];

        // move data
        for (int i = 0; i < N; i++)
            aux[count[a[i].charAt(d)]++] = a[i];

        // copy back
        for (int i = 0; i < N; i++)
            a[i] = aux[i];
    }
}

I think your idea with using a list of lists is good. And may looks faster since you are iterating one time less by skipping the cumulated counts. Still, it's clean and simple.

LSD.java


There are a few code issues that tools like flake will pick up on, but I'll just focus on performance.

First up, switching to pypy reduces the runtime on my machine from ~3 minutes to 16 seconds.

⚡ time pypy orig.py
Solution found: x0=89059908, y0=164204369
Next value: 231886864
pypy orig.py  15.79s user 0.07s system 99% cpu 15.915 total

Removing the L gives us another drastic speedup:

⚡ diff orig.py orig2.py
5c5
< P = 295075153L
---
> P = 295075153

⚡ time pypy orig2.py
Solution found: x0=89059908, y0=164204369
Next value: 231886864
pypy orig2.py  3.93s user 0.04s system 99% cpu 3.988 total

Changing the control flow gives us a smaller boost

def solve():
    seq = [210205973, 22795300, 58776750,
           121262470, 264731963, 140842553,
           242590528, 195244728, 86752752]
    P = 295075153
    for x0 in xrange(0, P):
        y0 = seq[0] ^ x0
        x, y = x0, y0
        for i in xrange(1, 9):
            x = (2 * x + 5) % P
            y = (3 * y + 7) % P
            if (x ^ y) != seq[i]:
                break
            if i == 8:
                print "Solution found: x0=%d, y0=%d" % (x0, y0)
                x, y = x0, y0
                for i in xrange(1, 10):
                    x = (2 * x + 5) % P
                    y = (3 * y + 7) % P
                print "Next value: %d" % (x ^ y)
                return
    print "No solution found"

solve()

⚡ time pypy orig3.py
Solution found: x0=89059908, y0=164204369
Next value: 231886864
pypy solve.py  2.60s user 0.03s system 99% cpu 2.633 total

Which gets us very close to the C solution

⚡ time ./a.out
Solution found: x0=89059908, y0=164204369
Next value: 231886864
./a.out  2.36s user 0.01s system 99% cpu 2.369 total

Forgot to compile with optimisations, which puts the Python version ~6x slower than C:

⚡ time ./a.out
Solution found: x0=89059908, y0=164204369
Next value: 231886864
./a.out  0.44s user 0.00s system 99% cpu 0.448 total


looking for OO input , is any of this code good OO or am i doing it all wrong?

A partial answer to the partial question (with no partiality to C#, Java, or quantum mechanics):

The invariants:

Some unnamed caller needs to effectively call:

order.processed(warehouse.calculateAllocation(order.getQuantity()));

where calculateAllocation is private (so, presumably invisible to the caller).

[So, let's imagine the int getQuantity() method in the Order interface.]

The Warehouse implementation depends on AllocationResponse.
The unnamed caller must minimally depend on the existence of Order and Warehouse and needs some way to call calculateAllocation "for an order".

Comparison of the variants:

Option 1 pros:

The unnamed caller has no further dependencies beyond the above minimum.

Option 1 cons:

Warehouse now depends on Order, Order.getQuantity and Order.processed.

Option 2 pros:

Warehouse has no further dependencies.

Option 2 cons:

calculateAllocation is now completely exposed to abusive calling (via allocate) with not so much as an Order in sight. They might as well be one public function. Yet calculateAllocation was likely defined private for good reason -- otherwise:

order.processed(new Warehouse().calculateAllocation(order.getQuantity()));

would have been Option 0.
The unnamed caller now depends on Order.getQuantity, Order.processed, and AllocationResponse.

Note: The dependency on AllocationResponse could be reduced (at least in one sense) at some cost of readability (you judge?) and unique line numbers for breakpoints (typically just where and when you need one) with:

    order.processed(new Warehouse().allocate(order.getQuantity()))

Now, those are just the apparent trade-offs, but they may well be outweighed by how these design options fit in with other present and foreseeable code.

For example,

Option 1 would be more favorable in a wider system that might:

define Warehouse-based classes that specifically refine the behavior of allocate(order),
possibly with no change or a different change to calculateAllocation(int). That is, refining allocate(order) SOLELY indirectly by refining calculateAllocation(int) would be the same deal between Options 1 and 2.
have many different callers of the exact same idiom:

warehouse.allocate(order)

require other exposure to Order, Order.getQuantity and Order.processed in the Warehouse module (helping to justify/amortize the dependency cost).

Option 2 would be more favorable in a wider system that might:

require or desire other exposure to Order.getQuantity and Order.processed, and possibly AllocationResponse in the unnamed caller (to justify/amortize the dependency cost) other than just using the idiom:

order.processed(warehouse.allocate(order.getQuantity()))

Repeated use of this idiom would argue for giving it its own method -- under Option 2, a local method of the unnamed caller, so that would be pretty much the same deal between Options 1 and 2.

In some "binary" sense, the Order interface is already imported by the unnamed caller, so the exposure to the methods is implicitly already there "for free" or more like "for better or worse". Here "binary" has BOTH its meanings of "either on or off" and "down to the compiled bits". This "binary" distinction is important when designing interfaces for libraries intended for public consumption "to be supported forever".  But in a subtler practical sense, for an interface that's only used experimentally or in a small "in house" code base, isolating function calls to a small fraction of even the modules that import the interface can make it considerably less painful to "break the contract" later by evolving those functions. In this sense, calls to each distinct Order method from the unnamed caller is a "deeper" dependency than merely importing the Order interface.

require or desire other exposure to calculateAllocation/allocate(int) outside Warehouse. That seems unlikely.  Otherwise, calculateAllocation would not have been declared private, or it would have been changed to public as a knee-jerk Option 0 solution as soon as this design problem arose, with none the wiser -- now THAT's what I'd call "doing it all wrong".


It could be the case that using Scala.Rx's reactive variables simplify your use case since they propagate change state as they happen. In particular, chaining those smart Var's together might help you simplify the task. Please have a look at:

https://github.com/lihaoyi/scala.rx

There you also find a link to the underlying publication that elaborates on the concept further.


Is this code an efficient implementation of Reservoir Sampling?

Reviving an old, but really interesting post, that did not get a great opportunity for review the first time around....
What you've done well:
This code, for the most part, is excellent. As for your specific questions:
Is this:

efficient
Mostly, yes. The inefficiencies in here are all related to the IO, and the Scanner, not your code. A more low-level API may net you some performance benefits, but not likely. You are also (re)using the Random class well, and there should not be a problem there.

actually reservoir sampling (with equal odds of any line being drawn)?
Yes. This is a good implementation of the reservoir algorithm. The random arguments are good, and the substitutions should be fine.

What's concerning

The most significant beef is that you do not close the Scanner. Scanners can hold on to open file-handles, and, if the file really is big, this may have system-wide consequences. A try-catch-finally block would be appropriate (or, a try-with-resources if you're on Java7 now).

A second (smaller) issue is that reservoir sampling is designed to handle huge data in a streaming way. I know it is perhaps unrealistic to consider in your use-case, but multi-gigabyte files are not unexpected, and the likelihood of overflowing the count variable is not unrealistic. That would cause problems....

You should consider converting count and randomNumber to be long values, and only convert it back to an int if it is less-than reservoirSize

Finally....
Nice code to review. Thanks. Obviously, the new language features in more recent Java versions may be interesting to consider....


Is this the right way to work with callbacks and the EventEmitter?

Interesting question,

I am assuming you know that usually, in essence, the setting of the name would be written like this:

Player.setName('somename' , function( err, result ) {
  console.log('Name changed');
});

and in essence setName would be

Player.prototype.setName = function( name, callbackFunction ) {

    var self = this;

    connection.query("UPDATE players SET ? WHERE ?", [
        { name: name },
        { id: self.id }
    ], function (err, result) {

        if (result) {
            process.nextTick(function () {
                self.name = name;
                console.log("Successfully updated name of player no. " + self.id);
                callbackFunction( false, true );
            });
        } else {
            process.nextTicket(function () {
                console.log("Trouble with the mysql while changing player name: " + err);
                callbackFunction( err, false );
            });
        }
    });
};

I like that with your approach you avoid "callback hell". Since your project is a small game  I would advise you to see how far you can go with this scheme.

Other than that, I hope you are not planning to write a whole function including SQL code for each property. In my mind you should only have 1 function that takes care of updating the whole of the player object.

Finally, easy up on the new lines, it makes your code too hard to read.


1. Bugs

You have two locks, one protecting state, and the other protecting timeRemaining. But these locks operate independently. That means that when you update both of these properties:

self.state = self.timeup
self.timeRemaining = 0

it would be possible for another thread to run in between these two statements and see state == timeup but timeRemaining != 0. You need one lock to protect both properties, so that they are updated atomically. See below for some race conditions that are consequences of this bug.
The timeRemaining property updates the _timeRemaining value by subtracting the elapsed time. But this means that if you keep requesting the timeRemaining property, it will keep subtracting the elapsed time, giving you nonsense like this:

>>> t = KitchenTimer()
>>> t.start(5)
>>> t.timeRemaining
3.2
>>> t.timeRemaining
0.6
>>> t.timeRemaining
-2.6
>>> t.timeRemaining
-6.6
>>> t.timeRemaining
-11.3
>>> t.timeRemaining
0.0

There's a race condition between the start method and the whenTimeup method. In start you have:

if self.isRunning():                  # 1
    raise AlreadyRunningError
else:
    self.state = self.running         # 2
    self.timeRemaining = duration     # 3

and in _whenTimeUp you have:

self.state = self.timeup              # 4
self.timeRemaining = 0                # 5

A possible order of execution is 4–1–2–3–5 which would set state to running and timeRemaining to 0.
There's a race condition between the stop method and the _whenTimeup method. In stop you have:

if self.isRunning():                  # 1
    self._timer.cancel()              # 2
    self.state = self.stopped         # 3

and in _whenTimeUp you have:

self.state = self.timeup              # 4

A possible order of execution is 1–4–2–3 which would leave state as stopped when it ought to be timeup.

(There may well be more race conditions; I haven't looked very hard.)

2. Comments on your code

Why "Kitchen" timer? The class doesn't seem to have anything to do with kitchens.
There doesn't seem to be any documentation for the methods.
Why does the timeRemaining method round the result to one decimal place? There doesn't seem to be any explanation of this. It would be more natural to return the actual time remaining.
Why do you rename threading.Timer as TTimer? The name Timer doesn't seem to conflict with anything in your code.
The Python style guide (PEP8) recommends using lowercase_with_underscores for method and property names. You're not obliged to follow this guide, but it will make it easier for you to collaborate with other Python programmers.
The intended use of private names in Python is to "avoid name clashes of names with names defined by subclasses" but that's not necessary here. So write _state_lock instead of __stateLock and so on.
The _now method seems a bit pointless:

def _now(self):
    return time()

Why not just call time()?


Removing the ORDER BY worked wonders and slightly altering the code:

,SUBSTRING(STUFF((SELECT ', '+TEAM FROM @TEAMMEMBER WHERE E.OID = CAREPROVIDEROID FOR XML PATH('')),1,1,''),2,4000) AS TEAMS


Alternative for storing id in hidden input

I would question the premise.

  But with this, just a change to the id may affect other pending comment, or those that are already approved.

I don't see a problem here.

Given the admin is allowed to approve any comment, and nobody else is authorized to access this page completely, I don't see how it's even a problem.

To put it bluntly, nobody in the world is using such a clumsy approach as it's either useless or has a completely different solution (to ensure that a user cannot access other users' records there should be an ACL system in the database, not some HTML/Session ratatouille).


Longest Increasing Path in a Matrix from leetcode

Overall, this is quite clean code. Your use of closures works quite well to hide implementation details.
The most obvious thing to change is to remove the class. In python things don't have to be in a class, and nothing is made better here by using one.

Here are some small other improvements
This version of check_boundary is smaller, and faster, and arguably cleaner.

def check_boundary(matrix, point):
    return 0 < point[0] < len(matrix) and 0 < point[1] < len(matrix[0])

dfs should use keyword arguments so you don't have to pass in initial conditions.

def dfs(current, matrix, visited=set(), memory={}):

This will simplify the end of your main method to

if not matrix:
    return 0
maximum = 0
for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        maximum = max(maximum, dfs((i, j), matrix))
return maximum + 1

This line for direction in [[-1, 0], [1, 0], [0, -1], [0, 1]]: should have Directions factored out, and it should probably be a tuple of tuples instead of a list of lists, for a minor performance boost.
Other than that, this looks good.


The quickest fix you can make to improve speed is removing all of the Select statements, and instead just referencing those selected ranges with variables. (Select slows down any VBA code significantly).  You can also toggle Application.ScreenUpdating to False before the code and True after to gain run-time speed.


Converting Celsius and Fahrenheit in C++

You might as well break the habit of using using namespace std. It involves a little more additional code, but it'll be helpful in the future, especially when using header files.
You don't need those global variables outside of main(). You should really avoid global variables unless absolutely necessary since they can be changed from any scope and you may not even know it. Just put those two variables inside if main() before their use.
farenheit is spelled incorrectly; it should be fahrenheit.
What if the user uses an uppercase 'C' or 'F' instead? You should account for those as well:

case 'c':
     'C': {

case 'f':
     'F': {

It may be more readable to multiply by both 9.0/5.0 and 5.0/9.0 respectively instead of 1.8 since that's most common with these conversion formulas. Make sure not to use integers for this, otherwise the division will truncate towards 0 (in this case, you'll end up with 1 instead of 1.8 and 0 instead of 0.555556).
You may find it better to use double instead of float in most cases and because the former has more precision.
For the next step up, I would recommend adding additional functions since main() shouldn't have to do all of the work.

You can simply acquire value from main(), pass it to the applicable function, then return the result and display it. It'll also allow you to avoid duplicating code in the switch, such as having multiple inputs for value, which is very nice and will be essential in every other program you create. I'll let you come up with that yourself.
If you want to make your program more useful, you can also add Kelvins.
You should probably put that tagline cout in a comment instead, otherwise it may be annoying to see it come up each time when only a result is expected to be printed.
You don't really need return 0 at the end of main() since success is already guaranteed at that point, though it won't hurt anything either.


Sorting an array of jobs by various criteria

First, it may make sense to make sure that the field you're checking in $sort, is the same as the propertyname of the object in $jobs_list.

Also, it looks like there's a lot of identical sort functions; the only difference being that the property you're checking is different.

You could just combine the switch statements that have an identical sorting strategy (revenue, status, profit, margin, etc..) and turn the field into a variable, such as:

switch ($sort) {
    case 'number':
    case 'status':
    case 'profit':
    case 'margin':
        usort($jobs_list, function($a, $b) use ($sort) {
            return ( (float) $a->$sort > (float) $b->$sort );
        });
        break;

}


A recursive program that attempts to solve an extremely large number

Your function is extremely slow because it does a lot of redundant calculations.

$$
\begin{align}
G(5) =& (G(4) + G(3))^{2} \\
     =& (G(4) + G(3)) \cdot (G(4) + G(3)) \\
     =& ((G(3) + G(2))^{2} + (G(2) + G(1))^{2})) \cdot ((G(3) + G(2))^{2} + (G(2) + G(1))^{2})) \\
     =& ((G(3) + G(2)) \cdot (G(3) + G(2)) + (G(2) + G(1)) \cdot (G(2) + G(1)))) \cdot ((G(3) + G(2)) \cdot (G(3) + G(2)) + (G(2) + G(1)) \cdot (G(2) + G(1))))) \\
     =& \ldots
\end{align}
$$

The complexity is \$O(4^x)\$: to calculate \$G(x)\$, you're breaking it into four problems of approximately the same size.

To start with, it would be smarter to square a number without having to compute the base again.

$$
\begin{align}
G(5) =& (G(4) + G(3))^{2} \\
     =& ((G(3) + G(2))^{2} + (G(2) + G(1))^{2}))^{2} \\
     =& \ldots
\end{align}
$$

Then you would be down to "just" \$O(2^x)\$, which is still horrible.

The trick is to notice that you're going to be computing \$G(2)\$, \$G(3)\$, etc. many many times.  What you want to do is memoization — caching previously computed results.  With memoization, you should be able to compute \$G(x)\$ in \$O(x)\$ time.

Once you solve the efficiency issue above, you will still run into a problem with stack overflow for large \$x\$.  To avoid stack overflow, you'll want to reimplement the functions using an iterative loop rather than recursion.


Why is this code so much faster (relatively) in IE7?

The short answer:
In your code the arr.length is the major bottleneck. Simply because of the differences between the various implementations of JavaScript. Not only the implementations differ, but also what the engines actually do prior to executing your code.
Why do I think this: simple:

for([[expr evaluated at start of loop]];
    [[expr re-evaluated on each iteration + 1(end of loop)]];
    [[expr evaluated for each iteration +1(end of loop)]]
)

The cases that are fastest on IE7 are those where the conditional expression in the for-loop is either missing or is simply comparing the values of 2 variables.

The long answer, without focussing on arr.length, but keep in mind that here, you're getting a property of an object, that is, sort-of, inherited from the prototype.

The reason why is simply because of how Chrome's V8 compiles the code, and how the Object[[GetProperty]] is implemented. Since JS arrays are just augmented objects (Array instanceof Object is true), getting a value from an array is, essentially the same as someObj.someProp.
Most JS implementations use either a HashMap or HashTable for the objects. Chrome's V8 engine, is a bit of an odd one out, in a couple of crucial ways.

FF's SpiderMonkey/*Monkey engines compile JS code to intermediate byte-code, that runs on a virtual machine.
Their Rhino engine compiles JS to Java, which is also a VM environment. Cf the hybrid model in the img below
JS "engines" of old didn't even go that far, they were just parse-and-execute things. They did no or very little optimization or reflection on the code they were asked to parse.
V8 does things a bit different: it parses, optimizes and compiles the resulting AST (Abstract Syntax Tree) straight into machine-executable code. No byte-code virtual-machine stuff to hold you back:

So, Chrome's V8 compiles to machine code, which cuts down overall execution time (in most cases). In addition to that, the V8 engine does not use a HashTable for object properties. It creates classes:

  To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes.

What does this mean for arr.length:

//V8:
arr = [];//creates class, that has length property, value 0
arr.push(123);//arr points to class with property 0 = 123, length = 1

That means that, arr.length or arr[0] both are simple, atomic operations. In terms of time-complexity, they are as close as makes no difference both: O(1). Now, I'm not familiar with the internals of IE's JScript engine, but I'm prepared to take a punt on how arr.length works:

arr.length;//->arr @instancelevel->search(length)
             //
             ==>arr.prototype->search(length)
                 //
                 ==> magic property, probably does something like:
                     return max(@instance.keys) +1

Now, this may range anywhere from pretty accurate to down-right absurd, but the principle stands: getting the length property from an array on engines that don't create classes for instances, is not atomic, and therefore slower.
Sadly, because of MS's software being closed source, I can't tell you what kind of AST the parser churns out, nor what the engine then does with that AST. You'll have to get friendly with someone working in Redmond, or send a very polite email, requesting more info (don't expect an answer, though :-P).

So, V8 compiles the AST directly to machine-executable code, and creates classes to speedup property. In theory, accessing a property in JS, running on V8 should be almost as fast as C++ code. In theory, that is :P.
Internet Explorer's JScript engine, especially IE7, is quite dated. It doesn't do optimization very well. It doesn't compile JS as well as modern day engines do.

I can't find the resource ATM, but I also seem to remember that IE's JScript implementation of objects was, in fact, rather lacking, too. I seem to recall it didn't even use a full-blown HashTable for its objects, which would explain why someArray.length takes ages (since it requires a prototype lookup).

Read more here.