Implementing min of 3 numbers in Mic-1 code

Min... ish

  Is there a better or shorter way I can find a min of three numbers in Mic-1?

Maybe, but first you should be finding the min of three numbers because right now, that's not what is happening.

This is what your current assembly code looks like translated to a pseudo-code:

ac = OP1
ac -= OP2
if ac > 0, return OP1
ac -= 3
if ac > 0, return OP1
return OP1

Try following this through with some example numbers. Still don't understand where you are going wrong? Look at this example again with some mo

; OP1 = 3, OP2 = 2, OP3 = 1
ac = 3
ac -= 2 ; ac is now 1
; ac is > 0, so jump passes and OP1 is returned when OP3 should be instead

See it now? This was probably overlooked due to the fact that you did not thoroughly test your code. It is important to test even the most extreme cases to make sure that your code is cleaned.

Now we need to re-write your code. First off, let's break down your code: instead of trying to find the min of just three numbers, why not try to find the min of two numbers? Then, this subroutine could be used in other min-based subroutines.

I think that the min subroutine would now look like this:

min2:
    LODL 1 ; ac = OP1
    SUBL 2 ; ac -= OP2
    JPOS min2_op2small ; if ac > 0

    LODL 1
    RETN
op2small:
    LODL 2
    RETN

If you are having trouble understanding how this works, try plugging in some values in your head. Here is a run down of what it is doing

Store OP1 in the accumulator.
Subtract OP2 from the accumulator.
If the accumulator is negative, then return OP1.
If the accumulator is positive, then return OP2.

Now that we have this basic min subroutine, we can the subroutine for finding the min of 3 numbers.

Using our handy-dandy min2 sub, this new subroutine can simply use the min2 sub to determine what is the greater of the three values:

Find the min2 of OP1 and OP2
Compare the lesser one with OP3
Return the lesser one.

Your current code already follows this structure. However, as show above, it doesn't quite do what it seems.

Comments

You seem slightly confused about how this "architecture" works, judging by your comments. In particular, these ones:

  SUBL 2; OP2 - OP1
  ...
  SUBL 3; OP3 - OP1

No; you aren't subtracting 1st parameter from the 2nd and 3rd ones here. In reality, these two statements are the equivalent of

  \$(OP1-OP2)-OP3\$

Why is it like this and not how you have indicated it? Here is what your code is doing, minus the conditionals:

Load the accumulator with OP1
Subtract OP2 from the accumulator.
Subtract OP3 from the accumulator.

The accumulator is a register that is used to hold a single value that is often the result of arithmetic. More simple instruction sets (such as this one) force any arithmetic to be done with one of the operands being the accumulator.

See what the difference is? Your comments seemed to act as if there were no conditional whatsoever. More accurate comments would be:

SUBL 2; ac = OP1 - OP2
...
SUBL 3; ac = (OP1 - OP2) - OP3


I think that you have an issue with general approach you have chosen. StateManager can still be improved tho.

Use better and consistent naming. Why _onCompletion but _nextOnComplete? Why _nextState, but _lastState (shouldn't it be "previous"?)? Why ChangeState() when it doesnt change the current state, but sets the next state instead (i'm not sure i understand why it changes last state as well)? What IsCompleted() does? Does it actually checks for completion (then the name is fine) or does it retrieves the result of operation (then it could use a better naming)? Looks like it is the latter. It should be a property either way. Minor stuff like that improves code readability by a lot.
Delegates are clearly coupled with states, so, if for some reason you can not refactor them into events of IState, you can implemet some aggregator-object:

private class StateInfo
{
    public IState State { get; set; }
    public StateCompletion OnExecuted { get; set; }
}

and then instead of

_onCompletion = _nextOnComplete;
_currentState = _nextState;

use _currentStateInfo = _nextStateInfo. This will reduce the number of fields and assignments.
I dont see an issue with _currentState.CheckStateModifiers();. Repeated code should be dealt with by extracting common logic to the base class (StateBase?).
I'm not sure _currentState.Enter (state entering object) makes much sense. Shouldn't object enter state and not vice versa?

It's hard to tell more without knowing implementation details and the logic you need to implement.


This class is... problematic. It is not thread safe at all. It has a mix of 3 different concurrency tools, and each of them has problems.

Volatile

volatile is almost always a bug. If you think you should be using volatile, you are wrong (almost always). Textbooks like to cover volatile, but "in the wild" it is about as common as the Sasquatch (clever pun there...).

In your code, for example, beginTime is only ever accessed from inside synchronized methods, so why is it volatile?

Atomics

You use AtomicLong to keep the lap time, but you have a race condition:

public void lap() {
    long lap = timeElapsed(lastLap.longValue());
    lastLap.addAndGet(lap);
    getLaps().add(toMilliseconds(lap));
}

In here, two threads may call lap() at about the same time. The first thread may get lastLap.LongValue() and convert it to lap. It may then pause there. The next thread may get the lap too, and call addAndGet(lap). The first thread may then overwrite the previous thread's value with the older lap. Then, both threads may get the laps List, and try to simultaneously add their lap values to the same synchronized ArrayList... the order they are added is unpredictable, but, for sure, you may end up with two really long laps, instead of a long one and a short one.

Atomics are atomic... they do not prevent race conditions (they just give a way to identify and handle them).

Synchronization

Here you have done a half-OK job. You are synchronizing on two methods, but you should be synchronizing on more.

I would recommend you throw away all the other concurrency tricks, and use only synchronization.

Believe it or not (you will believe it if you test it), synchronization blocks can be really really fast, and as a result, concurrency is still PDQ (Pretty Damn Quick).

So, with the following code, let me point out some things:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StopWatch {

    private long beginTime = 0;
    private long[] laps = new long[1 << 4];
    private int lapCount = 0;

    private final Object sync = new Object();

    public void start() {
        synchronized(sync) {
            if (beginTime != 0) {
                // already started
                return;
            }
            beginTime = System.nanoTime();
            laps[lapCount++] = beginTime;
        }
    }

    public long timeElapsed() {
        synchronized(sync) {
            if (beginTime == 0) {
                return 0;
            }
            return toMilliseconds(System.nanoTime() - beginTime);
        }
    }

    public void lap() {
        synchronized(sync) {
            if (beginTime == 0) {
                return;
            }
            if (lapCount == laps.length) {
                laps = Arrays.copyOf(laps, lapCount + (lapcount >> 1) + 8);
            }
            laps[lapCount++] = System.nanoTime();
        }

    }

    public void reset() {
        synchronized(sync) {
            beginTime = 0;
            lapCount = 0;
        }
    }

    public List<Long> getLaps() {
        long[] times;
        synchronized(sync) {
            times = Arrays.copyOf(laps, lapCount);
        }
        List<Long> data = new ArrayList<>(times.length);
        for (int i = 1; i < times.length; i++) {
            data.add(toMilliseconds(times[i] - times[i - 1]));
        }
        return data;
    }

    private long toMilliseconds(long nano) {
        return nano / 1000000;
    }

}

I use a dedicated object sync to lock on to. This prevents someone from using my instance as a lock for their synchronization needs, and breaking my class. E.g., with your code, if someone did:

Stopwatch sw = new Stopwatch();

.....

synchronized(sw) {
    Thread.sleep(10000);
}

That code would make your methods block in other threads...
I have no volatiles or atomics... only synchronized.
I use primitives, and arrays to store the data. This is fast, and reduces memory usage.
I don't do any math in the time-sensitive methods. All I do is store away the System.nanoTime(). The math is all done in the get methods, and outside of the synchronized blocks.

Conclusion

Mixing concurrency strategies is bad.
synchronization is normally more than enough for most needs
atomics are atomic, not thread safe. Atomics provide mechanisms to identify race conditions, not avoid them.


What you want to do, is use early-returns (FTW). Also, let the formatter do the string work for you. Right tool for the job.

Consider your code, rewritten in Ideone...:

static string FormatRushTime (TimeSpan span)
{
    if ( span.Days != 0 )
    {
        return String.Format("{0:d}d {1:d}h", span.Days, Math.Abs(span.Hours));
    }
    if ( span.Hours != 0 )
    {
        return String.Format("{0:d}h {1:d}m", span.Hours, Math.Abs(span.Minutes));
    }
    if ( span.Minutes != 0 )
    {
        return String.Format("{0:d}m {1:d}s", span.Minutes, Math.Abs(span.Seconds));
    }
    return String.Format("{0:d}s", span.Seconds);
}


Pad a ragged multidimensional array to rectangular shape

nested methods

Why do you nest the get_max_shape etcetera in the pad? There is no need to do this.

get_max_shape

Here you use recursion and a global variable. A simpler way would be to have a generator that recursively runs through the array, and yields the level and length of that part, and then another function to aggregate this results. That way you can avoid passing

def get_dimensions(array, level=0):
    yield level, len(array)
    try:
        for row in array:
            yield from get_dimensions(row, level + 1)
    except TypeError: #not an iterable
        pass

[(0, 3), (1, 3), (2, 3), (2, 1), (2, 2), (1, 1), (2, 1), (1, 2), (2, 2), (2, 1)]

The aggregation can be very simple using collections.defaultdict:

def get_max_shape(array):
    dimensions = defaultdict(int)
    for level, length in get_dimensions(array):
        dimensions[level] = max(dimensions[level], length)
    return [value for _, value in sorted(dimensions.items())]

[3, 3, 3]

creating the result

Instead of r = np.zeros(dims, dtype=dtype) + pad_value you can use np.full

You iterate over all possible indices, and check whether it is present in the original array. Depening on how "full" the original array is, this can save some time. It also allows you to do this without your custom get_item method to get the element at the nested index

def iterate_nested_array(array, index=()):
    try:
        for idx, row in enumerate(array):
            yield from iterate_nested_array(row, (*index, idx))
    except TypeError: # final level
        for idx, item in enumerate(array):
            yield (*index, idx), item

[((0, 0, 0), 0),
 ((0, 0, 1), 1),
 ((0, 0, 2), 2),
 ((0, 1, 0), 3),
 ((0, 2, 0), 4),
 ((0, 2, 1), 5),
 ((1, 0, 0), 6),
 ((2, 0, 0), 7),
 ((2, 0, 1), 8),
 ((2, 1, 0), 9)]

slice

an even better way, as suggested by@hpaulj uses slices:

def iterate_nested_array(array, index=()):
    try:
        for idx, row in enumerate(array):
            yield from iterate_nested_array(row, (*index, idx))
    except TypeError: # final level
        yield (*index, slice(len(array))), array

[((0, 0, slice(None, 3, None)), [0, 1, 2]),
 ((0, 1, slice(None, 1, None)), [3]),
 ((0, 2, slice(None, 2, None)), [4, 5]),
 ((1, 0, slice(None, 1, None)), [6]),
 ((2, 0, slice(None, 2, None)), [7, 8]),
 ((2, 1, slice(None, 1, None)), [9])]

padding

def pad(array, fill_value):
    dimensions = get_max_shape(array)
    result = np.full(dimensions, fill_value)
    for index, value in iterate_nested_array(array):
        result[index] = value
    return result

array([[[ 0,  1,  2],
        [ 3, -1, -1],
        [ 4,  5, -1]],

       [[ 6, -1, -1],
        [-1, -1, -1],
        [-1, -1, -1]],

       [[ 7,  8, -1],
        [ 9, -1, -1],
        [-1, -1, -1]]])


Unpacking
Try this rather than hard-coded indexing:
    user, password, host, port, database = db_credentials
    connection = psycopg2.connect(user, ...)

Or, if you're able to rearrange those parameters such that they match those of the connect signature:

dbname – the database name (database is a deprecated alias)
user – user name used to authenticate
password – password used to authenticate
host – database host address (defaults to UNIX socket if not provided)
port – connection port number (defaults to 5432 if not provided)

then you can simply do
connection = psycopg2.connect(*db_credentials)

Logs
Consider replacing
    print("Trying")
    print("connected")

with calls to the actual logging module, which is more configurable and maintainable.
Quote escapes
'The name that was given to cardbot didn\'t exist in the card table.'

can be
"The name that was given to cardbot didn't exist in the card table."

In-application queries
Your join_table_query is long. There are several approaches to improve this - either save a view in the database (my favourite), or a stored procedure (common but I think it's overkill in this case).
Injection

the bot is protected from any direct sql injections before I deploy it

This is directly vulnerable:
'''... WHERE card.name = ('%s') ''' % (recordName)

Never (ever) use string formatting to insert parameters to a query. All DB connection libraries have anticipated this concern and most approach it using "prepared statements".
This article is old but relevant. The actual reference shows that you should be passing vars as a sequence or a mapping, which will prevent injection.


Encode unicode codepoints to UTF-8 manually

Yes, the code is correct for all valid code points. I was first confused about the double shifts, since I have never seen them before, but they do their job well. Other authors typically do a single >> followed by a bit mask, e.g. (codepoint >> 12) & 0x3F to skip the 12 bits to the right and take the next 6 bits. That way, the numbers can be verified more easily, since they are smaller. Plus, all the 01xxxxxx bytes have the same bitmask.

Your code omits some validity checks:

codepoint could be < 0
codepoint could be between 0xD800 and 0xDFFF

Other than these, it is perfect.

I know for sure that this conversion is built-in into C#, I just don't know where. Try loading a file into a string using the UTF-8 encoding. During that loading, the built-in conversion code gets called.


Naive JS implementation of tidyr's gather function

First, I would be concerned about the performance of your three consecutive map operations followed by reduce, particularly as the size of data grows in terms of number of items in array.

Right now, you have to iterate data 4 times to complete all those operations.  While the 3x mapping operation probably does provide some clarity to the operations by breaking them down to simple transformation steps, I would consider creating a single map callback that could complete all steps of transformation on an item in one pass, minimizing repetitive iteration of the array.  Of course you would probably want to run some performance tests for your expected use cases to understand the performance trade-offs here.  It might be that a usage pattern like the following makes sense:

data.map( record => {
    // mapping step 1
    // mapping step 2
    // mapping step 3
    return mappedRecord;
}

Maybe the usage example you show is not very meaningful, but I am having a hard time understanding function signature for gather().

What is the difference between the two key and value labels parameters and the columns specified passed from columns array parameter?
The signature does not make it clear to me as to which fields in the input data are to be assigned to the Letter and Value properties (for this example) in the output array.
The parameter naming doesn't seem to make sense.  Why is one called key_label and one called value_label when both are used as keys in the output structure?
From looking at this signature, how is one to determine what the logic is that is to be applied in "splitting" apart the input records?

Do the with_fields() and split_record() methods have any value outside the context of the gather() function?  If not, consider nesting them inside gather as "private" functions only in context of gather();

Stylistically:

I don't like your use of snake_case in javascript, as it is common practice in JS world to use camelCase.
Consider sticking to comments before lines of code to they apply, rather than using commments at the end of the line (which I generally avoid, as I feel they make code harder to read).
There are a few cases where variable naming is not that meaningful - without_f, with_f.  Dropping a few characters from a variable is oftentimes not worth the value you get from having clearly understandable variable names.
When you get a more complex or longer return operation on an arrow function, you might consider using bracket syntax and/or line breaks to make the code easier to read.

For example:

.map(([left, right]) => right
  .map(long_pair => Object.assign({}, long_pair, left)))

Could become:

.map(([left, right]) => {
    return right.map(
        long_pair => Object.assign({}, long_pair, left)
    );
});

// or
.map(
    ([left, right]) => right.map(
        long_pair => Object.assign({}, long_pair, left)
    )
 );

To me, this makes it much clearer that there is a nested mapping operation happening here. This is much easier than trying to count/balance opening closing parenthesis in your head as one might have to do when looking at original code that ends with three closing parenthesis in a row.


The indentation isn't always consistent, e.g. the using scope in DeepClone should be indented a level.

Get property should probably be named Instance (a noun), or remain Get (a verb) and be turned into a method. The private and not implemented setter is sloppy, and the = null initialization of the backing private field is redundant.

Seems the restore mechanics are written with a specific UI in mind, where the UI immediately saves changes - typically a settings dialog would do something when the user confirms or applies modifications; seems your model is the other way around - the changes are saved unless they're cancelled, so cancelling changes requires work... seems backwards.

I'd remove that cloning and restore functionality, and make the UI work differently, off a ViewModel - not directly with the settings; when the dialog is cancelled, you have nothing to revert or restore (no changes were made), and when the dialog is okayed and/or changes are applied, then you persist the changes using your settings service.

I think a Singleton isn't needed for this, provided that the rest of the code isn't responsible for newing up anything; if you make that responsibility the job of an IoC container, then it's child's play to configure it in such a way that any class with an ISettingsService constructor parameter will always receive the same instance of whatever concrete type implements that interface - that's OOP with Dependency Injection at play, and static members don't play very well with OOP (static members belong to the type, not to an object), so the more of it you have in your code base, the more coupling you have everywhere between unrelated classes...


Looping through an array of strings containing approximately 3 million elements

Well you can optimize FileContains very simply - stop calling Text.ToLower() on every iteration!

In fact, at that point it's really simple to rewrite. Here's the code for the original question, which didn't have the Substring part:

public static bool FileContains(string text)
{
    // Variable name changed to save my eyes from the horror.
    return lines.Contains(text.ToLower());
}

If you store the lines in a HashSet<string> instead of an array or a list, it will be blazingly fast.

With the Substring part, I'd create a new HashSet<string> with just those substrings, assuming you want to look up more than once:

HashSet<string> lineStarts;

...

lineStarts = new HashSet<string>(lines.Select(x => x.Substring(0, x.IndexOf('|'));

Then use lineStarts within FileContains.

Note that using ToLower is a fairly crude approach to case sensitivity. You should think carefully about what this needs to do in terms of culture-sensitivity etc. See the relevant MSDN page for lots more information. (Ain't culture fun?)


Nitpick: map!(s => s.toStringz)(argv) would be more idiomatic as argv.map!toStringz. Apart from that, your code looks very much correct. It should work as expected, and is indeed the way to do this.


What do you think about my implementation? Is is done in a basically correct way?

Yeah who is to say what is "correct"? I mostly have worked with the chaiJS spies API and it feels like a basic version of that library.

  I'm I using the ES6-features (Classes, Rest, Spread) right?

While there isn't much to the code, I would say it looks like those features are used correctly. You could consider using more class features like getters and setters

In the constructor, there exists this line:

this.result = null;

but the result property doesn't appear to be used anywhere. What is that for?


Convert a Binary Tree to Doubly Linked List

Algorithm: because of the recursion, it still doesn't qualify as in-place. Consider a variation on a Morris traversal theme.

The calls to first() and last() are detrimental to the performance. Meanwhile, the callee already computed them. Consider returning a (fake) node pointing the beginning and the end of the flattened subtree, along the lines

    left = flatten(root.left);
    right = flatten(root.right);

    left.right.next = root;
    root.left = left.right;

    right.left.left = root;
    root.right = right.left;

    return Node(left.left, right.right);

There is only \$O(h)\$ Nodes to exist at any given moment, so the space complexity is not compromised.


Rearrange page numbers for printing a book

Style

Your code is not too far from following PEP8 and you know PEP8: it would have been a nice touch for volunteer reviewers to provide a piece of code even closer to what they expect. You'll find various tools (online or not) to check more or less precisely the compliancy of your code to PEP8. For most points, once you get used to it, it doesn't take any longer to apply as as you write the code.

Float ?

The following piece of code

pages = float(input("How many total pages is the book?"))

seems to imply that pages could be a float. As far as I can tell, this value corresponds to a number of page and an int would be more appropriate. Also, to be sure, I've tried giving a 0.5 value and the code is stuck in a loop.

Code organisation

Your code is the perfect example of a piece of code that could have been written as a clear function: input and output are both well-defined. Once you're done, you can even write unit-tests for it. Then, the code calling your function could be behind an if __name__ == "__main__": guard.

You'd get something like:

def page_order(pages):
    num_booklets = pages/32
    if (pages < 32):
        num_booklets = 1
    pages_per_booklet = int(pages/num_booklets)
    last_booklet = int(pages%32)

    f = 1               #first page of the book
    n = int(pages_per_booklet)  #last page of the first booklet
    k = 1               #number of booklets completed
    print_order = []

    while (len(print_order) < pages):
        while ((len(print_order) < pages_per_booklet*k)
        and (len(print_order) < pages)):
            print_order.extend([n, f, f+1, n-1])
            n -= 2
            f += 2
        k += 1
        n = pages_per_booklet * k
        f = 1 + (pages_per_booklet*(k-1))
        if ((len(print_order)+pages_per_booklet) > pages):
            n = int(pages)
            f = int(pages) - last_booklet
    return (print_order)

tests = {
    0: [],
    1: [1, 1, 2, 0],
    2: [2, 1, 2, 1],
    3: [3, 1, 2, 2],
    4: [4, 1, 2, 3],
    5: [5, 1, 2, 4, 3, 3, 4, 2],
    6: [6, 1, 2, 5, 4, 3, 4, 3],
    7: [7, 1, 2, 6, 5, 3, 4, 4],
    8: [8, 1, 2, 7, 6, 3, 4, 5],
    9: [9, 1, 2, 8, 7, 3, 4, 6, 5, 5, 6, 4],
    10: [10, 1, 2, 9, 8, 3, 4, 7, 6, 5, 6, 5],
    11: [11, 1, 2, 10, 9, 3, 4, 8, 7, 5, 6, 6],
    12: [12, 1, 2, 11, 10, 3, 4, 9, 8, 5, 6, 7],
    13: [13, 1, 2, 12, 11, 3, 4, 10, 9, 5, 6, 8, 7, 7, 8, 6],
    14: [14, 1, 2, 13, 12, 3, 4, 11, 10, 5, 6, 9, 8, 7, 8, 7],
    15: [15, 1, 2, 14, 13, 3, 4, 12, 11, 5, 6, 10, 9, 7, 8, 8],
    16: [16, 1, 2, 15, 14, 3, 4, 13, 12, 5, 6, 11, 10, 7, 8, 9],
    17: [17, 1, 2, 16, 15, 3, 4, 14, 13, 5, 6, 12, 11, 7, 8, 10, 9, 9, 10, 8],
    18: [18, 1, 2, 17, 16, 3, 4, 15, 14, 5, 6, 13, 12, 7, 8, 11, 10, 9, 10, 9],
    19: [19, 1, 2, 18, 17, 3, 4, 16, 15, 5, 6, 14, 13, 7, 8, 12, 11, 9, 10, 10],
}

if __name__ == "__main__":
    if False:  # Interactive
        pages = int(input("How many total pages is the book?" ))
        print(page_order(pages))
    else:  # Automatic tests
        for inpu, expected_val in tests.items():
            res = page_order(inpu)
            if res != expected_val:
                print(inpu, res, expected_val)
        print("DONE")

divmod

When you perform both a division and a modulo operation with the same values, you can use the more concise and faster divmod builtin function.

def page_order(pages):
    num_booklets, last_booklet = divmod(pages, 32)
    if pages < 32:
        num_booklets = 1

Then I do not understand enough what your code is trying to achieve to try to be able to help more. For the time being, the code looks like:

def page_order(pages):
    num_booklets, last_booklet = divmod(pages, 32)
    if pages < 32:
        num_booklets = 1
    pages_per_booklet = pages/num_booklets

    f = 1  #first page of the book
    n = pages_per_booklet  #last page of the first booklet
    k = 1  # number of booklets completed
    print_order = []

    while len(print_order) < pages:
        while len(print_order) < min(pages, pages_per_booklet*k):
            print_order.extend([n, f, f+1, n-1])
            n -= 2
            f += 2
        k += 1
        n = pages_per_booklet * k
        f = 1 + (pages_per_booklet*(k-1))
        if len(print_order) + pages_per_booklet > pages:
            n = pages
            f = pages - last_booklet
    return print_order


Detecting the total amount of RAM installed on a hardware from a Linux system using a POSIX shell script

Using sudo can be problematic within scripts.  It's really designed to be used interactively, and may request a password (which won't work very well if its standard input isn't a terminal).  The alternative is to require the script to be run as a suitably privileged user, and I can see that you want to minimise the amount of privileged code.

I couldn't initially find an unprivileged way to do what dmidecode - it inspects /sys/firmware/dmi/tables/DMI which is unreadable by ordinary users and I don't see the same information anywhere else in sysfs.  However, lshw can produce a total RAM summary without privilege (but can't see the individual DIMMs).  After a bit of tracing, it seems that it reads from /sys/devices/system/memory - multiply the contents of block_size_bytes (in hexadecimal) by the total of */online to get the total RAM size in bytes:

printf '%c' /sys/devices/system/memory/memory*/online | wc -c |
    dc -e '16i' -f /sys/devices/system/memory/block_size_bytes -e 'Ai ? *p'

If coreutils is available (almost all Linux systems, I think; certainly as likely as sed or awk and much more so than dmidecode), then we can use the numfmt utility to convert that number to a friendly human form:

numfmt --to=iec-i --format='%.1f%f' --suffix B

(see the man page to understand the options, and adjust to taste).

Full working alternative

#!/bin/sh

printf 'Total RAM installed = '
printf '%c' /sys/devices/system/memory/memory*/online | wc -c |
    dc -e '?16i' -f /sys/devices/system/memory/block_size_bytes -e '*p' |
    numfmt --to=iec-i --suffix B

As a bonus, this is much faster than using dmidecode (which seems to gather all its information even when printing only a small subset).

Other points:

I recommend setting -e and -u in all shell scripts (both are specified in POSIX):

set -eu

Don't pipe through grep and awk - since the latter does regexp matching, just add a pattern to the awk program:

dmidecode --type 17 | awk '/^[[:space:]]*Size: [0-9]/ { print $2 }'

Including a digit in the pattern eliminates the empty slots neatly at that stage, so obviating is_number.
Counting using sprintf|wc is a little safer if you use %c or %.1s conversion; that uses just the first letter, so you can count using wc -c and avoid double-counting strings with embedded newlines (for example, see my worked code).  You won't get the problem lines here, but it's a technique worth knowing.
Instead of iterating through the indices of $ram_entries and repeatedly invoking sed to extract individual lines, it's better to check that it's safe to expand without quotes (we know this to be true, since we've ensured it contains only decimal numbers), and then simply for ram_entry in $ram_entries.

Even better, instead of capturing and assigning to a variable, we could pipe into a while read loop to process each line.  Be careful to make the loop be in the main shell, not a sub-shell, though, or make it communicate the result out.


Is it an anti-pattern to let ViewModel fill itself from a domain object?

It's not an anti pattern. At some point, one layer must know about the layer underneath. You also don't want to rewrite view-model mapping code in multiple controllers or actions, nor do you want to introduce another layer to do the mapping for you. Instead, I opt for constructor injection.

The part of your code I do think is an anti pattern, or incorrect architecture, would be your view model having access to the data access layer.

Your last example using constructor injection will provide the least coupling and most code reuse:

public class EditEmployeeViewModel
{
    public EditEmployeeViewModel(Employee employee)
    {
        Id = employee.Id;
        // ...
    }
}

I would not include the reverse mapping in your view model, where you update an Employee domain model from the EditEmployeeViewModel object. Instead, I would opt for a command or service object to do this work, which would have access to the data access layer:

public class CreateEmployeeCommand
{
    public CreateEmployeeCommand(IEmployeeRepository repository, EditEmployeeViewModel model)
    {
        this.repository = repository;
        this.model = model;
    }

    private EditEmployeeViewModel model;
    private IEmployeeRepository repository;

    public void Execute()
    {
        if (repository.FindBySSN(model.SocialSecurityNumber) != null)
        {
            // cannot add duplicate employee
        }

        Employee employee = new Employee()
        {
            FirstName = model.FirstName,
            LastName = model.LastName,
            SocialSecurityNumber = model.SocialSecurityNumber,
            // ...
        };

        repository.Create(employee);
    }
}

Your controller becomes simplified. The key here is your data access layer should be created and destroyed at the controller level, not the command level. The controller should be controlling the transaction:

public class EmployeesController : Controller
{
    public ActionResult Create(EditEmployeeViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        using (IEmployeeRepository repo = new EmployeeRepository())
        {
            var command = new CreateEmployeeCommand(repo, model);

            command.Execute();

            repo.Commit();
        }

        return RedirectToAction("Index");
    }
}


Running a given command after each change in a file

class Loop(object):

Loop isn't a very descriptive name for this object. Something like WatchDog or FileWatcher would make more sense

    def __init__(self, cmd):
        self._command = cmd
        self._files_to_watch = {}

This is a mapping from filenames to modification times, but the name doesn't reflect that. I suggest calling _file_modification_times.

    def _watchdog(self):
        '''Check wheter any file in self._files_to_watch changed,
        if so fire self._command'''

        check_file = lambda f: stat(f).st_mtime

check_file isn't a great name, because it doesn't tell me what the function actually does, return the modification time. Since its only used once in this function its also not clear whether its helpful.

        files = self._files_to_watch

What does copy _files_to_watch into a local variable help?

        any_file_changed = False

Move this inside the while loop. You aren't using it to carry information across loop iterations, so limit the scope to being inside the loop.

        while True:

            # Check each file for st_mtime change (modification)
            for f in files.keys():
                actual_mtime = check_file(f)
                if not files[f] == actual_mtime:
                    any_file_changed = f
                    files[f] = actual_mtime

            if any_file_changed:

A simpler approach:

new_modification_times = dict( (filename, os.stat(filename).st_mtime) for filename in files)
if new_modication_times != files:
     self._file_modification_times = new_modification_times

Generally, if you find yourself wanting to set boolean flags, that's a sign you aren't doing things the pythonic way.

                # run command
                print('File: \'{}\' changed since last check.'\
                        .format(any_file_changed))
                any_file_changed = False
                subprocess.call(self._command)

            # sleep before next check
            sleep(0.5)

    def _set_files_to_watch(self, files):
        '''Process args files wheter they exists and include current directory
        content if requested.'''
        if '.' in files:
            files.remove('.')

This special interpretation of '.' is likely to end up being confusing.

            # combine all other given files with current working directory
            # content, without dot files
            files += [f for f in listdir(getcwd())\
                    if not f.startswith('.')]

        # make f list unique
        files = set(files)

Since you put them in a dictionary later, uniquifiying here is kinda pointless.

        # check rights (in order to perform system stat) and wheter they exist
        for f in files:
            if not exists(f):
                msg = 'file \'{}\' does not exists, or I don\'t\
                        have access rights.'.format(f)
                raise IOError(msg)

Rather then prechecking this, why don't you just let the os.stat() complain when it tries to access the files

        # save files to watch in instance variable
        self._files_to_watch = dict.fromkeys(files)

        # set modification times
        for file_key in self._files_to_watch.keys():
            self._files_to_watch[file_key] = stat(file_key).st_mtime

There's no benefit to prepopulating the dictionary here. Instead, you can create an empty dictionary and loop over files instead of .keys(). Better yet, you can use the dictionary trick I used above to fill it. You can put it into a function and call it in both places.

    def run(self):
        '''Parses command line arguments, processes files list,
        and fires watchdog.'''
        parser = argparse.ArgumentParser(description='Checkes wheter given \
                files change, when they do, runs given command.')
        parser.add_argument('files', metavar='F', type=str, nargs='+',\
                help='list files to process, if you add . in list it will\
                watch also all non dot files in current dir.\
                If you want to have all non dot files and some dot ones use:\
                \n.file1 .file2 .file2 . .file3 it will combine specified dot\
                files and all others.')

        args = parser.parse_args()

        self._set_files_to_watch(args.files)

        print('Started watching...')
        self._watchdog()

You should probably put command line parsing logic somewhere besides this class. It makes it harder to reuse this class if it mixes command line parsing with actual logic. I'd parse a command line in a seperate main function and then have it call this.

if __name__ == '__main__':
    pass

Why?


AsyncTask alternative with Runnable and CountdownLatch

First thing that is wrong is that you are reinventing a wheel.

Second why not ditch the CountDownLatch and do context.runOnUiThread directly in the first runnable instead?

// on the UI thread

onPreexecuteWrapper();
new Thread(new Runnable() {
    @Override
    public void run() {
        doInBackgroundWrapper();
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onPostExecuteWrapper();
            }
        });
    }
}).start();

Last thing is that it's better to use an Executor and ThreadPool than to spawn new threads.


Colorizing Excel cells with a date range filter

Let's think about what you're doing for a second.

For ligne = 2 To lastrow
    DoEvents

    For chambre = 1 To 38
    DoEvents
        For alveole = 1 To 6

6 * 38 = 228 iterations for every row. Wow. Yes. There's no wonder you had to give the OS time to operate.

All of this just to set the interior color of a cell. Which is a problem as well. What if the data changes? Well.... it's going to remain the same, forever as far as I can tell. There's nothing here to revert it. There's a better way. Use some conditional formatting to do this. No VBA needed. Just craft a formula that returns a True/False condition.

I can't claim this one is perfect or tested, but it should get you started.

=AND(GEMS!$A1 = 1, AND(GEMS!$B1 = COLUMN(), AND(GEMS!$C1 = ROW(), AND(GEMS!$D1 < PHOTO!$O$2, AND(GEMS!$E1 > PHOTO!$O$2)))))


Validation
This function _is_player_id_list_valid is stuck between two useful concepts - validating and returning bool, and throwing-or-not. Don't attempt to do a half-measure of both. Given its current name, it would be less surprising to do
for player_id in provided_player_id_list:
    if player_id not in all_player_id_list:
        return False
return True

If you want to keep the exception, then

Delete the return
Change the return type to None
Use a more specific type than Exception
Rename the method to something like check_player_id_list.

For this method you should also get rid of the loop, cast the lists to sets, use set intersection, and then base your error message off of all of the missing elements instead of just the first.
Late serialization
Validation should be done on tranche_date. The sanest way to do this is expect a date of a specific format (which you probably already do, though you haven't shown it); parse it into a real datetime (or perhaps date), and then re-serialize it in _get_all_player_id. Its representation should only be str at the extreme edges of your program - in your argument parsing, and in your S3 call. In the middle it should be a real date type.
Error messages
except BatchTimeoutException:
    print(f"Jobs are known to fail due data missingness.")

is... a little strange. You could print this and it would still be valid even if there were no timeout. Instead perhaps consider
    print('Batch timed out. Data may be missing.')

Note that this does not need to be an f-string. Also, what data?


Vectorize or otherwise speed up a double for loop

Can't see exactly what's going with the sliding windows but it looks like you're calculating the full distance matrix: (i,j) and (j,i). If so, you probably only need half (usually lower) but you can make both with Distances[n1,n2] <- Distances[n2,n1] <- sum ... If this is correct, you'll basically double your speed.

But, if I misunderstood the above, you could still win a little time by reducing the number of index lookup, since these are really slow in R. In particular c(windowp1[n1]:windowp2[n1]) could be pulled out of the loop. Depending on what "x" looks like, you might try "xor(a, b)" rather than "a != b".

Adding a few other changes (eg, drop n1,n2 in favor of the loop variables) but leaving the possible "full matrix" thing I mentioned, here's a suggestion:

distances.ncol <- ncol(Distances)
for(i in seq_along(windowp1)) {
    wp12 <- c(windowp1[i]:windowp2[i])
    setTxtProgressBar(prog, i)

    for(j in seq_len(distances.ncol)) {
        Distances[i,j] <-
            sum(x[pairs[j,1],wp12] != x[pairs[j,2],wp12])
    }
    Distances2 <- (Distances/winsize)*100
}


Your use of generics may be limiting. You may want to consider using the extends/super keywords to allow subtypes in the tree.
The Tree class should be final.
Perhaps TreeNode is a better name? Conceptually, it's a node, not a tree.
The children instance variable should be private. There's also no reason to use Collections.emptyList(). Just assign it to be a new ArrayList. You should really consider using a LinkedList, because you're not really doing random access on the list.
addChildren(List) should be addChildren(Collection). Sets need love, too. Whether the order is important or not should be left up to the client.
Your documentation for addChildren() and removeChildren() should make it clear that they modify the incoming children as a side effect.
It's not at all clear to me that it's desirable to return this from addChildren() and removeChildren(), but you certainly know more than I do about client needs.
setParent() needs to be private, or a client is going to change it manually and break your internals. Specifically, the node that used to be the parent will still have a reference to the node that just got its parent changed - you'll have two different one-way relationships, such that X's parent does not have X as its child.
getChildren() needs to return a (preferably immutable) copy of the children list, not the list itself. Otherwise a client can call removeAll() on the response and your internals are broken.
If you override equals(), you should also override hashCode(), or you may see strange behaviours, especially with collections. Are you sure you really need equals()?
The tree is thread-hostile. That is probably okay, given that this is most likely not production code, but it's something to be aware of.


Reducing Complexity
The first thing to do for reduced complexity is to break up the code into multiple functions. This would allow you to profile the code and see where it spends the most time. This also makes it easier to read, write and debug the code. There are possibly 5 functions in main. As programs get more complex it is generally better to limit the main() function to set up and clean up and do all other processing in sub functions.

This would be applying the Single Responsibility Principle to the code which is the first pillar of SOLID object oriented programming. The Single Responsibility Principle states The single responsibility principle is a computer programming principle that states that every module, class, or function[1] should have responsibility over a single part of the functionality provided by the software ...

Variable Names
Generally single character variable names make code harder to read and debug. It is unclear what the variables t, n, q or m are or do.

Use Explict Casts
The line of code

unsigned long int m = sqrt(n);

is an implicit cast and generates warning messages in some compilers. C++ attempts to be type safe and casts should be explict, in this particular case it would be better to use a static_case.

Performance
It looks like this code checks all numbers in a range, there is no reason to process even numbers except for 2 since all even numbers greater than 2 can't be prime numbers because they are divisible by 2.

Indentation
The code is improperly indented immediately after the while statement. This makes it much harder to read the code.


A better main

Instead of just calling main() at the bottom, wrap it in if __name__ == "__main__":. In otherwords:

if __name__ == "__main__":
    main()

This allows me to re-use your module better, see the answer I linked for more details.

if chains

This portion of code:

        if command == "get_first":
            print(list.get_first())
        elif command == "get_last":
            print(list.get_last())
        elif command == "add_first":
            list.add_first(command_tokens[1])
        elif command == "add_last":
            list.add_last(command_tokens[1])
        elif command == "remove_first":
            list.remove_first()
        elif command == "remove_last":
            list.remove_last()
        elif command == "print":
            print(list)

Is a code smell to me. I would refactor this with a dictionary:

commands = {
    "get_first": lambda: print(list.get_first()),
    "get_last": lambda: prrint(list.get_last()),
    ...
}

This can then be called with:

commands[command]()

Library Shadowing

list = LinkedList()

list is already part of the standard library. I would not over shadow the name. I would change the name to something like linked for instance.

namedtuple?

It is questionable whether you want to do this or not, but the class LinkedListNode is just an __init__ method. In this case, I would usually advocate using a namedtuple instead and using the defaults parameter added in Python 3.7 if applicable. Although, then again, defaults is only in 3.7... So, maybe not applicable. Still useful to know about.

Implement __str__ how you implemented __repr__

__str__ is for human-readable output. __repr__ is for more internal information. You have implemented __repr__ to display a human readable representation of your list. Switch to __str__ instead.


Whether the code is well designed or not -- is hard to tell without using it. But I have several points:

It's good that you have small functions/methods which do one thing and do well. It's good that you wrote docstrings and comments.
shortest=[i for i,l in enumerate(lengths) if l<=min(lengths)] -- here you are calculating min(lengths) on each loop cycle. Calculate this and put into a variable.
Comply with PEP-8. def cost(path): return len(path) -> have two different lines. np.arange(1,self.size**2) use one space after commas. Game = Sliding_blocks() -- only classes should named CamelCased -> game = SlidingBlocks(). Use pylint to see all warnings.
Use enumerate:

for i in range(len(possible)):
    actions.append(deepcopy(obj))
    actions[i].move(possible[i])

Will become:

    for i, _possible in enumerate(possible):
        action = deepcopy(obj)
        actions.append(action)
        action.move(_possible)

Move the imports to the top of the file

def rand_move(self):
    from random import choice

Import module instead of objects from it.

from itertools import product
...
from random import choice

Will become:

import copy
import itertools
import random

Using constants? Name them uppercase and make global. Is it a setting? Pass it as an argument with a default value or store as a class attribute.

def shuffle(self):
    steps = 30
    for i in xrange(steps):
        self.rand_move()

Fail early.

    if list(piece) in self.find_moves():
        self.block[tuple( self.find_free() )] = self.block[tuple(piece)]
        self.block[tuple(piece)] = 0
        return "success"
    else:
        return "error"

This can be rewritten as

        if list(piece) not in self.find_moves():
            return "error"
        ...
        return "success"

This will also reduce indentation.

return "error" -- this is a hardcoded string. Use a constant.

Indeed, using tuples and lists is hard to read and is slow

if list(piece) in self.find_moves():
    self.block[tuple( self.find_free() )] = self.block[tuple(piece)]
    self.block[tuple(piece)] = 0

You should rethink this.


Python3 Stack implementation with List built-in

By far the biggest problem this code has is error handling. When popping or peeking from an empty stack this returns a string. this is really broken. For an example of why, suppose I add the string "Cannot peek into an empty stack." to the stack and then try to see what the top element is. I won't know if the answer I got was because the stack was empty, or because that string was in the stack. The solution to this is to raise an IndexError when the stack is empty. I also think that you shouldn't define either size or count, as the pythonic way of getting somethings length is to call len(x). You might also be interested to know that python lists have a pop function already, so you could just use that for your pop


For .net framework 3.5, you can have following code improvements:

foreach (var drRow in table2.Rows.Cast<DataRow>()
                      .Where(drRow => !table1.Rows.Contains(drRow["KeyId"])))
{
    table1.ImportRow(drRow);
}

part of body can be converted to LINQ-expression
use "var" (implicitly typed) instead of "DataRow" (explicitly typed)


If the control doesn't exist then GetDlgItem returns NULL. Passing NULL to DestroyWindow should be "save" in the sense that it won't crash - it will return FALSE and GetLastError will be returning an "Invalid Handle" error (or something like that) (can't find any docs for it but that's the behaviour I've seen in the past).

A remark to your code:

hwnd = GetDlgItem(hWnd, IDC_BTN_FOOA);
DestroyWindow(hwnd);

The use of two different variables which only differ in the capitalization of a single letter is ugly and error prone and you should use a different name. One convention I tend to follow if I select objects which are to be destroyed is to call them doomed. So maybe something like this:

doomedHandle = GetDlgItem(hWnd, IDC_BTN_FOOA);
DestroyWindow(doomedHandle);


Simplifying and optimize a concurrent access

There is no sense in creating a task and waiting on it straight away. The following code is almost identical to your test method (almost - because tasks are created on a thread pool here):

[TestMethod]
public void RecoveryConcurrentTest()
{
    var tasks = Enumerable.Range(0, 10).Select(i => Task.Factory.StartNew(AutoRecover)).ToArray();

    Task.WaitAll(tasks);
}

Note that it doesn't actually test the fact that AutoRecover allows only one thread at a time, it just ensures that nothing fails when multiple threads call this method. There is no way in current design to detect it.

What I would suggest is to expose the fact of long process inside of AutoRecover by returning a Task that any thread can wait on:

[TestMethod]
public void RecoveryConcurrentTest()
{
    var tasks = Enumerable.Range(0, 10).Select(i => AutoRecoverAsync()).ToArray();

    Task.WaitAll(tasks);
}

private volatile Task _recoveryTask;
private readonly object _syncRoot = new object();

private async Task DoActualRecover()
{
    Trace.WriteLine("PROCESSING....");
    await Task.Delay(10000);
    Trace.WriteLine("PROCESSED....");
    _recoveryTask = null;
}

public Task AutoRecoverAsync()
{
    var recoveryTask = _recoveryTask;
    if (recoveryTask != null)
        return recoveryTask;

    lock (_syncRoot)
    {
        recoveryTask = _recoveryTask;
        if (recoveryTask != null)
            return recoveryTask;

        return _recoveryTask = DoActualRecover();
    }
}


Implementing Student Record Java program

To start with OOP, you should think of the Student class as an Object, a tangible thing like a ball. Say you were given a student. What properties might it have? For example, it may have a name, a gender, a major, a list of courses, etc etc. What could you ask it to do? You could ask it to tell you its name, to tell you whether it is enrolled in a given course or not, whether it shares a course with a given other student or not, etc etc.

In your example, Students appear to have a name, an age, a course, a year, and a section. These are the values that define a student. We can begin a more OOP approach by defining a Student class that adequately stores this information about a student, and allows construction and access to these fields:

public class Student{
    public String name;
    public int age;
    public String course;
    public String year;
    public String section;

    /** Constructs a Student object with the given values */
    public Student(String name, int age, String course, String year, String section){
        this.name = name;
        this.age = age;
        this.course = course;
        this.year = year;
        this.section = section;
    }

}

Now, you may notice that everything in the above example is public. This is (almost certainly) wrong. For example, making the age field public allows anyone to walk up to a student and say "you are now -12 years old". Certainly a bug. Let's revise and only allow get access to be public.

public class Student{
    private String name;
    private int age;
    private String course;
    private String year;
    private String section;

    /** Constructs a Student object with the given values */
    public Student(String name, int age, String course, String year, String section){
        this.name = name;
        this.age = age;
        this.course = course;
        this.year = year;
        this.section = section;
    }

    /** Returns the name of this Student */
    public String getName(){
        return name;
    }

    /** Returns the age of this Student */
    public int getAge(){
        return age;
    }

    /** Returns the course of this Student */
    public String getCourse(){
        return course;
    }

    /** Returns the year of this Student */
    public String getYear(){
        return year;
    }

    /** Returns the section of this Student */
    public String getSection(){
        return section;
    }
}

Now, while a student does have an intrinsic value for their age, you can't access it directly. You can, however, ask the student how old they are with getAge(), which will tell you what you wanted to know.

Finally, let's tackle the main method you were doing in the first place. Now that we have the Student class, we can represent a (name, age, course, year, section) as a single Student object. Instead of having 5 separate arrays, one for each field, we have a single array of Students. Just add this main method to the above Student class:

public static void main(String[] args) {
   int x = 0;
   int menuChoice = -1;
   Student[] students = new Student[30]; //As a note, hard-coding this '30' is a bad idea.
                                         //Probably should be static, final const in class.
   Scanner input = new Scanner (System.in);
   do{
       System.out.println("\t\t\tStudent Record Menu");
       System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
       System.out.println("Enter a choice: ");
       menuChoice = input.nextInt();

       if (menuChoice==1){
           if(x < 30) { //Able to add new student.
               System.out.println("Full name:");
               String name = input.next();     //This was your error - should be next like the others,
                                               //Not nextLine()
               System.out.println("Age:");
               int age = input.nextInt();
               System.out.println("Course:");
               String course = input.next();
               System.out.println("Year:");
               String year = input.next();
               System.out.println("Section:");
               String section = input.next();

               //Create the new student using the given inputs
               Student s = new Student(name, age, course, year, section);

               //Place in array
               students[x] = s;

               //Increment x for next student placement
               x++;
           } else {  //Not able to add new student
               System.out.println("Can't add new student, students full");
           }
       }
       else if (menuChoice==2) {
           for (int i=0; i<x; i++) {
               Student s = students[i];
               System.out.println(s.getName() + s.getAge() + s.getCourse()
                                      + s.getYear() + s.getSection());
           }
       }
       else if(menuChoice < 1 || menuChoice > 4){
           System.out.println("Unrecognized menu choice; please re-enter");
       }
   } while (menuChoice != 4);

   //Do close your scanners when you're done with them to avoid a resource leak.
   //This is closing System.in (which is bad), but you're code is terminating anyway
   //so its ok
   input.close();
}

Some places you could go from here are using a List (ArrayList will do) instead of an array for student storage in the main method, because arbitrarily limiting the number of students to 30 seems silly. You could also give students more complex behavior (a list of friends, for example) to do some really cool stuff.

Welcome to Java and OOP! If there's any way I can clarify my answer let me know.


Listing last 3 items (or all if less than 3) in an ArrayList

Is a best practice to define a variable as type of the interface the instance implement it(see OOP principles)
Just a little bit out of scope, you can declare your arrayList inline, like in the example I wrote.
Try to use available features of List(in this example) like subList rather than cycle(what if you have thousands of elements?)
toString on a list will return a string with those list, you don't have to concatenate them
it is a bad practice to concatenate strings in cycles because create new strings every time you add + " "

See an alternative solution below:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainTest {
    public static void main(String[] args) {
        final int wantedSize = 3;
        final List<String> arrayList = new ArrayList<>(Arrays.asList("item1", "item2", "item3", "item4"));
        final int listSize = arrayList.size();
        final List<String> result = (listSize >= wantedSize) ? arrayList.subList(listSize-wantedSize, listSize): arrayList;
        System.out.println(result.toString());
    }
}


As Jerry explained, all math operations treat numbers as floating point... even numbers stored as integers. This was my first attempt:

1 rem
2 rem fizzbuzz in commodore basic
3 rem
10 t = time
20 for i = 1 to 100
30 n = i / 15 :if n = int(n) then print "fizzbuzz" :goto 70
40 n = i / 3 :if n = int(n) then print "fizz" :goto 70
50 n = i / 5 :if n = int(n) then print "buzz" :goto 70
60 print i
70 next
80 print "ran for" (time - t) / 60 "seconds"

Skipping the rest of the conditions when a condition passes speeds it up significantly.
Assigning the value of X/Y to a variable and reusing it is faster than calculating it twice. Some places around the internet mention the formula X-INT(X/Y)*Y, but that was slower than N=INT(N) in my tests.
According to this article you can write your own modulo "operator" in assembly and use it in BASIC. The assembly program is available here. Seems like overkill to me.

You might think that you could replace the goto 70 with next, but it doesn't quite work. Once the loop is complete, it will go to the next line, and call the next on that line, and you'll get a "next without for" error. Technically it still does what it's supposed to do, but it doesn't exit cleanly.

You could do something like this as a compromise, but it's hackish:

1 rem
2 rem fizzbuzz in commodore basic
3 rem
10 t = time
20 for i = 1 to 100
30 n = i / 15 :if n = int(n) then print "fizzbuzz" :next
40 n = i / 3 :if n = int(n) then print "fizz" :next
50 n = i / 5 :if n = int(n) then print "buzz" :next :goto 70
60 print i: next
70 print "ran for" (time - t) / 60 "seconds"

Edward had a good idea: keep separate counters for fizz and buzz instead of doing division. Here's a variation on his approach that sacrifices speed for readability. It doesn't use goto and is about as readable as the original code in the question. It's faster than my examples above, but slower than Edward's solution (since it doesn't skip other conditions after passing one, and doesn't have a combined "fizzbuzz" case).

1 rem
2 rem fizzbuzz in commodore basic
3 rem
10 t = time
20 fizz = 0 :buzz = 0
30 for i = 1 to 100
40 fizz = fizz + 1 :buzz = buzz + 1
50 print
60 if fizz = 3 then print "fizz"; :fizz = 0
70 if buzz = 5 then print "buzz"; :buzz = 0
80 if fizz > 0 and buzz > 0 then print i;
90 next
100 print ,"ran for" (time - t) / 60 "seconds"

Incidentally, the biggest performance bottleneck seems to be printing carriage returns and moving everything up the screen. If you try the original code in the question without printing any carriage returns, it will run about three times faster.

Assuming the screen has 40 columns by 25 rows, it's just big enough to fit the fizzbuzz output neatly into columns without scrolling. This version does just that, shaving off about a second from the previous version.

1 rem
2 rem fizzbuzz in commodore basic
3 rem
10 t = time
15 print chr$(147);
20 fizz = 0 :buzz = 0 :row = 0 :col = 0
30 for i = 1 to 100
40 fizz = fizz + 1 :buzz = buzz + 1
50 row = row + 1
60 poke 211, col
70 if fizz = 3 then print "fizz"; :fizz = 0
80 if buzz = 5 then print "buzz"; :buzz = 0
90 if fizz > 0 and buzz > 0 then print i;
100 if row = 25 then print chr$(19); :col = col + 10 :row = 0
110 if row > 0 then print
120 next
130 secs = (time - t) / 60
140 poke 198, 0 :wait 198, 1
150 print chr$(147) "ran for" secs "seconds"

Notes:

chr$(147) is CLR, a form feed character which clears the screen.
poke 211, col manipulates system memory at the address where the cursor column is stored.
chr$(19) is HOME; it moves the cursor to the top row.
poke 198, 0 :wait 198, 1 waits for the user to press a key before continuing, so the timing message and READY prompt don't overwrite any of the output at the end.

Here's what the output from the final version looks like:


Reorder the letters of one string to match the order of letters in a second string

Your code is pretty good, except for using indexOf(char), as that can be quite expensive: O(string2.length). Here is how I would do it to avoid using that. Assuming hashmap access is O(1) and n being the max length between both strings, my implementation runs in O(n)

function characterCount (str) {
  var chars = {};

  for (var i = 0; i < str.length; i ++) {
    chars[str[i]] = (chars[str[i]] || 0) + 1;
  }

  return chars;
}

function reOrderLetters (str1, str2) {
  var count1 = characterCount(str1); // O(n)
  var count2 = characterCount(str2); // O(n)
  var result = [];
  var seenCount = {}

  for (var i = 0; i < str2.length; i++) {
    var char = str2[i];
    seenCount[char] = (seenCount[char] || 0) + 1;

    if (count1.hasOwnProperty(char)) {
      var remaining = count1[char] % count2[char];
      var toRepeat = Math.floor(count1[char] / count2[char]);

      if (seenCount[char] <= remaining) {
        toRepeat = Math.ceil(count1[char] / count2[char]);
      }

      result.push(char.repeat(toRepeat));
    }
  }

  for (var i = 0; i < str1.length; i++) {
    var char = str1[i];

    if (count2.hasOwnProperty(char) == false) {
      result.push(char.repeat(count1[char]));
      count2[char] = true;
    }
  }

  return result.join("");
}

console.log(reOrderLetters("shouts", "soups") == "sousht")
console.log(reOrderLetters("aa", "aaaa") == "aa")
console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")


2018/04/24 edit

I missed an obvious bug: is_linux_mint is not implemented correctly. The results of a return on an empty output of a command substitution, with or without quotes, is implementation-defined:

  The value of the special parameter '?' shall be set to n, an unsigned decimal integer, or to the exit status of the last command executed if n is not specified. If n is not an unsigned decimal integer, or is greater than 255, the results are unspecified.

The fix is to remove the return and dollar-parentheses:

is_linux_mint()
{
    grep -i mint /etc/lsb-release >/dev/null 2>&1
}

#!/bin/sh

printc()
{
    fd=1
    color=0 # Black
    case "$1" in
        -info)
            color=4 # Blue
            ;;
        -ok)
            color=2 # Green
            ;;
        -warning)
            fd=2
            color=3 # Yellow
            ;;
        -error)
            fd=2
            color=1 # Red
            ;;
        *)
            ;;
    esac
    [ "$color" -ne 0 ] && shift
    printf '%s\n' "$(tput bold)$(tput setaf "$color")$@$(tput sgr0)" >&"$fd"
}

show_error_and_exit()
{
    if [ "$?" -ne 0 ]
    then
        printc -error 'An error has occurred.'
        echo
        exit "$step"
    fi
}

ask_for_sudo_password()
{
    sudo sh -c ':'
}

is_linux_mint()
{
    return "$(grep -i mint /etc/lsb-release >/dev/null 2>&1)"
}

mintupdate()
{
    if is_linux_mint
    then
        while true
        do
            echo 'Do you want to check for kernel upgrade via MintUpdate?'
            read -r answer </dev/tty
            case "$answer" in
                [Yy])
                    break
                    ;;
                [Nn])
                    exit
                    ;;
                *)
                    echo 'Please answer Y or N.'
                    ;;
            esac
        done
        sudo /usr/bin/python3 /usr/lib/linuxmint/mintUpdate/mintUpdate.py show
    fi
}

echo
printc -info '--------------------'
printc -info 'Vlasta - Laptop Mint'
printc -info '--------------------'
echo
step=0
trap show_error_and_exit EXIT
while IFS='#' read -r command description
do
    printc -ok "Step $step:$description"
    printc -warning "$command"
    step=$(( step + 1 ))
    set -e
    eval "$command"
    set +e
    printc -ok 'Success.'
    echo
done <<'EOF'
ask_for_sudo_password # enter password
sudo dpkg --configure -a # configure packages
sudo apt-get install --fix-broken # fix broken dependencies
sudo apt-get update # update cache
sudo apt-get upgrade # upgrade packages
sudo apt-get dist-upgrade # upgrade packages with possible removals
sudo apt-get --purge autoremove # remove unused packages
sudo apt-get autoclean # clean up
mintupdate # Linux Mint kernel upgrade
EOF

ShellCheck output:

$ shellcheck myscript

Line 26:
    printf '%s\n' "$(tput bold)$(tput setaf "$color")$@$(tput sgr0)" >&"$fd"
                                                     ^-- SC2145: Argument mixes string and array. Use * or separate argument.
                                                                     ^-- SC2039: In POSIX sh, >& is undefined.

Line 31:
    if [ "$?" -ne 0 ]
         ^-- SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

SC2181 is a minor, irrelevant warning: the exit code can't be checked directly in this case.
SC2039 is a false positive for it couldn't detect the value of fd; just make sure that fd is always assigned a valid number here, which I have.
SC2145 is what I disagree with. See What is the difference between $* and $@?, from which I quote:

  "$*" expands to a single word "$1c$2c...". Usually c is a space, but it's actually the first character of IFS, so it can be anything you choose.

  "$@" expands to separate words: "$1" "$2" ...

Of course this depends on how you want to use printc: if you're only giving it strings to print, it's OK to use "$*"; if you're also passing it the format string, or don't want IFS to affect the output presentation, use "$@". Feel free to replace $@ with $* if you feel so inclined to clear this warning.

You forgot to enable interpretation of backslash escapes in echo with the -e option, so I didn't get colorful outputs on my openSUSE where the default for echo is to disable interpretation of backslash escapes. But it doesn't matter since options for echo aren't specified by POSIX. Also, the ANSI escape code is probably less portable, and definitely less readable, than the tput alternative, as a SO user noted.

I grabbed the printc function from my personal arsenal (with minor modifications) and put it here. Originally it didn't have the format string hard-coded in, but you always use it like echo in your code and I'm not about to define another function or add another option to get this behavior, so I sacrificed generality for convenience.

echo without any argument prints a newline, so you don't have to define a function to do just that.

The time frame between each prompt for a password by sudo is dependent on the sudoers policy, specifically the timestamp_timeout option, which can be set to 0 to always prompt for a password. Therefore, I'm not sure of the utility of your ask_for_sudo_password function when one can already type in the password on-demand, unless it is to test if sudo is available as a command, in which case it's better to write it in the same way as your is_it_linux_mint function and rename it to has_sudo or test_sudo.

Compare if is_linux_mint with if is_it_linux_mint, I think is_linux_mint is a better name.

There's no easy way to identify which Linux distribution is running on a user's system. /etc/os-release is a new standard, but for those without it, the most reliable way to find out, in general, is probably by parsing lsb_release -i, provided it is installed on the system.

I see some superfluous code in your case statement:

            [Yy]) :   ; break;;
            [Nn]) exit; break;;

It's probably done for stylistic reasons, but still I want to point out that : and the break after exit are not needed. On a side note, I prefer the shell equivalent of the Allman coding style, so I don't cramp up my case constructs into one line per pattern. But however you write your code, consistency is key.

Last but not least, you're repeating the same patterns throughout each step of the maintenance tasks, so I wrapped them in a while read loop reading from a here document. So now your while read loop, which I grouped inside a new function mintupdate, has to have its input redirected back to the controlling terminal, and rest assured that /dev/tty is required to exist by the POSIX specifications.

After the rewrite, it has become quite easy to adjust the script's behavior: you just add the commands you want to run, potentially wrapped inside functions, in sequential order in the here document. The descriptions are optional, and you can omit them by not adding #-style comments after the commands that they annotate. The # delimiter is chosen so one can easily copy the lines and run them on their terminal.


Handling conditional logic inside controller actions

This is just copy of my answer to your question on SO.

Usually you don't use action filters for so-called business logic of your web application - this is what the controllers are for. Action filter are rather for the whole stuff which is external to the actual logic - common case is logging, performance measurement, checking if user is authenticated / authorized (I don't think this is your case, although you call IsAuthorized method on the "Item").

Reducing code is generally good thing but in this case, I don't think putting the logic to action is a good way, because you've actually made it a bit unreadable, and unreadable code is in my opinon much worse than repeated code. Also, specifically in your case, for all valid items you actually call the _todoListItemsRepository.Find() twice (for each valid item), which might be costly if this is some webservice call or db lookup.

If the code is just repeated throughout the actions, make a method out of it like:

private View ValidateItem(Item) {
    if (Item == null)
      return View("NotFound");
   if (!Item.IsAuthorized())
      return View("NotValidOwner");
return null; }


Group items by types: replace nested for loops with reduce

Poor memory usage
Javascript has managed memory. That means it does all the hard work of allocating and releasing memory, which is great (managing memory manually is a real pain).
But this useful feature comes with a down sides...

Managed memory environments are inherently slow,
Managed memory environments encourage very poor memory usage patterns

Looking at your memory and CPU usage.
In your code you create a total of 9 arrays, keeping only 3 of them. (using the data example you provided)
Each time you add an item to a group you create a new array, that must be iterated over when you copy the existing group. groupedItems[type] = [...(groupedItems[type] || []), item]
There are only 6 type values yet you iterate over them 12 times. Once each with item.types.map(type => type.value); and then again with for (const type of getTypes(item))
For the 6 items you add to the 3 groups your code needed 16 iterations.
Less overhead
The example avoids copying the item.types array for each item and assigns a new array to new groups. If a group has been defined the item added is pushed rather than copy the whole array.
The resulting code only needs 6 iterations executing in half the time and using several times less memory
function groupTypes(items) {
    const groups = {};
    for (const item of items) {
        for (const {value: type} of item.types) {
            groups[type] ? groups[type].push(item) : groups[type] = [item];
        }
    }
    return groups;
}

Or slightly quicker by avoiding the copy of the type.value string to to the variable type
function groupTypes(items) {
    const grps = {};
    for (const item of items) {
        for (const type of item.types) {
            grps[type.value] ? grps[type.value].push(item) : grps[type.value] = [item];
        }
    }
    return grps ;
}


Font manager/loader class written in C++ (uses unordered_map)

Relationship between batch and single-call api

Typically, when a manager class like like has both a single and a batch API call, the general function is the batch API, and the special case is the single-case. so it's the single-call API that should be calling the batch API, or the batch api should not exist at all.

The reasoning is that normally, the batch API provides some kind of advantage on top of just calling the single call in a loop. If there is no advantage to be gained, then there should only be the single resource call function, and let your user write a loop around it if they need to call it a bunch of time.

You want to keep your API surface as small as possible.

Smart pointers

Unless you are dealing with some very legacy system, you should have access to C++11. use std::unique_ptr<> instead of raw pointers, it'll massively reduce the amount of possible errors, as well as the amount of code you have to write.

Avoid double lookups:

if (m_Fonts.count(fileName))
    return m_Fonts.at(fileName);

// vs

auto found = m_Fonts.find(fileName);
if(found != m_Fonts.end())
    return found->second;

The second block of code only does a single lookup through the container.

similarly:

LoadFont(fileName);
return m_Fonts.at(fileName);

// vs

return LoadFont(fileName);

and

m_Fonts.emplace(fileName, new Font(FONT_FOLDER_PATH + fileName));
return m_Fonts.at(fileName);

// vs

auto emplaced = m_Fonts.emplace(fileName, new Font(FONT_FOLDER_PATH + fileName));
assert(emplaced.second);
return emplaced.first->second;

removes extra lookups.

avoid Singleton instantiation in the header file

This is a little subtle, but the definition of FontManager::instance belongs in the cpp file. This is important because if DLLs are ever involved, you are going to have a bad time otherwise.


Recover a secret string from random triplets

I have mainly two things I'd like to look at:

I'm not a big of fan of the constant deconstructing and recreating of Sets in the loop, especially since this most likely has negative impact on the performance. Unfortunately because there is not direct way to add multiple values to a Set there is no functional "one line" solution. My function to do this would look like this:

const addToAfter = (key, values) => {
    const set = after[key] || (after[key] = new Set());
    values.forEach(a => set.add(a));
};

which changes the loop to

for (let triplet of triplets) {
    addToAfter(triplet[0], triplet.slice(1));
    addToAfter(triplet[1], [triplet[2]]);
    addToAfter(triplet[2], []);
}

This leads to my second point: the obvious code repetition. I don't think there is a reason not to use another loop here, which also has the "advantage", that you don't need to limit yourself to "triplets", but support arrays of any length:

for (let triplet of triplets) {
    for (let i = 0, len = triplet.length; i < len; i++) {
        addToAfter(triplet[i], triplet.slice(i + 1));
    }
}

If performance is important, I'd even consider getting rid of the .slice call and replace it with a loop, that adds the characters directly to the Set.

In general: I'm avoiding the "modern" functional way, because it (at least in this case) leads to slightly cryptic syntax (and thus unread code) and a lot of (slow) memory reallocation and data copying.


Best practise way to handle array of pairs

I would work with a two dimensional array, in stead of two separate arrays. You could then shuffle your array to get the items in a random order. Something like this:

$items = [
    ['id' => 1, 'name' => 'item 1', 'price' => '$1.00'],
    ['id' => 2, 'name' => 'item 2', 'price' => '$2.00'],
    ['id' => 3, 'name' => 'item 3', 'price' => '$3.00'],
    ['id' => 4, 'name' => 'item 4', 'price' => '$4.00'],
];

shuffle($items);

foreach($items as $item) {
    echo $item['id'] . ': ' . $item['name'] . ' ' . $item['price'];
    // or whatever you want to do, just trying to demonstrate you
    // won't need those $name and $price variables anymore...
}

I find it makes more sense to keep your item's properties together, in stead of spreading them over different arrays. You know when you pick an element from the items array you will have all it's properties. And to me the code is better readable as well.


Generating a sequential number for app-wide use

Have you considered using an AtomicLong instead of the RoastIdCounterService? You can then call AtomicLong.incrementAndGet() to get the next value. The atomic long will take care of the locking required for safe concurrent access.


Verilog is flexible with how it interprets integers.  It interprets 5 and 4'b0101 as the same numeric value.  Yes, it interprets 12 as an integer in the if statement.
Your code simulates properly on edaplayground, and you have done a good job of separating the design code from the testbench.  Here are some specific recommendations.
If you want your design code to be synthesizable, it would be best to move the $display statements into the testbench.  This requires you to replicate the logic in the testbench as well, but this is necessary when you create a testbench checker anyway.
For debugging purposes, it is helpful to display the simulation time as well: $time.
Also for debugging, it is better to dump signals throughout the hierarchy.  Currently, you just dump the testbench signals.  If you call $dumpvars without arguments, you will also get the design variables dumped to your VCD file.
An alternate approach to driving specific values to your input (12, 11, 51, etc.) is to drive random values in a repeat loop.  This allows you to easily change the number of values you drive and the range.  The code {$random} % 60 below returns a value in the range 0-59.
Your rd instance uses connections-by-position, which is fine for a small number of ports (2), like you have.  But, it is preferable to use connections-by-name to make the code more readable and to help prevent connection errors.  For example: .x (in)
In your design, it is preferable to use ANSI style port declarations to cut down on duplicate port names.
It is preferable to use an implicit sensitivity list always @* because it automatically triggers the block when the appropriate signals change.  This avoids a common Verilog problem where people forget to add or remove signals from the list when they change the code body.
To make the range programmable, one common way to do it is to use parameters.  They can be declared in both the design and the testbench.  For example, you can use MIN and MAX instead of 12 and 49 (all caps is a convention).  It is also helpful to add comments describing the legal values for the parameters.
Here is an alternate way to code everything:
module range_detect (
    input [9:0] x,
    output reg y
);

parameter MIN = 12;
parameter MAX = 49;

always @* begin
    if ((x>=MIN) && (x<=MAX)) begin
        y = 1;
    end else begin
        y = 0;
    end
end
endmodule

module testbench;
    reg [9:0] in;
    wire out;

    // MIN must be smaller than MAX.
    // MAX must be smaller than 1024.
    parameter MIN = 12;
    parameter MAX = 49;

    range_detect #(
        .MIN (MIN),
        .MAX (MAX)
    )
    rd (
        .x  (in),
        .y  (out)
    );

    always @* begin
        if ((in>=MIN) && (in<=MAX)) begin
            $display($time, "  Input: %0d lies between %0d and %0d", in, MIN, MAX);
        end else begin
            $display($time, "  Input: %0d does not lie between %0d and %0d", in, MIN, MAX);
        end
    end

    initial begin
        $dumpfile("dump.vcd");
        $dumpvars;
        repeat (10) #2 in = {$random} % 60;
        #2;
    end
endmodule

You can simply change the parameter values in the testbench and they will propagate into the design.

I use 4-space indentation because I think it is easier to see the different levels of your code's logic.
I add parentheses around terms like (x>=MIN) so that I never have to think about which operators have higher precedence, and it also helps me visually parse the code.


Caching data by using the result of first running operation

Yes, it seems thread safe.

I run a test to prove it which I give the details at the bottom, but first are some code review comments.

The code is missing the Credentials class which I think is also important for the review. The cache items are added with keys credentials.ToString() and it is important for this method to return the same value for Credentials objects having the same credential values, and distinct values for Credentials instances with different credential values. Is it?
Naming conventions. Class names should be PascalCase and the class AgentMetadata violates this rule. Should be AgentMetaData
To achieve better encapsulation and seperation of concerns, (The creation of an empty credential object should be a concern for the Credentials class, which has control over the internals of itself) instead of having a static readonly Credentials EmptyCredentials field in this class, it is better to have a public static readonly Credentials Empty field (or property getter) in Credentials class.

Instead of this:

Credentials empty = (credentials ?? EmptyMetadataCredentials);

Isn't it better to have this?

Credentials empty = (credentials ?? Credentials.Empty);

The variable names agentMetadata and lazyMetadata are not descriptive enough.

This is somewhat confusing:

return (lazyMetadata ?? agentMetadata).Value;

Having names like the following might eliminate that confusion:

var newLazyInstance = new Lazy<AgentMetadata>(() => GetCurrentInternal(credentials));

var cachedLazyInstance = (Lazy<AgentMetadata>)MemoryCache.Default.AddOrGetExisting(
                           (credentials ?? EmptyMetadataCredentials).ToString(),
                           newLazyInstance,
                           DateTime.Now.AddMinutes(5));

return (cachedLazyInstance ?? newLazyInstance).Value;

And here are the results of the test, which shows the GetCurrentInternal method is invoked a total of 5 times for all the 100 threads.

The test created 100 threads which access the GetCurrent method randomly within 500 ms. There is another thread for removing the item from the cache in 100 ms continuously (This is because, the cache policy doesn't seem to effectively remove the item at the exact point of time of expiration).

The GetCurrentInternal method lasts for a random time between 0 and 500 ms

With the following results, it can be seen that the GetCurrentInternal method is invoked a total of 5 times (which is the number of the cache not containing a Lazy instance for the given credentials, first one because the cache is empty, and for 4 more times because it is removed from the cache)

I can't help myself thinking why the AddOrGetExisting of MemoryCache returns null  when the item is added to the cache. This would have been implemented differently (as returning the added instance as ConcurrentDictionary does)

T:47    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 145,68
T:13    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 146,44
T:20    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 146,54
T:26    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 147,45
T:71    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 148,46
T:62    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 148,55
T:53    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 149,37
T:5 M:GetCurrent    E:AddOrGetExisting.Added?   R:False 146,68
T:22    M:GetCurrent    E:AddOrGetExisting.Added?   R:True  150,66
T:31    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 150,18
T:63    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 154,58
T:50    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 157,15
T:27    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 182,13
T:67    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 182,33
T:43    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 182,18
T:32    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 182,13
T:3 M:GetCurrent    E:AddOrGetExisting.Added?   R:False 187,24
T:55    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 194,8
T:29    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 197,13
T:28    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 214,17
T:4 M:GetCurrent    E:AddOrGetExisting.Added?   R:False 221,11
T:84    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 228,12
T:78    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 232,09
T:19    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 235,1
T:66    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 238,1
T:7 M:GetCurrent    E:AddOrGetExisting.Added?   R:False 242,14
T:61    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 245,11
T:49    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 246,15
T:23    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 250,08
T:85    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 251,1
T:81    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 254,1
T:98    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 254,12
T:44    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 254,13
T:91    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 255,25
T:65    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 257,2
T:59    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 259,33
T:56    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 269,1
T:34    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 271,11
T:89    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 271,12
T:41    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 279,12
T:100   M:GetCurrent    E:AddOrGetExisting.Added?   R:False 280,12
T:11    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 290,11
T:17    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 292,08
T:58    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 293,1
T:14    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 297,09
T:90    M:GetCurrent    E:AddOrGetExisting.Added?   R:True  303,12
T:75    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 312,15
T:46    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 318,17
T:45    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 321,11
T:10    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 322,1
T:92    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 328,1
T:80    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 339,12
T:8 M:GetCurrent    E:AddOrGetExisting.Added?   R:False 341,11
T:51    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 342,11
T:74    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 343,11
T:86    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 351,12
T:68    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 352,11
T:95    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 354,1
T:72    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 359,11
T:48    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 360,11
T:18    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 364,1
T:6 M:GetCurrent    E:AddOrGetExisting.Added?   R:False 374,12
T:35    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 377,09
T:15    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 377,11
T:93    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 378,1
T:33    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 379,1
T:9 M:GetCurrent    E:AddOrGetExisting.Added?   R:False 390,12
T:39    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 391,09
T:12    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 395,11
T:24    M:GetCurrent    E:AddOrGetExisting.Added?   R:True  401,11
T:40    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 402,11
T:30    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 404,09
T:70    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 411,11
T:102   M:GetCurrent    E:AddOrGetExisting.Added?   R:False 412,1
T:52    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 413,11
T:57    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 417,1
T:37    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 426,13
T:69    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 428,1
T:16    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 432,11
T:21    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 438,13
T:96    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 441,11
T:38    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 442,09
T:54    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 456,18
T:82    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 465,12
T:76    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 466,11
T:25    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 470,11
T:36    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 477,09
T:73    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 483,12
T:42    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 483,13
T:101   M:GetCurrent    E:AddOrGetExisting.Added?   R:False 491,13
T:64    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 494,12
T:60    M:GetCurrent    E:AddOrGetExisting.Added?   R:True  502,11
T:97    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 528,2
T:24    M:GetCurrentInternal    E:Invoked   R:AgentMetadata_ID=1    547,76
T:24    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    548,3
T:70    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    548,36
T:40    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    548,32
T:57    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    549,27
T:21    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    561,53
T:36    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    574,77
T:102   M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    548,4
T:38    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    563,24
T:101   M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    575,21
T:77    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 579,16
T:25    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    571,16
T:54    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    567,6
T:73    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    574,79
T:42    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    574,8
T:76    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    567,61
T:37    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    554,64
T:82    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    567,6
T:52    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    548,38
T:64    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    575,44
T:16    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    557,74
T:94    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 587,92
T:69    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    556,54
T:96    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    562,78
T:30    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=1    548,35
T:88    M:GetCurrent    E:AddOrGetExisting.Added?   R:True  616,19
T:103   M:GetCurrent    E:AddOrGetExisting.Added?   R:False 631,16
T:90    M:GetCurrentInternal    E:Invoked   R:AgentMetadata_ID=2    642,16
T:90    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    642,37
T:80    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    644,54
T:72    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    648,45
T:47    M:GetCurrentInternal    E:Invoked   R:AgentMetadata_ID=3    645,16
T:47    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    650,61
T:26    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    652,63
T:22    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    654,89
T:9 M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    654,43
T:86    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    646,88
T:18    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    648,75
T:6 M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    649,06
T:15    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    650,84
T:74    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    646,62
T:53    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    658,94
T:31    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    662,34
T:46    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    642,4
T:62    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    652,69
T:95    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    646,88
T:67    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    664,69
T:71    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    660,52
T:93    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    650,84
T:45    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    642,4
T:50    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    652,69
T:23    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    677,68
T:78    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    672,49
T:66    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    672,5
T:4 M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    671,15
T:10    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    642,44
T:5 M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    657,11
T:65    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    678,46
T:29    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    669,35
T:81    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    679,46
T:33    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    649,06
T:92    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    642,46
T:14    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    688,26
T:13    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    652,62
T:17    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    688,25
T:28    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    671,12
T:89    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    684,54
T:11    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    686,67
T:100   M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    686,67
T:58    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    688,25
T:61    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    676,52
T:20    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    660,51
T:34    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    684,53
T:68    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    646,88
T:85    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    674,46
T:44    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    677,66
T:49    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    673,36
T:32    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    667,5
T:3 M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    669,31
T:41    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    686,66
T:39    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    654,43
T:7 M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    672,5
T:48    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    648,47
T:12    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    655,34
T:19    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    672,5
T:83    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 672,09
T:98    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    680,64
T:63    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    662,4
T:91    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    677,96
T:8 M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    644,56
T:75    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=2    642,38
T:43    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    665,46
T:27    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    662,37
T:59    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    680,63
T:55    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    669,34
T:99    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 695,73
T:51    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    646,62
T:56    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    684,53
T:84    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    672,24
T:87    M:GetCurrent    E:AddOrGetExisting.Added?   R:False 691,88
T:35    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=3    650,56
T:60    M:GetCurrentInternal    E:Invoked   R:AgentMetadata_ID=4    988,26
T:60    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=4    988,88
T:77    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=4    988,96
T:94    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=4    989,03
T:97    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=4    988,97
T:88    M:GetCurrentInternal    E:Invoked   R:AgentMetadata_ID=5    1050,3
T:88    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=5    1050,85
T:83    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=5    1050,94
T:87    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=5    1052,18
T:103   M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=5    1050,91
T:99    M:GetCurrent    E:Lazy.Value    R:AgentMetadata_ID=5    1050,97