Find minimum XOR values in a given array

The program is running in quadratic time. As usual, to improve performance you need to change the algorithm.

Sort the numbers into 32 buckets, according to where the most significant bit of the number is. Convince yourself that if a bucket contains more than one number, it makes no sense to test them against the numbers from other buckets (the result is guaranteed to not be minimal). A cross-bucket xor should be tested only if two adjacent buckets contain just one number each.

Work recursively with each bucket.


Replace keys in values with key->values from same dictionary

Well what you want there is evaluating expressions while keeping track
of dependencies, so you should definitely not implement it via regular
expressions and hoping that running it ten times is enough.

The best way in Python would probably be using the
ast module to parse and
figure out the referenced variables, then calculate dependencies and
evaluate the parsed expressions via
compile
and eval
while passing in the referenced variables in the local parameter.

That way you make sure that the expressions are actually valid, you can
use Python expressions and you can (and should) also detect cycles in
the specification.

Below is a sketch how to do that, not saying that is the best code,
please edit or comment with improvements, I couldn't find a good example
while searching.

import ast, _ast

params = {
    'ad': '2*dmcg/factor*(xw/factor)',
    'dmcg': 2.05e-07,
    'dxwn_3vna': 10.0,
    'factor': 1,
    'xw': '0+dxwn_3vna',
    'foo': 'bar',
    'bar': 'foo'
}

parsed = {}

for key, value in params.iteritems():
    parsed[key] = value

    if type(value) in (str, unicode):
        parsed[key] = ast.parse(value, mode="eval")

evaluated = {key: value for key, value in parsed.iteritems()}

So at this point the evaluated dictionary is mostly a copy of the
params, except that expressions have been parsed.

def referenced(code):
    return [node.id for node in ast.walk(code) if "id" in node._fields]

referenced returns a list with the names of referenced variables in
the expression.

evaluating = []

def resolve(key, value):
    if key in evaluating:
        raise Exception("Loop while evaluating {}".format(key))

    if type(value) is not _ast.Expression:
        evaluated[key] = value
        return value

    evaluating.append(key)

    locals = {name: resolve(name, evaluated[name]) for name in referenced(value)}

    result = eval(compile(value, "<unknown>", "eval"), globals(), locals)

    evaluated[key] = result

    evaluating.pop()

    return result

resolve evaluates the expression recursively but also keeps track of
the stack (in evaluating), so it can detect cycles by looking up the
current variable.  It also assigns the results immediately, so in
further invocations it will return early (the not _ast.Expression
case).

for key, value in parsed.iteritems():
    try:
        resolve(key, value)
    except Exception as exception:
        print ("Error while evaluating {}: {}".format(key, exception))

print(evaluated)

Lastly, iterate over all entries and try to evaluate them.


Strategy pattern instances based on enums

Another way to do the instance creation would be to give each type a constructor reference for the strategy it corresponds to.

enum DataPresenterStrategyType {
    DISTANCE(DistanceStrategy::new), POWER(PowerStrategy::new);
    private final Supplier<DataPresenterStrategy> constructor;

    DataPresenterStrategyType(Supplier<DataPresenterStrategy> constructor){
        this.constructor = constructor;
    }

    DataPresenterStrategy newStrategy() {
        return constructor.get();
    }
}

The main advantages I see for this way are the compile time safety that each type has a Supplier and that you don't need to look for all the switch statements in your project to add cases if you add a new strategy type.

If not all of the constructors of your strategies take the same arguments you can replace the constructor reference with a lambda.

If you don't have access to Java 8, you can accomplish the same thing more verbosely with an anonymous class instead of the constructor reference, or you could make newStrategy() an abstract method and implement it in each type.


You can use a list comprehension to avoid verbosity:

        items = []
        for value in obj:
            if isinstance(value, dict) or isinstance(value, list):
                items.append(comp_sort(value, sort_order))
            else:
                items.append(value)
        return items

Becomes:

is_dict_or_list = isinstance(value, dict) or isinstance(value, list)
return [comp_sort(value, sort_order) if is_dict_or_list else value
               for value in obj ]

Remember to specify:

except ExpectedError:

And not

except:

The latter will swallow anything and harden debugging.


Create array of date pairs for next 10 days

Rather that continuing to append to arrive, just use the n offset from 'today'.

You can also use call strftime from a datetime object directly, like so:

def getNextTenDays():
    dates = []
    today = datetime.datetime.now()
    for n in range(1, 11):
        arrive = today + datetime.timedelta(days=n)
        next_day = today + datetime.timedelta(days=n+1)
        arrive_s = arrive.strftime('%m/%d/%Y')
        next_day_s = next_day.strftime('%m/%d/%Y')
        dates.append({'arrive': arrive_s, 'depart': next_day_s})
    return dates

If you are just going to return the strings, and throw away the actual date times you can do that in one go like so:

def getNextTenDays():
    dates = []
    today = datetime.datetime.now()
    for n in range(1, 11):
        dates.append({
            'arrive': (today + datetime.timedelta(days=n)).strftime('%m/%d/%Y'),
            'depart': (today + datetime.timedelta(days=n+1)).strftime('%m/%d/%Y'),
        })
    return dates

For here its a simple step to making it a list comprehension:

def getNextTenDays():
    today = datetime.datetime.now()
    return [
        {
            'arrive': (today + datetime.timedelta(days=n)).strftime('%m/%d/%Y'),
            'depart': (today + datetime.timedelta(days=n+1)).strftime('%m/%d/%Y'),
        }
        for n in range(1,11)
    ]


Bug

There's a bug in delMax:

const mx = this.queue[1];
this.queue[1] = this.queue.pop();
if (!this.isEmpty()) {
    this.sink(1);
}
return mx;

What will happen when the heap has 1 element? The code will:

Replace the first element with itself (the last element)
It doesn't become empty

In other words, the last element cannot be deleted.

Avoid hacky solutions

This code happens to work, but it's hacky:

while ( 2*k <= this.n() ) {
    const c1 = 2*k;
    const c2 = 2*k + 1;
    const j = this.more(c1,c2)?c2:c1;

What's wrong with it? When 2*k == this.n(), then c2 will point past the end of the queue, and more will compare queue[c1] with undefined, and always return false. The code works, but it would be better to not rely on numeric comparisons with undefined.

Look for generalization opportunities

It's a good idea to use a function to decide the ordering of elements, similar to what you did with less and more. This could open the opportunity to make the implementation work with arbitrary ordering.

The current implementation doesn't make it easy to pass in these functions to customize the behavior. It would be good to make that possible. And it would be even better to make it work with a single function, let's say less.

If you do that, then you should rename some methods, since max and delMax won't make sense for a min-heap ordering. You could rename these to peek and pop.

Hide implementation details

The class exposes many methods that are unnecessary for users:
swim, sink, less, more, exch, flr.
These are implementation details, and it would be best to hide them.

Drop the unnecessary trick

This trick:

/**
 * We initialize index 0 because, calculations for finding
 * children of a node and the parent of a node is easier
 * parent = [ k/2 ], children: [ k*2, k*2+1 ]
 */

Looks completely unnecessary... I don't see a reason whatsoever why the dummy first element helps. You can eliminate it, and the implementation will be simpler and clearer.

Dividing by 2

I'm not sure if this is recommended in JavaScript world,
but instead of Math.floor(x / 2),
x >> 1 feels cleaner.

Naming

Some method names could be improved:

exch -> swap
n -> size
insert -> add
flr -> floor, or instead of always calling it with flr(k / 2) you could name it childIndex and call it with k, letting it do the necessary math
flr uses parameter i. The name i is best in simple counting loops.


'Countdown' Numbers round - combine numbers arithmetically to reach a target

I have slightly simplified the generate function by merging the pairTwo function into the resulting seq computation expression. I refrained from merging the getExpressions function, as its functionality is distinct enough to warrant a separate function IMO.

let generate exprs =
    // for two given expressions, get possible combinations
    let getExpressions x y =
        let isDivisible x y =
            let denom = eval y
            denom <> 0 && eval x % denom = 0

        let a,b = if x > y then x,y else y,x
        seq {
            yield Multiply (x, y)
            yield Add (x, y)
            yield Subtract(a, b) // don't bother with negatives
            if isDivisible a b
                then yield Divide(a, b)
            yield x // yielding each partial result prevents near-misses getting lost
            yield y // although expands the search tree
        }

    let indexed = List.mapi (fun i x -> i,x) exprs

    seq {
        for (i,x) in indexed do
        for (j,y) in indexed do
        if j > i then
            for expr in getExpressions x y do
            yield expr :: [ for (k,z) in indexed do if k <> i && k <> j then yield z ] }

I would still very much appreciate any and all critique!


Your friend is right, and there's ways to parameterize the code to make it more useful. Consider three things:

Don't print each character - build a block of text up, and print the block (note that adding a newline to the string \n works as well as a System.out.println())
You can input the text to repeat as a parameter to the function...
It is common practice to have loops from 0 to 1-less-than-the-limit like for (int i = 0; i < limit; i++) {....} and not from 1 to the limit for (int i = 1; i <= limit; i++) {...}. Your loop is not wrong.... but it is unconventional.

So, take your function:

public static void printLine(int length)
{
    for (int i = 1; i <= length; i++)
    {
        System.out.print("*");
    }
    System.out.println();
}

And apply the three concepts above... and we get:

public static String repeatText(String text, int count) {
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < count; i++) {
        output.append(text);
    }
    return output.toString();
}

Now, that function can be used as the basis for a bunch of things....

your top-and-bottom lines of the box.
the inside-content of the other lines of the box
the repeating rows inside the box

Consider your printBox function:

public static void printBox(int length, int height)
{
    printLine(length);

    for (int i = 1; i <= height - 2; i++)
    {
    System.out.print("*");
        for (int j = 1; j <= length - 2; j++)
        {
            System.out.print(" ");
        }
        System.out.println("*");
    }
    printLine(length);
}

Let's use the same 3 principles I listed earlier, but let's also use the new repeatText function....

public static String buildBox(int length, int height)  {
    String topAndBottom = repeatText("*", length) + "\n";
    String middle = "*" + repeatText(" ", length - 2) + "*\n";
    String box = topAndBottom + repeatText(middle, height - 2) + topAndBottom;
    return box;
}

Now, you can print that box just once with:

System.out.print(buildBox(length, height));

There are still issues, like what happens if the length or height are less than 2? That would be a problem. Consider ways to avoid that, or handle that.


Python file reader/writer, with processing pipeline and context manager

This code looks very nice! I admire how clean and organized your code is. It appears that you tried to think through how to arrange it, and I really appreciate that.

There are really only a few areas that I see things could be improved: the speed of execution, the robustness of the code when a user attempts to supply invalid data, and the verbiage for readability when others must see this code.

Efficiency

I had to look it up, but I remember reading about how reducing all of your code that follows if __name__ == '__main__': into a single main() function is good practice. After searching around I remember where I read it, it was in the Python Cookbook (3rd edition) by O'Reilly Media. The authors David Beazley and Brian K. Jones wrote:

  A little-known fact is that code defined in the global scope like this runs slower than code defined in a function. The speed difference has to do with the implementation of local versus global variables (operations involving locals are faster) ... The speed difference depends heavily on the processing being performed, but in our experience, speedups of 15-30% are not uncommon

Robustness

I can see in a couple places where someone using this code may (whether accidentally or with malicious intent) break it and cause an error, or perhaps not cause an error but make it do something not designed. You may want to consider adding checks throughout your code, so that if say a value in a dict is of a type other than a string, then you know something is wrong and you shouldn't continue with the swap function. I realize adding Exception handling throughout or if/then branches will make for less clean and readable syntax, but it is an area where you may need to take this next if you plan to put this into a production environment.

Readability

Think about how this code will look if someone else has to get up in the middle of the night when something breaks, and half conscious and under duress, go through and figure out where a problem might be. (I think my friend and QA Guru Jon Gluck called it "Drunk Proofing" your code, so even the intoxicated who get a late night emergency call can fix the problem.)

As an example, consider the word "processing." This is a general enough word that you could use it almost anywhere in your code, and across multiple classes and functions even though different uses of this word may be completely unrelated. It reminds me of "college speak" for the word "do." Imagine replacing the word "process" (including "processing" and "processor" and "deprocessor" with the words "doing", "doer" and "undoer", respectively). I don't have a suggestion for what to replace the word process with, and maybe it truly is the best and only word to use here (just as 'handler' is often the best word to use in many cases), but just be careful. Be especially careful if you have used these same terms in other parts of your code that could cause significantly more confusion if someone attempts to wade through a stack trace to troubleshoot an error.

Caveat

Please understand that I think your code is quite beautiful, and frankly I'm not sure my code would look this good if I were tasked with the same project. Regardless, since you posted in code review asking for suggestions, I am trying to poke some holes in it, and make suggestions of where to go from here.

Great job, and keep it up!


Well for starters with

[self.addNSFWPoster(post) for sub in self.content for post in sub]

you are constructing a list of

[None, None, ... , None]

with a length equal to

len(self.content) * len(sub)

that you are immediately throwing away because you aren't assigning it to a variable. In other words you should only use a list comprehension for building a list, not for calling a method that is doing work elsewhere.

An alternative implementation is as you might expect a nested for loop:

for sub in self.content:
    for post in sub:
        self.addNSFWPoster(post)

To speed this up further you could reduce your function call overhead with the following:

for sub in self.content:
    for post in sub:
        print 'Parsing author and adding to posters.'
        self.nsfw_posters.add(str(post.author))


stability of an exponential moving average

How about initializing the compensation factor so that it doesn't have to do the convergence from an undefined state?

UltrasonicRecorder(int referenceValue, Input referenceInput) :
    _referenceValue(referenceValue),
    _referenceInput(referenceInput)
{
    _compensation = 1.0; // This!
}

Edit: Your EWMA is correct. Your woes of compounding errors are unfounded. As you always "move towards" the measurement value, any compounding errors will be limited. In fact the compound error will at any point in time be less than:

(sum{i=0,infty} (1-delta)^i)*ULP(ANALOG_VALUE_RANGE) ~ 2^-(52-12) / delta ~ 10^-6


I don't like the name - it ought to be more explicit that it's an input-only range.

Otherwise, it looks just as a range should, with the observation that we omit the usual const iterators, as they don't make sense here.

I think you can avoid repetition of the return type:

std::istream_iterator<T> begin()    {return {stream};}
std::istream_iterator<T> end()      {return {};}


Changes all floats in a pandas DataFrame to string

Since you're already calling .apply, I'd stick with that approach to iteration rather than mix that with a list comprehension.
It's generally better to avoid making data modifications in-place within a function unless explicitly asked to (via an argument, like inplace=False that you'll see in many Pandas methods) or if it's made clear by the functions name and/or docstring.
The logic is reasonably complex, so it might be clearer as a named function.
The leading _ in the function name is usually reserved for "private" functions, whereas this seems to be a general utility function. It's fine if you don't want external code to touch it, that's just not clear from this code snippet.

Here's one way you might re-write the function to follow these tips:

def format_floats(df):
    """Replaces all float columns with string columns formatted to 6 decimal places"""
    def format_column(col):
        if col.dtype != float:
            return col
        return col.apply("{:.6f}".format)

    return df.apply(format_column)

And a usage example:

In [1]: format_floats(pd.DataFrame([{'a': 1, 'b': 2.3}, {'a': 2, 'b': 3.0}]))
Out[1]:
   a         b
0  1  2.300000
1  2  3.000000


Stack based non-recursive Fibonacci - Go implementation

I'm not convinced that the mechanism of using a stack is a good one. Why did you choose that data structure? In Go, a slice would be a much more appropriate structure, and also probably a lot more memory efficient. What you are looking for is a 2-element queue, not a 2-member stack.

The need for you to pop() term1 and then push it back again, is an indication that the stack is the wrong structure.

Consider a much simpler Fibonacci method, that does essentially the same logic as your method, but .... simpler.

func Fibonacci(n int) int {
    // seed the sequence with the next 2 numbers in the sequence
    fib := []int{0, 1}

    // advance the future 2 sequences as necessary.
    for i := 0; i < n; i++ {
        current := fib[0]
        next := fib[1]
        // remove the first member
        fib = fib[1:]
        // add the next member
        fib = append(fib, current+next)
    }

    return fib[0]
}

This uses a Go slice as a queue, shifting the value from the front of the queue, and adding another value to the end of the queue.

A trick is computing the two values "ahead" instead of the two values "before" the "current" item. This allows you to have simpler logic for the first and second results (but at the expense of calculating a single value you will never use).

See this running in the playground


Sorting dictionary according to letter patterns

This can be improved and shortened by naming the concepts you are using:

A function called encodeWord that takes a single word and returns its encoded value
A function called groupedByCodes which takes an array of words, and returns the object you are seeking: codes as keys, and arrays of words that get encoded to those keys.

This will have the following benefits:

What your code is doing will be crystal clear.
You'll have less code
Most of your temporary variables will vanish

I've also purposefully left out the writing and reading of the files, as that's really a separate concern from your main program.

Rewriting it this way, you'll get something that looks like this:

var sampleFile = "CAT\nDOG\nTOM\nBOB\nTOT",
    words = sampleFile.split("\n");

console.log(groupedByCodes(words));
// { ABC: [ 'CAT', 'DOG', 'TOM' ], ABA: [ 'BOB', 'TOT' ] }

function groupedByCodes(words) {
  return words.reduce(function(dict, word) {
    var code = encodeWord(word);
    if (!dict[code]) dict[code] = [];
    dict[code].push(word);
    return dict;
  }, {});
}

function encodeWord(word) {
  var encodingDict = {}, nextCode = 65; //'A'
  return word.split('').map(encodeLetter).join('');

  function encodeLetter(l) {
    return encodingDict[l] || (encodingDict[l] = String.fromCharCode(nextCode++));
  }
}


Dividing valuable items so that two persons get the most similar value possible

partitions

This is inefficient since
once you have one person's items you know what the other person's items are - just take the complement.

Also - does this condition really work if two items have the same value?

   if set(a).union(set(b)) == set(items) and\
        not set(a).intersection(set(b)))

For instance, what if the values of the items are [3,3,3,3]?

This suggests that you should partition the item ids - not the item values.

Here is an example of what I'm getting at:

def evenly_divide(vals):
  ids = range(len(vals))
  total = sum(vals)
  half = total / 2

  bestSum = 0
  bestIds = []
  for a in all_subsets(ids):
    s = sum( vals[i] for i in a )
    if 2*s <= total and s > bestSum:
        bestSum = s
        bestIds = a
        if 2*s == total: break -- no need to continue
  return (bestSum, bestIds) # returns items for one person

This is still very inefficient, but it's more direct and concise.


Wrapper to mount partition before launching executable

[ $? -ne 0 ] is a well-known over-complication - you can replace that with a simple || in the pipeline:
DETAILS=`SUDO_ASKPASS="$(which ssh-askpass)" sudo --askpass mount "$DEVICE" "$PARTITION" 2>&1` \
    || return $?

And in fact we can have a whole chain here:
launch() {
    findmnt "$PARTITION" \
        || DETAILS=`SUDO_ASKPASS="$(which ssh-askpass)" sudo --askpass mount "$DEVICE" "$PARTITION" 2>&1` \
        || return $?
    notify-send "Launching.."
    exec "$EXECUTABLE"
}

If you have chronic installed, that could replace the tedious saving of output into DETAILS:
NAME
       chronic - runs a command quietly unless it fails

SYNOPSIS
       chronic [-ev] COMMAND...

DESCRIPTION
       chronic runs a command, and arranges for its standard out and standard
       error to only be displayed if the command fails (exits nonzero or
       crashes).  If the command succeeds, any extraneous output will be
       hidden.

So,
launch() {
    findmnt "$PARTITION" \
        || SUDO_ASKPASS="$(which ssh-askpass)" \
           chronic sudo --askpass mount "$DEVICE" "$PARTITION" \
        || return $?
    notify-send "Launching.."
    exec "$EXECUTABLE"
}


It produces the right answer in this particular case, but it wouldn't produce the right answer for all inputs. Consider a=4. The first time you hit the while guard, x is 2 and a/x is 2, so it skips the loop and prints 4.

Is there any reason for using an op= construct for x+=1 but not for a=a/x?

I'm not a Pythonista, but I'm pretty sure it's preferred style to put the if and else blocks on a new line even if they're only one line long:

    if a%x==0:
        a/=x
    else:
        x+=1


There's one style issue I want to address, and then I'll talk bigger picture.

This comment may turn irrelevant in this specific case, because bigger picture, the better option is probably going to be to use NSTimer, and I'll go over some samples of how to use that, but this comment is still useful for other scenarios, so here it goes:

-(void) update {
    switch (self.state) {
        case CountdownNotStarted:
            break;
        case CountdownCounting:
            [self doCountdown];
            break;
        case CountdownPaused:
            break;
        case CountdownFinished:
            break;
        default:
            break;
    }
}

We have 4 possible conditions (not including default:), but only 2 possible results.  What you're doing here is on par with something like this:

NSUInteger foo;
// stuff

switch (foo) {
    case 0: break;
    case 1: [self doCountdown];
    case 2: break;
    case 3: break;
    case 4: break;
    // etc ad naseum
    case NSUIntegerMax: break;
    default: break;
}

Listing EVERY possible value for an NSUInteger in a switch statement in which we only care about 1 (or even a couple) value seems absurd, right?  It's no less absurd to do this for an NS_ENUM.

After all, your NS_ENUM is actually backed by some sort of primitive data type.  And in this case we have only 4 different values, but it doesn't mean there can't be more.  For my current project at work, one of my enums already has 100+ defined values, and will easily have hundreds more by the time the project is done, yet most of the time when I switch on variables of this type, I only care about one specific value, sometimes two or three more.

There are three possible options on how to rewrite this into something better.

A simple if-else.  If the specific scenario means it's extraordinarily unlikely that we'll only ever care whether or not the variable matches this one specific variable, and we don't need an if-else if-else or anything more complex than a simple if-else, then we're fine to just use an if-else:

if (self.state == CountdownCounting) {
    [self doCountdown];
}

And in this specific case, we don't even need the else.

Let conditions with that should execute the same block of code simply fallthrough:

switch(self.state) {
    case CountdownCounting:
        [self doCountdown];
        break;
    case CountdownNotStarted:
    case CountdownPaused:
    case CountdownFinished:
    default:
        break;
}

This one explicitly lists each condition, and this is fine if the enum is well defined, small, and unlikely to contain more than a handful of values.  However, this specific syntax will not work with swift switch statement.  You'd have to add the fallthrough keyword to each of those empty cases to achieve the exact same code, and at that point, we're not any better than the original situation of just break-ing from each.  Since iOS development will likely move quickly to swift, I'd recommend against getting into the habit of this sort of switch structure if you're not already in it.

Let default: handle the default cases.  Any case for which the code you want to be executed matches exactly to the code in default: can simply be omitted.

switch (self.state) {
    case CountdownCounting:
        [self doCountdown];
    default:
        break;
}

Now this is the same logic as the if-else above.  It makes it more clear that we only care about this specific case.  However, compared to the if-else above, this is easier to add other values and scenarios.  And this structure will work perfectly fine exactly as-is barring syntax discrepancies if/when you make the transition to swift.  This is absolutely the style I would recommend, although all three options are better than what you currently have I believe.

Now then, as I mentioned before (and as you mentioned in the question), NSTimer is probably the answer here.

You said you'd heard of it, but not messed with it yet.  NSTimer is no different from any of the other Apple classes.  It may seem a little confusing or overwhelming at first, but the documentation is great, and it really only takes using it for yourself once or twice to get pretty settled in and comfortable with how the class works, so here's a few pointers on NSTimer.

There are 5 methods for creating a timer.  Of these 5, I personally only ever use 1 of them.  One of the methods is an init method, where the other 4 are factory methods, convenience methods that do some extra set up for you.

Of these 4 factory methods, there's two groups, scheduled and unscheduled.  The two methods that start with the phrase timerWithTimeInterval: create unscheduled timers.  The two that start with the phrase scheduledTimerWithTimeInterval: are scheduled timers.  The only difference between creating timers with these two groups is that the former need to be scheduled after they've been created while the latter do not.  The latter are scheduled to start counting time from the instant they're instantiated.

So let's focus on the two scheduled timers as these are the ones that are really the most useful.

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
                                 invocation:(NSInvocation *)invocation
                                    repeats:(BOOL)repeats;

+ (NSTimer *)scheduledTimerWithTimerInverval:(NSTimeInterval)seconds
                                      target:(id)target
                                    selector:(SEL)aSelector
                                     repeats:(BOOL)repeats;

So, there are three parts to these timers.

The timer interval between now and when the timer should fire.
The action that should be taken when the timer fires.
Whether or not the action should repeat.

The first method solves part two with a single argument, an NSInvocation class, something I'm not familiar with, but it's basically an Objective-C message rendered static--an action turned into an argument.

The second method solves part two with two arguments.  A target and a selector.  The target is a reference to the object you want to call a method on, and the selector is the method you want the timer to call on that target.

The method should take a single argument of type NSTimer as the timer object sends itself as the argument to the method it calls.  This is particularly useful because NSTimer has a NSDictionary property called userInfo in which you can store any information you want when you create the timer so that the method that gets called can retrieve the information stored.

So, a quick rewrite of your class using NSTimer might look something like this:

In interface:

@property (nonatomic,strong) NSTimer *timer;

In implementation:

- (void)startTimer {
    self.state = CountdownCounting;
    self.timer = [NSTimer scheduledTimerWithInterval:0.25f
                                              target:self
                                            selector:@selector(update:)
                                             repeats:YES];
}

- (void)restartTimer {
    [self cancelTimer];
    [self startTimer];
}

- (void)cancelTimer {
    if (self.timer.isValid) {
        [self.timer invalidate];
    }
    self.state = CountdownNotCounting;
}

- (void)update:(NSTimer *)timer {
    // logic for whatever you want to happen each time the timer fires
}

In the update: method, you don't need any special logic relating to the timer.

When we call invalidate on the timer, it stops the timer.  Because we sent YES for the repeats argument, it will automatically recall update: every 0.25 seconds until we stop the timer.

Although, as you can see, NSTimer is really quite simple to use, and arguably doesn't warrant a wrapper class.

One important thing to watch out for with NSTimer however.  While the timer is valid, the timer object holds a strong reference to the value sent for the target: argument.  This is important to note because in most cases the timer is a property on a given object with a strong reference to it (so the timer doesn't deallocate) and the object will typically send itself as the target argument.  So we're knowingly and intentionally creating a retain cycle for the timer period during which the timer is valid.

This is mostly fine.  If we sent NO as the argument for repeats:, then the retain cycle only lasts until the timer fires, at which point the method is called on the object (which is better than a method being called on a deallocated object, which would crash the app).  Once the method returns, NSTimer releases its strong reference to the object, the retain cycle is broken, the object deallocates, leaving no strong references to the NSTimer object, so it deallocates, and now everything is fine.

NSTimer also breaks its strong reference when it is invalidated however, so all you have to do to break an NSTimer retain cycle is simply call invalidate on it.  This is important to remember when you've sent YES for the repeats: argument.


Plot heat map from csv file using numpy and matplotlib

Since you are already using numpy, you can use numpy's loadtxt function to read in all the data at once as numpy arrays from the start.  This allows you to avoid having to worry about opening or closing files (this is done automatically), converting to numpy arrays, etc.  Then it is a simple matter of converting the indexes to values.

You can also vectorize the test data creation, using numpy's meshgrid function to get a grid of corresponding X and Y coordinates.

You can make the plotting better, in my opinion at least, by using plt.subplots() to get a figure and axes object right at the beginning, then using those to do the plotting.

So here is how I would do it:

import numpy as np
import matplotlib.pyplot as plt

def create_test_csv(fname):
    np.random.seed(42)

    # Generate X and Y coordinates
    x = np.arange(300)
    y = np.arange(600)

    # Get corresponding X and Y coordinates
    xs, ys = np.meshgrid(x, y)

    # Get random values for each location
    zs = np.random.randint(0, 255, size=xs.size)

    # Convert 3 2D arrays to 1 2D array of columns
    data = np.vstack([xs.ravel(), ys.ravel(), zs.ravel()]).T

    # Save to file
    np.savetxt(fname, data, delimiter=',', fmt='%d')

def get_xyz_from_csv_file_np(csv_file_path):
    '''
    get a grid of values from a csv file
    csv file format: x0,y0,z0
    '''

    # Load the csv file into a single 2D array,
    # then split the columns into individual variables.
    x, y, z = np.loadtxt(csv_file_path, delimiter=',', dtype=np.int).T

    # Create an empty 2D array of pixels and
    # put all the values into the correct place
    plt_z = np.zeros((y.max()+1, x.max()+1))
    plt_z[y, x] = z

    return plt_z

def draw_heatmap(plt_z):
    # Generate y and x values from the dimension lengths
    plt_y = np.arange(plt_z.shape[0])
    plt_x = np.arange(plt_z.shape[1])

    # everything is the same from here on
    z_min = plt_z.min()
    z_max = plt_z.max()

    plot_name = "demo"

    color_map = plt.cm.gist_heat #plt.cm.rainbow #plt.cm.hot #plt.cm.gist_heat
    fig, ax = plt.subplots()
    cax = ax.pcolor(plt_x, plt_y, plt_z, cmap=color_map, vmin=z_min, vmax=z_max)
    ax.set_xlim(plt_x.min(), plt_x.max())
    ax.set_ylim(plt_y.min(), plt_y.max())
    fig.colorbar(cax).set_label(plot_name, rotation=270)
    ax.set_title(plot_name)
    ax.set_aspect('equal')
    plt.show()
    return figure
    figure = plt.gcf()
    plt.show()
    return figure

if __name__ == "__main__":
    fname = 'temp.csv'
    create_test_csv(fname)
    res = get_xyz_from_csv_file_np(fname)
    draw_heatmap(res)


Create a binary tree, code review request

I only see one really questionable thing in your code.  Why do you call this() in your constructor?  Your parameter-less constructor does absolutely nothing, so this line is irrelevant.  If anything, I would actually even remove that constructor entirely so that your API can only be used with your meaningful and useful one.

Also, as a side note, the following line opens you up to a NullPointerException since you never check to see if items is null or if it has any elements.

root = new TreeNode(null, items.get(0), null);


Still pulling information from XML to insert into Word Document inside 3rd party application

I see one point that seems almost obvious enough that I'm worried I might be missing something. A For Each is "smart" enough that its body isn't executed at all for an empty collection, so you can eliminate the test for the list having a length of 0:

Dim phoneNode
Dim phoneNodeList
ReturnData = ""

Set phoneNodeList = XmlDoc.SelectNodes("/Record/Case/CaseFormsLoad/PartyLoad/Party/PartyPhones/Phone")
For Each phoneNode In phoneNodeList
    If phoneNode.GetAttribute("ConfidentialFlag") = "True" Then
        ReturnData = ReturnData & phoneNode.Getattribute("PhoneNum") & VbCrLf
    End If
Next


Is the JavaScript code I've provided following Functional Programming best-practices?

Preface
"Best Practises" are very subjective, so your question cannot really be answered in that regard, but I will try to give you some tips nonetheless.
To lead into the rest of my answer I would say one of the most beginner-friendly resources for learning a functional style in javascript is this Medium article (without going into a lot of the nitty-gritty theoretical stuff). By reading this I think you will come to understand a lot of the ideas that come with functional programming.

♀ Paradigm vs. Style
With that out of the way, let us start with a shocker: Javascript is not really a functional programming language. Yep, I said it. Javascript is more a procedural (or object-oriented) language (some newer features have allowed for more functional-ish style but it remains very procedural). But all that ofcourse does not mean you cannot apply a functional style, which I think is more the core of your question?
Presuming I did correctly interpret your question, let me paraphrase to you the first two sentences of the Wikipedia page about FP:

[...] functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm [...], rather than a sequence of imperative statements [...].

This means that, when writing your programs, you do not tell the computer exactly what to do every step of the way (i.e. for (let i = 0; i < n; i++)) but rather you chunk a problem into smaller sub-problems, solve those, and compose a function that calls your smaller functions to solve the bigger problem. This leads me to my first tip. Javascript functions come in two forms: procedures, and lambda's. I am not going into the details that differentiate the two, but rather I would like to tell you about lambda's.

 Tip 1: Embrace expressions
You seem to know javascript's lambda syntax, since you use the arrow notation (x => y), but you are using it in a procedural way. What I mean by that, is that you append a block to each lambda, as such:
const doSomething = (arg1, arg2) => { /*steps*/ };

This kind of defeats the purpose of the notation, and is basically another syntax for the procedural functions of JS:
function doSomething (arg1, arg2) { /*steps*/ }

In Javascript, x => y means a function that takes x and returns y. So a lot of your functions can be simplified. Let's change a couple to make it clear:
const sayHello = (name) => {
    return `Hello, ${name}!`;
};
// can be
const sayHello = name => `Hello ${name}!`;

and
const addNums = (x, y) => {
    return x + y;
};
// can be
const add = (x, y) => x + y;

 Tip 2: Spice up your functions
But then what is the purpose of the lambda notation, and why is your code defeating its purpose? To put it simply: a lambda is a function that takes zero or one argument(s), maybe transforms it, and yields a result. Wikipedia's article about lambda calculus says the same, but with more jargon:

[...] all functions in the lambda calculus are anonymous functions, having no names. They only accept one input variable, with currying used to implement functions with several variables.

You use a lot of functions as procedures (sequence of steps) which you cannot have in FP, and you are using multiple parameter functions which are also disallowed (or rather just do not exist in FP). But, you might ask, how are you supposed to do anything with just one parameter and a single expression body? Let us take a snippet of your code and refactor it into a nice functional style:
// Original
const createButton = (text, func) => {
    const button = document.createElement('button');
    const buttonText = document.createTextNode(text);
    button.appendChild(buttonText);

    button.addEventListener('click', () => {
        return func();
    });

    return button;
};

// Functional alternative
// Some setup, notice the currying for multiple arguments.
const text = text => document.createTextNode(text);
const newButton = () => document.createElement("button");
const listen = event => handler => target => {
  // Javascript was not meant to be used purely functionally,
  // so we have to use a block with several statements to
  // mutate the target, and then return it (mutation will never
  // happen in functional programming, as you might know).
  target.addEventListener(event, handler);
  return target;
};
const append = child => target => {
  // Same story: we have to return the target after mutating it.
  target.append(child);
  return target;
};

// Here comes the true power of functional programming: composition
const onClick = listen("click");
const addLabel = label => append(text(label));
const sayHi = () => console.log("Hi!");
const sayBye = () => console.log("Bye.");
const button = label => handler =>
  addLabel(label)(
    onClick(handler)(
      newButton()));

const friendlyButton = button(":)")(sayHi);
const sadButton = button(":(")(sayBye);

// Try it out!
document.body.append(friendlyButton, sadButton);

Ok, giant code sample with weird and maybe hideous things. Let me explain it!
Firstly I would like to say that Javascript is a great language, but the DOM is not the best part to use FP for, because it's an amalgamation of mutation and imperativeness, which are the arch-enemies of FP. But let us do it anyways because it is fun!
The first statement of the refactor goes as follows:
const text = text => document.createTextNode(text);

which is essentially a function that, when called with an argument text will create a textNode with text being its text. Now this is a bit of a weird one, because we made a function that takes an argument, and then calls another function with that very argument, so we basically aliased it. Aliasing is the same as storing it in a variable with another name, so why not write it like this:
const text = document.createTextNode;

text is equal to document.createTextNode, so text("Hi!") is equal to document.createTextNode("Hi!").

Now JS is a bit weird (and full of side-effects), so we have to specify that the this of document.createElement is document (document.createElement.bind(document)). The peculiarities of Javascript's this go far beyond the purpose of this post so if you do not understand what that meant, just wrap it in a function like so: x => y(x);

The first real weirdness happens in the listen function:
const listen = event => handler => target => { /*...*/ };

What? A function that returns a function that returns a function that returns something else?! Yep, that is functional programming baby! But why would we do this? Because it allows for very easy composition. Notice how later on, we defined the function onClick, which is a composed listen:
const onClick = listen("click");
// This means the following:
const onClick = handler => target => target.addEventListener("click", handler);

So we made a function that always adds a click eventlistener to a target. We can take this a step further:
// Let's make a function that makes an element yell "OUCH!" on click!
const ouch = onClick(() => console.log("OUCH!"));
// This means the following:
const ouch = target => target.addEventListener("click", () => console.log("OUCH!"));

// Try it out!
const boxingDummy = ouch(addLabel("Don't hit me!")(newButton()));
document.body.append(boxingDummy);

I hope that made it clear why you would write programs in such a weird (coming from procedural programming) way. I would link you the wiki article but that is just unintelligble jibberish to me too.

 Tip 3: Lose control
You seem to really rely on the imperativeness of Javascript to perform tasks in a set order, which does not fit well in a functional style -- most functional languages do not even allow it. The great functional programming evangelists have thought about this long and hard, and showed us how you do not need loops, if's or sequences to create complete and functional (in the literal sense) programs. Taking, for example, another function you wrote:
const view = () => {
    const component = document.createElement('div');

    // create a button element that has a callback function that will append the returned value to the DOM

    component.appendChild(createButton('Hello', () => {
        return component.appendChild( createText( sayHello('Kristian') ) );
    }));

    component.appendChild(createButton('Add Numbers', () => {
        return component.appendChild( createText( addNums(3, 7) ) );
    }));

    component.appendChild( createButton('Log', simpleLog) );

    component.appendChild(createButton('Add to array', () => {
        console.log( `Original array: [${myList}] - New array: [${addToArray(4)}]`);
    }));

    return component;
};

Pardon the joke, but this looks really WET... (as in, the opposite of DRY). You call component.appendChild(createButton(/*...*/)) a lot of times. Apart from that being a bit of a code smell, it also is a really great place to put in some FP magic. Analysing the abstract meaning of your code, let me write that out in a more functional style:
// Remember our previous functions?
// I made them nice and generic so they are
// reusable here!
const appendButton = label => action => append(button(label)(action));
const add = x => y => x + y;
const addFive = add(5);
const saySix = () => console.log(addFive(1));
const fold = (...functions) => value => functions.reduce(
  (result, fun) => fun(result),
  value);
const component = document.createElement("div");
const view = fold(
  appendButton("Greet")(sayHi),
  appendButton("What's five plus one?")(saySix)
  /* etc... */);

// Try it out!
document.body.append(view(component));

BAM! No blocks, no loops, no if's! Instead of a sequence of statements, we use a fold to abstract away a lot of the DOM boilerplate. Higher-order functions such as fold(left) are very important functions to keep in your arsenal. I suggest reading up on it a bit, if the article isn't too crytographic (there's a joke that says functional programmers tend to lose their ability to explain FP as soon as they understand, and I think that applies perfectly on most wiki pages).

Well that should be about it. To summarise:

Javascript DOM isn't the best place to apply FP (in my humble opinion), but go ahead and break the rules!
Don't get RSI: (x) => { return y; } is the same as x => y.
Procedures are so 1970; compose a function from functions to solve your problems (and most importantly: be able to reason about your solution).
Currying and higher-order functions are a functional programmer's best friends, conquer the world with them.


JQuery UI Datepicker with beforeShowDay function

for 1)

var today = new Date();
today.setTime(0); // resets the time. (midnight)

I believe this will fix the date comparison issue

for 2)

It just sucks that there isn't a built-in for this sort of thing. I would suggest not putting it on the Date prototype just in case it conflicts with some other date function/library down the road. Its seems to be only a matter of preference though.

(if you Google: JavaScript format date you'll see many other examples of formatting the date or https://stackoverflow.com/q/1056728/684890 where there are a few alternatives suggested in case you want some more functionality. )


Simple OOP currency converter - follow-up

Set?

You have logic preventing duplicate currency pairs. The easier (and more performant) thing to do is to simply represent pair_currencies as a set instead of a list. When you add, it will automatically discard duplicates.

snake_case

The standard is to name methods like your last_pair - i.e., get_rate.

Lookups

You have a loop in getRate and editRate to try and find the correct currency. Instead, you should be using a dictionary, which does not require a loop.

Remove duplicate methods

editRate and setRate do the exact same thing, so delete the former.

Equality test is wrong

Your __eq__ method should be comparing to an object instance, not a string. As such, you should be comparing self.name with object.name.


const split = (text) => (text.replace(/.(.)?/g, '$1') + ("d"+text).replace(/.(.)?/g, '$1')

The regex matches every other char. Do it twice, add any arbitrary char to the start of the string the second time to offset it.


Selecting subset of size k using recursion

Your logic is good, and the API is pretty solid as well. There are a few point that could use some work.

Organization

selectRec can be moved inside of selectSubset to simplify the structure slightly.

It's also tail recursive, so you might as well add the annotation. I cannot recall if this is required, but even if it's not, it's a good habit to get into.

For readability, I'd recommend reversing the if so that the one-liner is in the if clause rather than the else clause. Generally speaking, it's easier to keep track of what part of the code it belongs to, the closer it is to the construct - particularly if there is a bunch of nesting. Here it doesn't make a big difference, but as a matter of course I'd swap them.

Return Types & Misc

As you are forgetting everything except acc when we return, we can actually simplify the return type to just Seq[O].

I'm going to assume that Seq was intended, so candidates - next, acc + next needs to become candidates.filter(_ == next), acc :+ next.

As the name of the trait was dropped from the question, I'm going to use GreedySubset.

Early Termination

What you have marked as an "early termination" is just "termination", it's the base case. Limiting this to the length of candidates isn't really early termination. A similar effect could be achieved by replacing k in the selectRec call inside selectSubset with k min candidates.length.

If you want to the library users to terminate early, which is not a bad idea, one way is to have selectNext return Option[O] rather than just O.

Refactored Version

import scala.annotation.tailrec

trait GreedySubset {
  type O /* Individual objects */
  type S /* Intermediate state */

  def selectSubset(candidates: Seq[O], k: Int): Seq[O] = {
    @tailrec
    def loop(candidates: Seq[O], acc: Seq[O], count: Int, state: S): Seq[O] =
      if (candidates.isEmpty || count <= 0) acc
      else selectNext(candidates, acc, state) match {
        case Some(next) =>
          loop(candidates.filterNot(_ == next),
            acc :+ next,
            count - 1,
            computeState(state, next))
        case None => acc
      }
    loop(candidates, Seq[O](), k, initialState(candidates))
  }

  /* Implemented by library users */
  def initialState(candidates: Seq[O]): S

  def selectNext(candidates: Seq[O], alreadySelected: Seq[O], state: S): Option[O]

  def computeState(previousState:S, lastSelected:O): S
}

Alternate Implementation

Another alternative, which is arguably simpler, is to implement this as a case class with function arguments. This implementation is exactly equivalent to the refactored version above, and is arguably simpler and easier to use.

case class GreedySelector[E,S](
  initialState: Seq[E] => S,
  selectNext: (Seq[E], Seq[E], S) => Option[E], // First argument is candidates
  computeState: (S, E) => S) {

  def selectSubset(candidates: Seq[E], k: Int): Seq[E] = {
    @tailrec
    def loop(candidates: Seq[E], acc: Seq[E], count: Int, state: S): Seq[E] =
      if (candidates.isEmpty || count <= 0) acc
      else selectNext(candidates, acc, state) match {
        case Some(next) =>
          loop(candidates.filterNot(_ == next),
            acc :+ next,
            count - 1,
            computeState(state, next))
        case None => acc
      }
    loop(candidates, Seq[E](), k, initialState(candidates))
  }
}


The web.config is loaded into memory once per-request anyway - it isn't loaded and parsed every time you access a section via the WebConfigurationManager. What speed increases have you actually noticed?

In fact, it might not even occur for each request, according to MSDN: 'These settings are calculated once and then cached across subsequent requests. ASP.NET automatically watches for file changes and re-computes the cache when any of the configuration files change within that file's hierarchy. When the server receives a request for a particular URL, ASP.NET uses the hierarchy of configuration settings in the cache to find the requested resource.' So, you're just doubling up on memory consumption; and I'm not convinced it's faster.


Computing the autocorrelation between 2D time series arrays in python

So here is a slightly simplified version that uses more numpy functionalities, where your solution manually iterates over the outer lists:

def autocorrelate_graipher(Data):
    Data = np.array(Data)
    A = Data.mean(axis=0)                        # Average 2D array
    New_Data = (Data - np.mean(A)) / np.std(A)
    for count in range(1, len(New_Data) // 2):
        i = np.arange(len(New_Data) - count)
        yield np.multiply(New_Data[i], New_Data[i+count]).sum(axis=0).mean()

It returns the same result as your function, albeit as a generator, so you need to call list on the output.

Unfortunately it still has the manual loop over the lags, which I at least made a for loop instead of a manual while loop.

Note that Python has an official style-guide, PEP8, which people are encouraged to follow. It recommends using lower_case for variables and functions, so Data should be data, New_Data should be new_data, A should be a, or even better average.


You could rewrite your get_IPs function to be a list comprehension instead:

return [i.rsplit(' ', 1)[-1] for i in map(str.strip, os.popen('ipconfig'))
        if i.startswith('IP')]

map will call strip on all of the results from 'ipconfig' and then you can iterate over that, ignoring any values that don't start with "IP".

In worker you're using a loop to retry after timeouts. But you're just using 2 arbitrarily. Use a constant here so it's clear what you're doing, and easy to change later:

You also multiple times open files, but you should always try to use with, known as the context manager. It automatically closes the file even in the event that an error is raised. It's the safest way to open a file.

with open(filepath) as filename:
    execute_code_with(filename)
print("Done with filename")

Once you leave that indented block, the file is automatically closed. No need to even call filename.close().


Avoid Selecting of Activating Object unless absolutely necessary Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset).

Writing an array of values to a worksheet is much faster than writing the values individually.

The Worksheet.Pictures method returns a collection of pictures on the worksheet.
You can get a subset of pictures by passing an Array of Indices as a parameter to the Worksheet.Pictures method:

 ActiveSheet.Pictures(Array(1,2,30))

Or an Array of names:

 ActiveSheet.Pictures(Array("Picture 1","Picture 2","Picture 3"))

You can also work on the whole collection or subset at once:

 ActiveSheet.Pictures.Delete

Formatting a range of cells is much faster than formatting each cell in a range.

Columns("H:I").ClearContents
Columns("H").NumberFormat = "@"

Short compact code is much easier to read.

Which is easier to read?

h = hDefaut
h = h - 4

Or

 h = hDefaut - 4

Largeur = Imag.Width
Hauteur = Imag.Height
Largeur = Largeur * Rapport
Hauteur = Hauteur * Rapport
Imag.Width = Largeur
Imag.Height = Hauteur

Or

Largeur = Imag.Width * Rapport
Hauteur = Imag.Height * Rapport

With Worksheets("Pix")
   DerLig = .Range("H" & Rows.Count).End(xlUp).Row
   ActiveWorkbook.Names("PicTable").Delete
   ActiveWorkbook.Names.Add Name:="PicTable", RefersTo:="=Pix!$H$2:$H$" & DerLig
End With

The code above can be simplified:

With Worksheets("Pix")
   .Range("H2",.Range("H" & Rows.Count).End(xlUp)).Name = "PicTable"
End With

MS Access is better suited for this type of thing.  I personally would create a webpage.  Whether I used Excel or a webpage I would create a paginator and avoid embedding the images.

I refactored your code here: Making a catalog of pictures.xlsm.  Note: I didn't make the Rapport size adjustments but it should be easy enough for you to implement it.


I see a number of things that could help you improve your program.

Fix your formatting

Crowding multiple statements on a single line makes your program harder to read and understand.  So instead of this:

if ((*off) > msg.size()) return 0;
int32_t result; int size = sizeof (result);

Write this:

if ((*off) > msg.size()) {
    return 0;
}
int32_t result;
int size = sizeof (result);

Use the required #includes

The code uses std::vector which means that it should #include <vector>.  It was not difficult to infer, but it helps reviewers if the code is complete.  For this code, it appears that you need these:

#include <vector>
#include <cstring>
#include <cstdint>

Use C++-style includes

Instead of including string.h you should instead use #include <cstring>.  The difference is in namespaces as you can read about in this question. I infer that the code used that because the call to memcpy was not std::memcpy.

Prefer passing a reference to a raw pointer

The writeInt32() function takes a pointer to a vector, but what if the pointer is nullptr?  Clearly the function will fail, and probably crash the program if that happens.  Better, then, would be to pass a reference instead, which says that it really MUST be a std::vector<std::uint8_t> and nothing else.

Avoid portability problems

The endianness of computers is not fixed by the C++ language standard, so your memory copy or memory casting is not going to work the same way on all machines.  This portability problem can be solved by doing one of two things: either rely only on guarantees that are actually made by the standard or use conversion routines to put everything in the same order.  This often comes up in network communications, so some platforms have htonl() and friends to convert from "host order" which might be big-endian or little-endian, to network order which is always big-endian.  Note, however, that this has its own portability issues because those functions are not part of the C++ standard.  So the other way to do it is to do it yourself.

static void writeInt32(std::vector<std::uint8_t>& msg, std::int32_t value)
{
    for (auto i = sizeof(value); i; --i, value >>= 8) {
        msg.push_back(value & 0xff);
    }
}

This is shorter and also portable.  In this version, i is declared to be auto but declaring it to be of type std::size_t, as you had it, is another way to do it and even works if you're not using a C++11 compiler.

Be careful with signed and unsigned

In the readInt32 routine, the code compares an int to a size_t, but size_t is unsigned and int is signed.  In this case, your off variable should probably be declared as being of std::size_t * type.

Don't fail silently

In the readInt32 function, a returned value of 0 might mean that a value of zero was actually read or it might mean that the offset pointer was off the end of the message.  Unfortunately with the current code there's no way to differentiate these cases.  I'd suggest throwing an exception instead.

Be careful with memcpy

The code currently catches the case in which the offset is beyond the end of the vector, but what if it's pointing instead to the last byte of the vector?  In this case, memcpy will copy that last byte and whatever happens to be in memory beyond that.  This is not likely to be a useful value.  In this case, I'd recommend not using memcpy at all and rewriting the code to be portable as mentioned above.

Reconsider the interface

Right now, the code consists of two functions which deal with writing/reading a std::int32_t value to/from a message.  If your code frequently does things with such messages, it might be better to create a Message class and have member functions that read and write particular types of values, such as your std::int32_t values used here.  I'd also recommend that raw pointers such as off not be part of the interface at all.


Using an internal representation of time that is as simple as possible would simplify your work. For example, using internally seconds since midnight, the add method could become

def add(self, other):
    self.seconds = (self.seconds + other.seconds) % SECONDS_IN_DAY


Displaying information about a ticket purchase

I finally figured out a better approach to avoid those complex logic in my view by using a presenter pattern. I create a presenter directory in my app folder and subfolder for the event controller and a tickets_report_presenter.rb file with the following code

module Events
  class TicketsReportPresenter
    attr_reader :event

    def initialize(event)
      @event = event
    end

    def all_bookings
      event.bookings.paginate(page: 1, per_page: 20)
    end

    def attendees
      event.attendees.paginate(page: 1, per_page: 20)
    end

    def ticket_types
      event.ticket_types.map do |ticket|
         Report::Ticket.new(ticket)
      end
    end

    def grand_quantity
      ticket_types.map(&:quantity).inject(0, &:+)
    end

    def ticket_left
      ticket_types.map(&:remains).inject(0, &:+)
    end

    def quantity_sold
      ticket_types.map(&:tickets_sold).inject(0, &:+)
    end

    def total_price
      ticket_types.map(&:price).inject(0, &:+)
    end

    def total_amount
      ticket_types.map(&:amount).inject(0, &:+)
    end

  end

  module Report
    class Ticket
      attr_reader :ticket

      def initialize(ticket)
        @ticket = ticket
      end

      def name
        ticket.name
      end

      def quantity
        ticket.quantity.to_i
      end

      def tickets_sold
        ticket.user_tickets.count.to_i
      end

      def price
        ticket.price.to_i
      end

      def remains
        quantity - tickets_sold
      end

      def amount
        price * tickets_sold
      end
    end
  end
end

Then in my tickets_report action, I did this

def tickets_report
    @presenter = Events::TicketsReportPresenter.new(@event)
end

This allows be to call the following methods in my view:

@presenter.all_bookings
@presenter.attendees
@presenter.ticket_types
@presenter.grand_quantity
@presenter.ticket_left

Thanks to anyone who viewed this.


Read PEP8, it will give you directions on how to write Python code that look like Python code to other.

Other than that, the behaviour you're seeking is already implemented in range:

>>> a = range(7, 0, -2)
>>> list(a)
[7, 5, 3, 1]

You just need to reverse it to form the full hourglass:

>>> a = range(7, 0, -2)
>>> list(a) + list(reversed(a))
[7, 5, 3, 1, 1, 3, 5, 7]

And remove the repeated center:

>>> decreasing = range(7, 0, -2)
>>> increasing = reversed(decreasing)
>>> next(increasing)  # Remove duplicated center
>>> list(decreasing) + list(increasing)
[7, 5, 3, 1, 3, 5, 7]

Now you can make use of itertools.chain instead of list concatenation and turn your function into a generator to separate computation from printing.

import itertools

def hourglass(size):
    decreasing = range(size, 0, -2)
    increasing = reversed(decreasing)
    next(increasing, None)  # Remove duplicated center
    for length in itertools.chain(decreasing, increasing):
        yield '{:^{}}'.format('@' * length, size)

if __name__ == '__main__':
    for i in range(20):  # Test our function
        print('\n'.join(hourglass(i)), end='\n---\n')

Note that if you are using Python 3.6+ you can format the line using

yield f'{"@" * length:^{size}}'

instead which may be slightly more readable.


Return the first recurring character in a string

The problem is similar to your other "two of something" problems, such as Palindrome and Find the elements that appear only once.  As in those problems, a Set is the appropriate data structure.

The main difference is that early exit is possible (when two of something is found) so we'd rather not be inside of a reduce.

const firstRepeated = s => {
  const seen=new Set();
  for (var c of s) {
      if (seen.has(c)) return c;
      else seen.add(c);
  }
  return null;
}


Implementing the "Thinking in React" example from React documentation without using Refs

Actually, I'd worry more about the issue that's bound to happen - your handleChange trying to do everything. I suggest you split them off to two distinct functions, one for the text input, and the other for the checkbox. This is much more maintainable in the long run, as each function is only responsible for one task. This ain't mixed martial arts :P

There's nothing wrong with refs. They're simply for easy access to the DOM elements inside the component. What's probably wrong is when an parent component accesses child refs, or a component exposing its refs to other components. Components should only receive props and state, and emit events with data (like a regular DOM element). You don't mess with how it implements its internals.

Anyways, not much change here:

var SearchBar = React.createClass({
  handleInputChange: function(){
    this.props.onUserInput(this.refs.myInput.value, this.props.inStockOnly);
  },
  handleCheckboxChange: function(){
    this.props.onUserInput(this.props.filterText, this.refs.myCheckbox.value);
  },
  render: function() {
    return (
      <form>
        <input type="text" placeholder="Search..." value={this.props.filterText} onChange={this.handleInputChange} ref="myInput" />

            <input type="checkbox" checked={this.props.inStockOnly} onChange={this.handleCheckboxChange} ref="myCheckbox" id="myCheckbox" />
            Only show products in stock

      </form>
    );
  }
});

Now regarding your markup,
 means paragraph but you have an <input>. I believe
 was simply used for layouting.
 is more appropriate. It also appears that your text is a label for the input. I suggest you wrap them in a  so clicking the label toggles the box. An additional  is recommended since you might want to style the text differently from a text-only label.


In Python, you don't need to create your variables before using them, so the address = '' before your loop is unnecessary. You also don't need to reset a variable before using it again, so the address = '' at the end of each loop iteration is particularly unnecessary.
You currently get the addresses from the DB and then concatenate parts of that address as the query string for your geolocation. This would be easier if you got the address in the same order you need it later:
sql_command = "SELECT ADDRNUMBER, STREET, CITY1, REGION, POST_CODE1 FROM CV_COORDS_TO_PROCESS"
cursor.execute(sql_command)
rows = cursor.fetchall()

for row in rows:
    #build the address string and save the address id
    addr_id, address = row[0], ", ".join(row[1:])
    ...

There's probably a way to do the concatenation already in SQL, but I am not versed enough in that language to suggest how.
If you want to get the first value from an iterable, you can use next:
location = next(iter(client.geocode(address)['results']))

Most DB wrappers support prepared statements, which would mean that you don't have to prepare the full query string, but rather use something like this:
merge_query = "upsert zsa_addr_coords values ('100', ?, ?, ?, ?, ?) where addr_id = ?"
try:
    cursor.execute(merge_query, (addr_id, lat, long, accuracy, accuracy_type, addr_id));
except:
    print (ex)

Indeed, hdbcli also support this: https://blogs.sap.com/2017/07/26/sap-hana-2.0-sps02-new-feature-updated-python-driver/
It should even take care of quoting for you and prevents the most basic SQL
injection attacks.
And since that string now never changes, you can pull it outside of the loop.
You can probably speed up the execution time by disabling the auto-commit mode before your loop and manually committing at the end, which ensures that you don't have to do that every loop iteration:
conn.setautocommit(False)
for row in rows:
    ...
conn.commit()


One purpose for using jQuery is the ability to chain methods. You can first remove the "active-element" class from .d, then utilize .filter() with a single line passed as parameter within a template literal which removes the "active-filter" class from .b elements, filters and adds the same class to this element, and concludes by returning the .data() of the current element, which is the attribute value selector to match the corresponding .d element where the "active-element" class is added.

$(".b").click(function(e) {
  $(".d").removeClass("active-element")
  .filter(`[data-filter='${
    $(".b").removeClass("active-filter")
    .filter(this).addClass("active-filter")
    .data().filter
   }']`)
  .addClass("active-element");
});
.b {
  width: 60px;
  height: 60px;
  padding: 10px;
  margin: 10px;
  background-color: lightgrey;
  float: left;
}

.c {
  width: 60px;
  height: 60px;
  padding: 10px;
  margin: 10px;
  background-color: lightgrey;
  float: left;
}

.element {
  float: left;
  display: block;
}

.active-filter {
  background-color: pink;
}

.active-element {
  background-color: yellow;
}

data-filter

data-filter

data-element

data-element


You're taking for granted that a link will be '<a href="http:/', which is definitely not always the case. What about https:// for example, or if you have something like '<a class="visited" href="http:/' ? That's why you should use a library to parse the DOM objects instead of relying on raw text parsing.
Naming:

usually a row is related to a database, while a line is related to a text file.
temp means nothing, it's the new content, so you should use something like new_html_content.
It takes a bit to understand that counter is actually the max depth that you want to follow, so why not call it depth
Function names should explain what they do, dumbwork name doesn't, something like recurse_page may be better.
start_link is good for the first link (almost, see below) but the parameter to the function is actually the current link being parsed, so why not call it current_link?
You used snake case for start_link, you should keep using it, so get_from_url may be better.
start_link, start_url and end_url are not links or urls, they're actually the index of the string, so they should be start_link_index, start_url_index and end_url_index
text is the HTML content, so just rename it to html_content

The lines doing something with row should be next to each other, or better yet, in a separate function.
That 2 should be in a constant so that the first line of the function can be something like if depth < MAX_DEPTH:
You're trapping exceptions but you're not doing anything with them, you should at least log somewhere what happened.
The text.find to get the url are probably better off in a separate function, to improve readability, something like
getfromurl already returns a string, no need for the str()
You're using always the same name for the file which, when opened with w will overwrite the contents. You should at least check if the file already exists.
You're opening a file and leaving it open for the whole duration of the process. This is not bad in itself, but I'd probably put a function called append_to_file where I open the file with a instead of w, write the line and immediately close it. Inside of that function you will also convert the status code to a string.

In the end, your worker loop may look something like this:

def recurse_page(current_link_index, start_index, html_content, pattern, depth):
    if depth < MAX_DEPTH:
        depth += 1
        while current_link_index > -1:
            try:
                url = get_url(html_content, start_index)
                append_to_file(url, urllib.urlopen(url).getcode())
                new_html_content = get_from_url(url)
                recurse_page(new_html_content.find(pattern), 0, new_html_content, pattern, depth)
                current_link_index = html_content.find(pattern, end_url_index + 1)
            except Exception, e:
                # TODO: Proper error handling
                break

It's not complete code, but it should give you an idea of what I mean.


Rather than generating the substring for the last two chars and reversing it, you could simply add the last two chars in reverse order:

return str.substring(0, str.length() - 2)
    + str.charAt(str.length() - 1)
    + str.charAt(str.length() - 2);


You're using pathlib, which is great! Unfortunately, you immediately discard the functionality it gives you, and use old-style os APIs.
A good place to start is here - a mapping between the os[.path] APIs and their Path equivalents. Doing that gets us here:
def make_archive2(source, destination):
    shutil.make_archive(destination.stem, destination.suffix, source.parent, source.name)
    shutil.move(destination, "/Users/my_name/Desktop/Zip Test/zipped_content")

We now don't need to do any manual manipulations using os or os.path. Once we're here, we can actually realize that the first parameter to make_archive is a full path to the file, completely removing the requirement to call shutil.move
From there, we can improve some of the other things you do. For example:

Your source and destination are the same thing... but you don't actually use the destination in a meaningful way
You extract the format from the destination, which feels a bit odd
You hardcode the actual final destination
You use both the root_dir and base_dir parameters, when that really isn't necessary
You don't return where the file ended up, which feels nicer than the caller having to set up their Path themselves

Altogether, I ended up with something like this:
def make_archive3(to_archive, move_to, archive_format="zip"):
    move_to.mkdir(exist_ok=True)
    return shutil.make_archive(move_to / to_archive.name, archive_format, to_archive)


The underlying complexity

  I suspect the problem lies …

Ah, but we don't like to suspect. Just as our compiler tells us that we're missing a semicolon, our profiler will tell us where we lose time. Let's add a main first:

main :: IO ()
main = readLn >>= print . length . primes

Now, it's easier to measure:

$ ghc -prof -auto-all -O2 Primes.hs
$ echo 1000 | ./Primes +RTS -s -p
168
      23,717,912 bytes allocated in the heap
       1,235,856 bytes copied during GC
         111,776 bytes maximum residency (2 sample(s))
          26,880 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0        44 colls,     0 par    0.000s   0.002s     0.0000s    0.0002s
  Gen  1         2 colls,     0 par    0.000s   0.001s     0.0005s    0.0008s

  INIT    time    0.000s  (  0.002s elapsed)
  MUT     time    0.375s  (  0.372s elapsed)
  GC      time    0.000s  (  0.003s elapsed)
  RP      time    0.000s  (  0.000s elapsed)
  PROF    time    0.000s  (  0.000s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time    0.375s  (  0.377s elapsed)

  %GC     time       0.0%  (0.8% elapsed)

  Alloc rate    63,247,765 bytes per MUT second

  Productivity 100.0% of total user, 99.5% of total elapsed

$ echo 2000 | ./Primes +RTS -s -p
303
      84,381,928 bytes allocated in the heap
       9,612,184 bytes copied during GC
         137,048 bytes maximum residency (2 sample(s))
          28,592 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0       161 colls,     0 par    0.062s   0.015s     0.0001s    0.0005s
  Gen  1         2 colls,     0 par    0.000s   0.001s     0.0003s    0.0004s

  INIT    time    0.000s  (  0.001s elapsed)
  MUT     time    2.297s  (  2.399s elapsed)
  GC      time    0.062s  (  0.015s elapsed)
  RP      time    0.000s  (  0.000s elapsed)
  PROF    time    0.000s  (  0.000s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time    2.359s  (  2.416s elapsed)

  %GC     time       2.6%  (0.6% elapsed)

  Alloc rate    36,737,710 bytes per MUT second

  Productivity  97.4% of total user, 95.1% of total elapsed

Before we have a look at the profile, we already see that something is amiss. For twice the maximum, your code takes almost 7 times the time: 0.375s for numbers up to 1000, and 2.297 seconds for 2000. That indicates that your algorithm doesn't have the right complexity to begin with. Let's check 4000:

$ echo 4000 | ./Primes +RTS -s -p
550
     302,844,912 bytes allocated in the heap
      70,455,392 bytes copied during GC
         431,144 bytes maximum residency (37 sample(s))
          36,976 bytes maximum slop
               2 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0       546 colls,     0 par    0.016s   0.093s     0.0002s    0.0006s
  Gen  1        37 colls,     0 par    0.031s   0.012s     0.0003s    0.0013s

  INIT    time    0.000s  (  0.001s elapsed)
  MUT     time   16.766s  ( 17.134s elapsed)
  GC      time    0.047s  (  0.105s elapsed)
  RP      time    0.000s  (  0.000s elapsed)
  PROF    time    0.000s  (  0.000s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time   16.812s  ( 17.240s elapsed)

  %GC     time       0.3%  (0.6% elapsed)

  Alloc rate    18,063,443 bytes per MUT second

  Productivity  99.7% of total user, 97.2% of total elapsed

For twice the elements, we have 8 times the time. This indicates that you have \$\mathcal O(n^3)\$ complexity.

An unhelpful profile

Let's have a look at the generated profile. In case you don't know GHC's profiling feature yet: -prof enables profiling during compilation, but you still need to tell GHC what to profile (in your code). -auto-all enables profiling of your functions without changing your code. And +RTS -p enables profiling at runtime.

This will create a .prof file. However, it's not very helpful, since most of your logic is in a list comprehension, and that's not profiled:

Sun Sep 11 08:24 2016 Time and Allocation Profiling Report  (Final)

       Primes +RTS -s -p -RTS

    total time  =       15.19 secs   (15193 ticks @ 1000 us, 1 processor)
    total alloc = 185,477,264 bytes  (excludes profiling overheads)

COST CENTRE  MODULE  %time %alloc

primes.sieve Main    100.0   99.9

                                                             individual     inherited
COST CENTRE     MODULE                     no.     entries  %time %alloc   %time %alloc

MAIN            MAIN                        44           0    0.0    0.0   100.0  100.0
 main           Main                        89           0    0.0    0.0   100.0  100.0
  primes        Main                        91           1    0.0    0.1   100.0  100.0
   primes.sieve Main                        92         550  100.0   99.9   100.0   99.9
 CAF            GHC.Read                    76           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Encoding.CodePage    73           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Encoding             68           0    0.0    0.0     0.0    0.0
 CAF            Text.Read.Lex               61           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Handle.Text          57           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Handle.FD            56           0    0.0    0.0     0.0    0.0
 CAF:main1      Main                        52           0    0.0    0.0     0.0    0.0
  main          Main                        88           1    0.0    0.0     0.0    0.0
 CAF:lvl5_r3TO  Main                        51           0    0.0    0.0     0.0    0.0
  main          Main                        90           0    0.0    0.0     0.0    0.0

We see that most of the work is done in primes.sieve. That's nothing new, though. We would like to see where the additional work happens. Remember that I said that we usually have to add profiling annotations (also called cost centers)? Now it's time to add them:

    sieve (p:xs) = p : sieve [multiple*p+offset
                             | multiple <- {-# SCC multiple #-} [1..(last xs) `quot` p]
                             , offset <- {-# SCC offset #-} [1..(p-1)]
                             , {-# SCC elem #-} multiple*p+offset `elem` xs]

Now let's see what takes all that time (and space):

    Sun Sep 11 08:35 2016 Time and Allocation Profiling Report  (Final)

       Primes +RTS -s -p -RTS

    total time  =       14.27 secs   (14270 ticks @ 1000 us, 1 processor)
    total alloc = 186,588,744 bytes  (excludes profiling overheads)

COST CENTRE  MODULE  %time %alloc

elem         Main     98.9   46.7
primes.sieve Main      0.7    9.4
offset       Main      0.4   43.3

                                                             individual     inherited
COST CENTRE     MODULE                     no.     entries  %time %alloc   %time %alloc

MAIN            MAIN                        44           0    0.0    0.0   100.0  100.0
 main           Main                        89           0    0.0    0.0   100.0  100.0
  primes        Main                        91           1    0.0    0.1   100.0  100.0
   primes.sieve Main                        92         550    0.7    9.4   100.0   99.9
    elem        Main                        95     1813869   98.9   46.7    98.9   46.7
    offset      Main                        94        9263    0.4   43.3     0.4   43.3
    multiple    Main                        93         549    0.0    0.4     0.0    0.4
 CAF            GHC.Read                    76           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Encoding.CodePage    73           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Encoding             68           0    0.0    0.0     0.0    0.0
 CAF            Text.Read.Lex               61           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Handle.Text          57           0    0.0    0.0     0.0    0.0
 CAF            GHC.IO.Handle.FD            56           0    0.0    0.0     0.0    0.0
 CAF:main1      Main                        52           0    0.0    0.0     0.0    0.0
  main          Main                        88           1    0.0    0.0     0.0    0.0
 CAF:lvl5_r3UH  Main                        51           0    0.0    0.0     0.0    0.0
  main          Main                        90           0    0.0    0.0     0.0    0.0

Let's focus on the new centers:

    elem        Main                        95     1813869   98.9   46.7    98.9   46.7
    offset      Main                        94        9263    0.4   43.3     0.4   43.3
    multiple    Main                        93         549    0.0

Wow. For 4000 elements, we have 1813869 elem checks. That's almost \$4000^{1.8}\$. Each of those elem checks is linear. While the size of the list decreases, at worst case it has size \$\mathcal O(n) \$. We end up with \$\mathcal O(n^{2.8})\$ complexity from our empirical point of view, which is really close to our real behaviour.

Prime time for efficiency

Now that we now that the elem checks destroy our runtime, and the creation of offset eats the other half of your RAM, let's get back to the drawing board and remember what Eratosthenes' Sieve is supposed to do:

You write down the numbers from 2 to \$n\$.
You start with the next number that you haven't looked at yet
If it's crossed out, take the next one
If it's not crossed out, cross all it's multiple out
Go to step 2, until you've run out of numbers

However, here's what you do:

You write down the numbers from 2 to \$n\$ (only the odds).
You start with the next number that you haven't looked at and that isn't crossed out yet
Put "maybe prime?" markers on all numbers that aren't multiples of it
Cross out all multiples of your number (all that don't have a marker; that step is implicit)
Go to step 2, until you've run out of numbers

The difference in step 3 is huge. For any number \$p\$, there are at most \$\lfloor \frac{n}{p} \rfloor\$ multiples in the range \$[1,n]\$. How many aren't? Well, \$n - \lfloor \frac{n}{p} \rfloor\$. And since \$p > 2\$, we will always check too many elements.

Now, let's change your sieve so that it actually implements the first algorithm:

    sieve :: [Integer] -> [Integer]
    sieve [] = []
    sieve [a] = [a]
    sieve (p:xs) = p : sieve [prime | prime <- xs
                                    , prime `rem` p /= 0]

Before I post the result, let us verify that this really does the same as yours: for a single \$p\$, you created a list of all non-divisible numbers that were also in xs. Therefore, you ended up with:

$$ \{x \in xs \} \cap \{n \in \mathbb N : n \neq 0 \mod p \}$$

Which is almost literally in the code above. Now for the result:

$ echo 4000 | ./Primes +RTS -s -p
2000
     339,984,336 bytes allocated in the heap
      24,834,416 bytes copied during GC
          89,728 bytes maximum residency (2 sample(s))
          27,736 bytes maximum slop
               2 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0       459 colls,     0 par    0.047s   0.040s     0.0001s    0.0003s
  Gen  1         2 colls,     0 par    0.000s   0.001s     0.0004s    0.0007s

  INIT    time    0.000s  (  0.001s elapsed)
  MUT     time    0.250s  (  0.290s elapsed)
  GC      time    0.047s  (  0.041s elapsed)
  RP      time    0.000s  (  0.000s elapsed)
  PROF    time    0.000s  (  0.000s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time    0.297s  (  0.332s elapsed)

  %GC     time      15.8%  (12.2% elapsed)

  Alloc rate    1,359,937,344 bytes per MUT second

  Productivity  84.2% of total user, 75.2% of total elapsed

Still too much garbage collection, but that's fine for a start.

Additional discussion

Try to avoid last. Instead, you could have used

multiples <- [i * p | i <- [1..nmax`quot`p]]

or similar. last has to traverse all the list.

Next, it's great that you've added type signatures, but make sure that you can actually need Integer. On your platform, Int will probably go up to \$2^{63}-1\$, which is more than enough. It will also make your program a lot faster, since Integer has an overhead.

And last but not least, make the code slightly more readable by adding whitespace. If you get a vertical scrollbar on CR, it's usually a sign that your lines are too long.

Oh, and by the way: this variant will still be too slow compared to Java, but you're probably using another data structure with random access abilities in Java, whereas we're creating a "new" list in Haskell all the time.

TL;DR

Verify that you actually implemented the algorithm that you want to implement.


If you were writing this for real world use1, I think the right way would be to use std::get_time and std::put_time, something on this order:

#include <iostream>
#include <iomanip>
#include <ctime>

int main() {
    struct std::tm t;
    std::cin >> std::get_time(&t, "%I:%M:%S%p");
    std::mktime(&t);
    std::cout << std::put_time(&t, "%H:%M:%S");
}

(Note: it's open to question whether the call to mktime is really necessary here, but at worst it's still pretty harmless).

Switch Statement

Looking more specifically at your code, the thing that probably sticks out the most is the big switch statement. I'd eliminate that in favor of a tiny bit of math:

if (ampm == "PM")
    hours += 12;

Reading Delimiters

Right now, the code to initially read the data is made somewhat ugly and unreadable (and arguably failure-prone) by it's somewhat poor handling of delimiters. It currently just reads a character and assumes it's a delimiter. In real life, you probably want to at least compare what you read to what you expected so ensure that the input is correctly formatted (and react appropriately if it's not).

Personally, I think I'd write a little operator overload like this:

std::istream &operator >> (std::istream &is, char const *pat) {

    char ch;
    while (isspace(static_cast<unsigned char>(is.peek())))
        is.get(ch);

    while (*pat && is && *pat == is.peek() && is.get(ch))
        ++pat;

    // if we didn't reach the end of the pattern, matching failed (mismatch, premature EOF, etc.)
    if (*pat) {
        is.setstate(std::ios::failbit);
    }

    return is;
}

At least to me, this supports much cleaner code to read the data:

cin >> hour >> ":" >> minute >> ":" >> second >> ampm;

...and the operator overload takes care of reading data, comparing to what was passed, and setting the stream's failbit if it didn't match. As it stands right now, I've also included skipping any leading white-space like normal extraction operators do, but it would be trivial to eliminate that if you didn't want it (but it shouldn't make any difference for solving the HackerRank problem).

1. HackerRank is apparently using an old/broken standard library, so it won't accept this, even when you try to tell it you want to use C++14.


Dining philosophers problem with mutexes

In the problem as I have seen it, the philosophers only take one fork at a time and can hang on to it (but they only eat when they have 2 forks). You have simplified it by having them take both or none.

There shouldn't be any deadlocks as the philosopher only has 0 or 2 forks, but there is still potential for starvation if the 2 neighbouring philosophers start eating again before the philosopher has finished thinking.


matplotlib fixing axis scale and alignment

If you want to get rid of the global t you could consider creating a class to manage the data and updating. I quickly whipped something together, although I'm not well versed enough in stats to have a good idea about what names would be more appropriate.

from functools import lru_cache

import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

#probability density function generator: chached
@lru_cache # beacuse it redraws each time
def get_pdf(mu, sigma=1, offset=4):
    o = sigma * offset
    x = np.linspace(mu - o, mu + o, 100)
    rv = ss.norm(mu, sigma)
    return x, rv.pdf(x)

# This simple class will hold the reference to `t` so that it doesn't need to
# be a global
class Data():
    '''
    A simple class that plots data on an axis and contains a method for updating
    the plot.
    '''

    def __init__(self, ax, **properties):
        self.properties = properties
        self.t = ax.fill_between(*get_pdf(2), **properties)

    def update(self, val):
        x, y = get_pdf(val)
        self.t.remove()
        self.t = ax.fill_between(x, y, **self.properties)
        fig.canvas.draw_idle()

# Generate the figure and axis for our widget

fig, ax = plt.subplots()
# added the subplot for bottom margin and the slider, since its also the ax
plt.subplots_adjust(bottom=0.25)

# add a slider widget
slider = widgets.Slider(
    # ax position are absolute, should be easy without subplot may be
    ax      = plt.axes([0.25, 0.1, 0.5, 0.03]),
    label   = "shift",
    valmin  = -5,
    valmax  = 5,
    valinit = 2,
    valstep = 0.5
)

# add a reference distribution *A*
ax.fill_between(*get_pdf(0), label='A', alpha=0.7)
ax.set_xlim(-10, 10)
ax.set_ylim(0, 1)

# Create a data instance
properties = dict(label='B', color='crimson', alpha=0.7)
data = Data(ax=ax, **properties)

# link data update method to slider.on_changed
slider.on_changed(data.update)
ax.legend()
plt.show()

```


Get RSS feeds and store them into database

When using defn, the docstring goes before the arguments list, not after.

In order to prevent environment coupling, functions that use a db should accept it as an argument instead of accessing it via a Var. This may seem like an inconvenience, but it will yield much more maintainable code.

You should also improve the naming :) names likes construct-foo or process-feed are not very explicit.


Your Question

Is there the better way to add a function to the option "buttons" to get the data and to go to a new dialog?

I don't believe there is a "better" way, though instead of using an object for the buttons option, an array could be utilized, which would allow more customization of the buttons. For example, the submit button could have a custom icon added to it and more custom event handlers, like mouseenter. See the code snippet at the end of this post for an example.
Feedback
Elements without ids
Your example contains only one form input (i.e. <input type="text" name="">), though it is typically rare to only have one form input. As soon as other text/radio/checkbox inputs are added, the way that is referenced in JavaScript will need to change. I would advise you to always add an id attribute to the elements and use those when referencing them in the JavaScript. So that text input could have an id attribute like id="username". Then the JavaScript can reference it using that attribute: $('#username').val().
The same is true for the  element that gets set with the text entered by  the user. It would be wise to also give that element an id attribute and use it in the JavaScript code. This actually would prevent the title of the message dialog from getting updated with the name (see screenshot below).

That happens because $('span') matches multiple elements, including the header of the message dialog and the element that follows "Hello, ", and then .text() updates all of those matching elements.
jQuery DOM ready callback
It is best to wrap the jQuery code in a function called when the DOM is ready. Traditionally that was done with $.ready() but in the latest versions that is deprecated, in favor of the $(function() {...}); syntax. That way, all variables will have limited scope instead of being global variables (i.e. on window).
jQuery references
It is wise to store DOM look-ups (e.g. $('#message')) in a variable (or actually, a constant would be semantically better, though browser support can be an issue there...), since  those can be expensive.
So for example:

$("input").val()

could be replaced with
usernameInput.val();

if a line like the following is added at the beginning of the script:
const usernameInput = $('#username');

For more tips like these, I suggest reading this article. I know it is 3 years old and bashes jQuery in the beginning but there are some really useful tips there.

$(function() { //DOM ready callback
    //store references in DOM
    const usernameInput = $('#username');
    const usernameDisplay = $('#username_display');
    //store a reference to the message dialog
    const messageDialog = $("#message").dialog({autoOpen: false});
    const formDialog = $("#form").dialog({
        autoOpen: false,
        modal: true,
        title: "What is your name?",
        buttons: [{
            text: "submit",
            icon: "ui-icon-contact",
            mouseenter: function() { //when user starts to hover over button
                $(this).effect('shake', 'swing', 100);
            },
            click: function() {
                $( this ).dialog( "close" );
                messageDialog.dialog("open");
                var str = usernameInput.val();
                usernameDisplay.text(str);
            }
        }]
    });
    $("#btn").click(function(){
        formDialog.dialog("open");
    });
})

<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

<button id="btn">Click me</button>
    <form id="form">
        <input type="text" name="" id="username">
    </form>

Hello, !


One more algorithmic approach could be to use a different object model more closely relating to the actual cube. That is instead of keeping the state of faces, keep the state of each part of the cube, i.e.The 8 corner pieces of a 2x2x2 cube, and then keep track of the state of each of these, and then have methods to handle the cube and to get the different faces based on the pieces.

If you do this kind of modelling, then your code would also expand easily to larger cube dimensions, as the general movement methods would/should be generic and be applicable to any dimension of the cube.

Edit: Added pseudo code

As always when approaching a problem you need to visualise and simplify into something you are able to comprehend and code. Some givens for this particular problem:

The cube is 3D, but at any given time you are only revolving one plane/face of the cube
When revolving any given face, pieces keep their internal place in that face, albeit the global position has changed, i.e. the corner piece remains the corner piece, but the top-left corner piece could become the top-right corner piece
All pieces in a plane is related and will move as one
For a 2x2x2 cube, use positions from [0, 0, 0] through [1, 1, 1], where [0, 0, 0] is the bottommost, leftmost, frontfacing piece

How does this help us? Well, one can define and code the 2d operations available, and apply them to the cube, which in turn applies them to each piece in turn. Lets define the operations as Rot + Plane  + Direction, where Plane can be X, Y, and Z, and direction is either CW - Clockwise or CCW - CounterClockWise. Operations then become: RotXCW, RotXCCW, RotYCW, and so on. But we need to know which of n=2 planes we're rotating, so lets pass that as an argument.

In order to execute the operation RotXCW(1) on the cube, that is rotate the face to the right clockwise, we need to loop through all pieces having x==1, and call RotXCW on each piece:

Change piece orientation correctly
Let the piece calculate its own position:

        x = prevX
        y = ( prevZ == 0 ) ?    0  : (n-1)
        z = ( prevY == 0 ) ? (n-1) :    0

  To find the new position I wrote down all combinations based on previous position, and looked for the easiest way to represent this acknowledging that the coordinate of a corner piece is always 0 or n-1. Here is the table for rotating clockwise:

  Old Z   Old Y     New Z   New Y
    0      0     >     1      0
    1      0     >     1      1
    1      1     >     0      1
    0      1     >     0      0

  This table leads to implementation given that the new Yis the previous Z, and the new Z is the opposite of the previous Y

In order to implement this you need a Cube class of dimension n, and this concists of Piece's which has a position, and an orientation. Both classes needs to have rotational methods, and in addition you need a method to display the face, and rotate the face of a given piece.

Hopefully this should give you enough to start coding. It might seem heavy, but isolating and diving the concern into handling single pieces will, in my experience, be well worhth it. Now you can call the rotation operation on the cube, and the single concern of that method is to call rotate on the pieces.