There is not a lot to say, the script is fairly simple.

For the date format:

file="${path}/$(date +%F).tar";

I think I would define a constant variable at the top of the code. You might want to change the pattern latter (use something different than YYYY-MM-DD).

This:

$(mkdir -p "$path");

can simply be written as:

mkdir -p "$path"

unless you want to save the output of the bash command to a variable but this is not the case here.

You have some key/pair values to define your backup sources:

dirs=(
    "/home/ferre/Minecraft"
    "/var/lib/automysqlbackup/daily"
);

# backup names
names=(
  "Minecraft"
  "Mysql"
);

I would combine both into an associative array.

declare -A sources=(
    ["Minecraft"]="/home/ferre/Minecraft"
    ["Mysql"]="/var/lib/automysqlbackup/daily"
)

for item in "${!sources[@]}"; do
  echo "Name: $item => Directory: ${sources[$item]}"
done

Output:

Name: Mysql => Directory: /var/lib/automysqlbackup/daily
Name: Minecraft => Directory: /home/ferre/Minecraft

Thus you can easily loop on the array and extract name and target directory. Warning: please check the syntax. Bash has many pitfalls and I may have made mistakes.

Logging: I think it is important to retain a trace of script execution. Especially when the script is unattended. The console can quickly fill up and you could miss critical messages.

You have a few options like:

define a variable for a log file then use tee -a next next to each command, so that you get output to console and to a file at the same time. But this is tedious and not flexible.
Call your script like this: /path/to/your/script.sh > backup.log (use >> to append) or: /path/to/your/script.sh | tee backup.log
or better yet /path/to/your/script.sh 2>&1 | tee backup.log to capture the output of stderr.

Last but not least, your script could return an exit code. This is useful if your script is going to be handled by another script or even set up as a service.

Suggestions:

Have the script send you the log file by E-mail after execution. Or archive the log file somewhere for later review if desired.
Add error handling to make your script more reliable and more robust. If something wrong happens, or at least a fatal error, the script should stop and alert you. Here is an intro: Bash Error Handling

A backup script is usually critical, it has to perform reliably. One day, you may need to restore some important files, or recover from a system crash. There is nothing more tragic than useless/incomplete backups.

So you should also test your backups manually from time to time. Attempt to restore a random file and verify the result.


Correctness of calculations with struct timespec

I can see nothing wrong, but I think it is not optimal.  My compiler warns me
about floating point conversions of those '1E9' constants.  If I rewrite your
timeAdd as follows, the code is easier to read and the generated code is
significantly smaller:

#define BILLION 1000000000
Time timeAdd(Time t1, Time t2)
{
    long sec = t2.tv_sec + t1.tv_sec;
    long nsec = t2.tv_nsec + t1.tv_nsec;
    if (nsec >= BILLION) {
        nsec -= BILLION;
        sec++;
    }
    return (Time){ .tv_sec = sec, .tv_nsec = nsec };
}

The same goes for the other functions, I think.


Daily Coding Challenge solution - day 21

To clearly show which part of your code is the interesting part, you should define a function:

def rooms_required(classes):
    classes = classes[:] # do not modify the argument, make a copy of it
    rooms_bookings = []

    # TODO: insert your code here.

    return len(rooms_bookings)

To describe the function in more details, you should add some documentation about the expected data types:

from typing import List

def rooms_required(classes: List[(int, int)]) -> int:
    ...

This way, you can easily define several test cases:

def test_rooms_required():

    # The example from the challenge.
    assert rooms_required([(30, 75), (0, 50), (65, 150)]) == 2

    assert rooms_required([]) == 0

    # This class needs no time at all, therefore it doesn't need a room.
    assert rooms_required([(0, 0)]) == 0

    # Classes that go backwards in time should either be ignored or raise an exception.
    assert rooms_required([(1200, 1100)]) == 0

    # Ensure that rooms_required does not modify the given list,
    # as that would be surprising.
    classes = [(0, 1), (0, 2), (0, 3), (2, 3)]
    assert rooms_required(classes) == 3
    assert rooms_required(classes) == 3

Read more about pytest to see how to run these automatic tests.

Some more detailed remarks, from top to bottom:

def item_2(element):
    return (element[1]) #Returns second element of tuple for sorting

Since this challenge is about time spans, it's more helpful to the reader of your code if you call this function end, since it returns the end of a time span.

def end(span):
    return span[1]

And since the meaning of [0] in the code is not really obvious, you should also define:

def start(span):
    return span[0]

Then, instead of span[0] and span[1], you can write start(span) and end(span), which clearly tells a story.

classes = [(15,50),(51,53),(54,58),(60,70),(61,63),(65,69),(71,83)]
#classes = [(30, 75), (0, 50), (60, 150), (0, 500), (40, 70)]

As I mentioned above, instead of testing only one scenario at a time, you should define a function that does the interesting work, which then allows you to have automatic tests, and several of them at the same time.

print("The following classes will be needed")

That's wrong. It should be "the following rooms" instead.

while classes:
    item = classes[0]

The word item is a very general term. A better name for this variable is span.

    index = 0

This variable is not used in the rest of the code. You can remove this line.

    room_bookings = []
    room_bookings.append(item)

You can simplify this into room_bookings = [span].

    for next_item in remaining:
        if next_item[0] > end_time:

Instead of the end_time variable (end time of what exactly?), you can write start(next_span) > end(span), which makes the expression look symmetrical and easy to read aloud: if the next span starts later than the current span ends …

When you use this pattern, you can remove the end_time variable, which will make the code a little shorter.

    print(room_bookings)

The function that computes the room bookings should not print anything. Printing things is the job of the main program. That's a general rule.


public static String GetConnectionString()

You shouldn't have to use this outside of the class so make it private. Furthermore I would turn it into a property and set it from the static constructor -- that way you avoid having to query your configuration each time you want to make a new call.

This is assuming you don't do it deliberately like this so you can change the connectionstring without halting the application.

cmdTxt

What's that, commandtext? Something more descriptive would be helpful, perhaps just "command"  or "query" would be okay.

return command.ExecuteScalar() ?? null;

"if execution returns null, return null".

Might as well just return command.ExecuteScalar();.

string.Format("SELECT User: {0} Base: {3} SQL:{2} Error:{1}"

Keep the indices in ascending order -- it's what everybody expects and you won't have silly mistakes because the arguments passed in expected 0-1-2-3 instead.

Why use a try-catch and not a simple if(Session["ClientBase"] == null)? Exception handling is expensive and shouldn't be used for normal application flow.

GetValueAsBoolean
GetValueAsString
GetValueAsInt
GetValueAsDobule

I would consider making this a generic GetValue<T> and do the conversion inside that method while throwing a NotSupportedException for types that you don't want to support. The above idiom smells too much like Java and we're better than that.

Notice also the typo Dobule.


I realized that the nested Records never go more than 3 deep (outermost, middle, innermost), which means it could be rewritten to use primitive arrays.

Comparison 1:

n: 20
fas_ack -> 8388605 took PT0.399960323S
arr_ack -> 8388605 took PT0.115302129S
n: 25
fas_ack -> 268435453 took PT11.283535003S
arr_ack -> 268435453 took PT3.553065491S
n: 30
fas_ack -> 8589934589 took PT757.605898139S
arr_ack -> 8589934589 took PT233.040801010S

Comparison 2:

n: 20
fas_ack -> 8388605 took PT0.807311828S
arr_ack -> 8388605 took PT0.442201425S
n: 25
fas_ack -> 268435453 took PT35.765848937S
arr_ack -> 268435453 took PT14.004015773S
n: 30
fas_ack -> 8589934589 took PT959.685955407S
arr_ack -> 8589934589 took PT141.390498532S

Updated code:

extern crate time;

use time::PreciseTime;

fn main() {
    let m = 3;

    for n in [20, 25, 30].iter() {
        println!("n: {}", n);
        let s = PreciseTime::now();
        let res = arr_ack(m, *n);
        let e = PreciseTime::now();
        println!("arr_ack -> {} took {}", res, s.to(e))
    }
}

fn arr_ack(m: u64, n: u64) -> u64 {
    let mut cache: [u64; 6] = [0; 6];
    cache[0] = 1;
    for m_builder in 0..m {
        cache = _arr_ack(m_builder, 1, cache)
    }
    for n_builder in 1..(n + 1) {
        cache = _arr_ack(m, n_builder, cache)
    }
    cache[0]
}

fn _arr_ack(m: u64, n: u64, mut cache: [u64; 6]) -> [u64; 6] {
    if m == 0 {
        [n + 1, 0, 0, 0, 0, 0]
    } else if m == 1 {
        [n + 2, 0, 0, 0, 0, 0]
    } else if n == 0 {
        let mut new_cache = [1, 0, 0, 0, 0, 0];
        for m_builder in 0..m {
            new_cache = _arr_ack(m_builder, 1, new_cache);
        }
        new_cache
    } else if n == 1 {
        let previous_result = cache[0];
        for n_builder in 2..(previous_result + 1) {
            cache = _arr_ack(m - 1, n_builder, cache);
        }
        [cache[0], previous_result, cache[0], cache[1], cache[2], cache[3]]
    } else {
        let previous_result = cache[0];
        let mut new_cache = [cache[2], cache[3], cache[4], cache[5], 0, 0];
        for n_builder in (cache[1] + 1)..(previous_result + 1) {
            new_cache = _arr_ack(m - 1, n_builder, new_cache);
        }
        [new_cache[0], previous_result, new_cache[0], new_cache[1], new_cache[2], new_cache[3]]
    }
}


Reducing using/foreach/using nesting with a helper extension

I'd argue that no, this does not make the code easier to understand. Instead of a combination of familiar general-purpose constructs (using and foreach), you now have an undocumented custom special-purpose construct Using(outer, inner) that must be understood before one can make sense of the code. This use-case seems too uncommon to be worth that trade-off.

The main problem I have with the original piece of code is that it looks like a 'camel' because of the Disposable.Create hump at the start. Your alternative is still a camel, just with a bigger hump at the front and a flatter one at the back. With a DisposeAll extension method, you could turn it into a dromedary. It's still a tall hump, but now the shape actually matches its single-loop nature:

using (_logger.BeginScope().CorrelationHandle("TestBundle").AttachElapsed())
using (Disposable.Create(() => cache.Values.DisposeAll()))
{
    _logger.Log(Abstraction.Layer.Service().Meta(new { TestBundleFileName = testBundle.FileName }));
    foreach (var current in tests)
    {
        using (_logger.BeginScope().CorrelationHandle("TestCase").AttachElapsed())
        {
            // TODO
        }
    }
}

Another thing you can do is to move the loop body to a separate method or local function.


Map, which contains biomes, which contain landforms, which contain tiles

I want it to be generic so I can easily add new links to the chain
  (like adding a new kind of section between Biome and Landform for
  example)

Generics work fine for simple generic data structures (like a List). Your "generic" data structure is actually a very special one which will not be used outside of your model. It is more a try to extract the common parts of your model to a generic structure which may be useful, but based on your question I can not see the value in your case.

In my experience, data stuctures with multiple generic types, which has contraints to other generic types, are hard to understand and make the code more complicated.

In your case, I would just give generics up and write the data structure down as it is:

public class Map
{
    public List<Biome> Biomes { get; } = new List<Biome>();
    public List<Map> AdjacentMaps { get; } = new List<Map>();
}

public class Biome
{
    public Map Map {get; }
    public List<Landform> Landforms { get; } = new List<Landform>();
    public List<Biome> AdjacentBiomes { get; } = new List<Biome>();
}

public class Landform
{
    public Biome Biome {get; }
    public List<Tile> Tiles { get; } = new List<Tile>();
    public List<Landform> AdjacentLandforms { get; } = new List<Landform>();
}

public class Tile
{
    public Landform Landform {get; }
    public List<Tile> AdjacentTiles { get; } = new List<Tile>();
}

Much more readable! The properties has more descriptive names and it needs a minute to extend this hierachical data structure with other types.


My guess is that the bottleneck is drawing random numbers at each iteration.

Why guess when you can measure? I changed the height to 100 so the whole thing takes me about 8 seconds, reasonable to play around with. Removing the assert line on the bottom makes it a bit faster. Also removing the dirty = [j if...] line makes it a lot faster. As you'd expect from that inefficient line.
Not sure why you're making it so complicated. I think clean[idx] = 0 does the deletions you want, and it's fast.


Possibly the most obvious part is here

    left = self.isMirror(l.left, r.right)
    right = self.isMirror(l.right, r.left)
    return left and right

there's no need to perform the second test if the first one returns False:

    if not self.isMirror(l.left, r.right): return False
    if not self.isMirror(l.right, r.left): return False

    return True


Efficient way to get value from a dataframe and append new dataframe

getTableKey

I'm not sure it's good style to define functions inside other functions unless you are implementing some sort of closure:

# this is much easier to read as a separate function
# and you don't incur the cost of defining it every time
# you call the encapsulating function
def getTableKey(parsed):
    findFrom = False
    wordKey = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']
    for word in parsed.tokens:
        if word.is_group:
            for f in getTableKey(word):
                yield f
        if findFrom:
            if isSelect(word):
                for f in getTableKey(word):
                    yield f
            elif word.ttype is Keyword:
                findFrom = False
                StopIteration
            else:
                yield word
        if word.ttype is Keyword and word.value.upper() in wordKey:
            findFrom = True

def getTableName():
    tableName = []
    query = (sqlparse.parse(sql))
    for word in query:
        if word.get_type() != 'UNKNOWN':
            stream  = getTableKey(word)
            table   = set(list(getWord(stream)))
            for item in table:
                tabl = re.sub(r'^.+?(?<=[.])','',item)
                tableName.append(tabl)
    return tableName

yield from syntax

Furthermore, instead of using for f in getTableKey(word): yield f, later versions of python3 introduced the yield from syntax:

def getTableKey(parsed):
    findFrom = False
    wordKey = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']
    for word in parsed.tokens:
        if word.is_group:
            yield from getTableKey(word)

        # combine this, since it's exactly this combination that will yield
        # f, there's no elif or else
        if findFrom and isSelect(word):
            yield from getTableKey(word)
        # rest of func

This leverages less function calls and is faster:

import dis

def f():
    for i in range(10000):
        yield i

def g()
    yield from range(10000)

dis.dis(f)
2           0 SETUP_LOOP              22 (to 24)
              2 LOAD_GLOBAL              0 (range)
              4 LOAD_CONST               1 (10000)
              6 CALL_FUNCTION            1
              8 GET_ITER
        >>   10 FOR_ITER                10 (to 22)
             12 STORE_FAST               0 (i)

  3          14 LOAD_FAST                0 (i)
             16 YIELD_VALUE
             18 POP_TOP
             20 JUMP_ABSOLUTE           10
        >>   22 POP_BLOCK
        >>   24 LOAD_CONST               0 (None)
             26 RETURN_VALUE

dis.dis(g)
2           0 LOAD_GLOBAL              0 (range)
              2 LOAD_CONST               1 (10000)
              4 CALL_FUNCTION            1
              6 GET_YIELD_FROM_ITER
              8 LOAD_CONST               0 (None)
             10 YIELD_FROM
             12 POP_TOP
             14 LOAD_CONST               0 (None)
             16 RETURN_VALUE

To show the speed gain:

python -m timeit -s 'from somefile import f, g' 'list(f())'
1000 loops, best of 3: 507 usec per loop

python -m timeit -s 'from somefile import f, g' 'list(g())'
1000 loops, best of 3: 396 usec per loop

set vs list membership tests

Checking for membership in a list over and over is slow, worst case being O(N). To fix this, make word_list a set, which yields O(1) lookup:

python -m timeit -s "x = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']" "'FULL JOIN' in x"
10000000 loops, best of 3: 0.0781 usec per loop

python -m timeit -s "x = set(['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN'])" "'FULL JOIN' in x"
10000000 loops, best of 3: 0.0246 usec per loop

So create the set like:

def getTableName(...):
   ~snip~
   wordKey = set(['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN'])

Though it might be even better to move this out of the getTableKey function entirely so you aren't paying for the re-construction of this set during every iteration:

# add a positional arg for it
def getTableKey(parsed, wordKey):
    # rest of func

And define it in getTableAttribute like:

def getTableAttribute(dataFrame, queryCol, date):
    wordKey = set(['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN'])
    ~snip~
    for row in dataFrame:
        table_name = getTableName(row, wordKey)

getTableName

There's no need to enclose sqlparse.parse in parens, as it will just default to whatever the enclosed value is:

x = (5)
x
5

You are losing speed calling set(list(iterable)), since set will consume any iterable, and it looks like getWord(stream) is an iterable already:

    table   = set(getWord(stream))

re.compile

If you are going to call a regex many times, it is better to compile it once, then call compiled.sub where compiled is the output of re.compile("<expression>"):

 python -m timeit -s 'import re; x = "abc123"' 'for i in range(100000): re.match("\w\d", x)'
10 loops, best of 3: 67.5 msec per loop

python -m timeit -s 'import re; x = "abc123"; y = re.compile("\w\d")' 'for i in range(100000): y.match(x)'
10 loops, best of 3: 28.1 msec per loop

To make this work, you might consider adding an arg in getTableName to allow for a compiled regex:

# somewhere in getTableAttribute.py file
import re
def getTableAttribute(dataFrame, queryCol, date):
    tableName       = []
    attributeName   = []
    table_re        = re.compile(r'^.+?(?<=[.])')
    df              = pd.DataFrame()
    for row in dataFrame[queryCol]:
        table       = getTableName(row, table_re)
        # rest of code

def getTableName(sql, re_expr):
    ...
    for item in table:
        tabl = re_expr.sub('', item)
        # rest of code


String helper functions in NASM Win16 Assembly

There's plenty to optimize here!

In NASM you get the address simply by writing mov di, prompt. This has a shorter encoding than lea di, [prompt]. (In MASM this would be mov  di, offset prompt giving the same benefit over the lea form).

Instead of writing the pair mov ah, 0x4c mov al, 0, you could combine these in 1 instruction as mov ax, 0x4C00. This shaves off 1 byte from the program.

Your getchar returns a byte in AX and your putchar expects a byte in DX. You would be better off if you used AL and DL. This would avoid those several mov ah, 0 and mov dh, 0 instructions.

Your putchar code uses the BIOS.Teletype function 0x0E. This function does not expect anything in the CX register. What it does require is that you specify the displaypage in the BH register. Simply add mov bh, 0 here. And if it's even possible that your program has to run on the graphical video mode then it would make sense to write mov bx, 0x0007 because then the color for the character is taken from the BL register.

I see that the getstring code also checks for the linefeed code 10. No one does that. If the user presses the Enter key, you'll receive the carriage return code 13 and that's the only code that you need to check. The linefeed code only comes into play when outputting.

The pair of instructions mov [di], al inc di (3 bytes) can be replaced by the 1-byte instruction stosb. Given that your program is in the .COM file format we have DS=ES and the direction flag is almost certainly going to be clear. Ideal for using the string primitive assembly instructions. This also means that your putstring routine could use lodsb if you're willing to trade in DI for SI as the input parameter.

An interesting optimization comes from eliminating a tail call. You wrote call putchar directly followed by ret. This is equivalent to writing jmp putchar. Both shorter and faster this way!

Make it better

Your getstring procedure must not allow the user to input more than 19 characters. Anything more would overflow the 20-byte buffer.
Your getstring procedure should store (in the buffer) a terminating zero when the finishing Enter key arrives. This way the buffer can be used repeatedly and not just this one time.
In assembly we want to avoid all kinds of jumping because those are more time consuming than many other instructions.
Your putstring code uses a je and a jmp instruction on each iteration of the loop. The code below only uses the jne instruction on each iteration.

; IN (di)
putstring:
    jmp     .first
.continue:
    call    putchar
    inc     di           ; move to the next character
.first:
    mov     al, [di]     ; grab the next character of the string
    cmp     al, 0
    jne     .continue
    ret

; IN (al)
putchar:
    mov     ah, 0x0E     ; BIOS.Teletype
    mov     bx, 0x0007
    int     0x10
    ret

Using DX as the input for putchar is a poor choice, not only because DL would be enough, but especially because you need the character in AL anyway. So why not move it there in the first place?

Be consistent

Always write your numbers the same way. You wrote mov ah, 0x4c and also mov ah, 0x0E.
I suggest you use capitals for the hexadecimal digits and always write as many digits as will fit in the destination. So don't write stuff like mov ah, 0xE.
In case you're wondering why I make this suggestion. Using uppercase hexadecimal digits enhances the contrast with the lowercase 0x prefix or lowercase h suffix. Readability is very important in a program.

mov ah, 0x4C
mov ah, 0x0E

or

mov ah, 4Ch
mov ah, 0Eh

For many programmers function numbers are easiest recognized when expressed in hexadecimal.
You could thus write mov ah, 0x00 int 0x16 in your getchar routine.

As a final note, your labels are well chosen and the comments that you've added are all to the point. Congrats...


Replacing values in a file based on values in another file

I’d go with:

def replace(word, threshold):
    """Convert any string ('word') that does not equal 'threshold'
    into: '?' if it is not an integer, '$' if it is lower than
    'threshold', or ' ' if it is greater than 'threshold'.
    """
    try:
        value = int(word)
    except ValueError:
        return '?'
    if value < threshold:
        return '$'
    if value > threshold:
        return ' '
    return word

def get_threshold(filename):
    """Read the first line of 'filename', split it around an '=' sign
    and convert the last part into an integer.
    """
    with open(filename) as f:
        return int(f.readline().split('=')[-1])

def process_file(data_file, threshold_file):
    """Replace data from 'data_file' according to the value found in
    'threshold_file'. Print the original data and then the converted
    one.
    """
    threshold = get_threshold(threshold_file)

    lines = []
    print('Original data:')
    with open(data_file) as f:
        for line in f:
            line = line.strip()
            print(line)

            # Join back the converted bits into a single line
            replaced_line = ' '.join(
                # Split the line at words boundaries and convert each
                # bit of text according to the threshold
                replace(chunck, threshold) for chunck in line.split())
            lines.append(replaced_line)

    print('\nData replaced with threshold', threshold)
    for line in lines:
        print(line)

# Does not execute anything unless run from the command line.
if __name__ == '__main__':
    # Call the main function of the program
    process_file('data', 'data.txt')

The key is to have simple functions that one can easily test in the interpreter and extensive documentation for trickier parts.

Docstrings should be enough to mostly describe what is going on; adapt to the intended audience. Using descriptive variable names can also improve the understanding.

For the processing of the data file, there are 3 possibilities:

 with open(data_file) as f:
     lines = [' '.join(replace(chunck, threshold) for chunck in line.strip().split())
         for line in f if not print(line)]

Pretty dense and it uses a test only for its side effect in order to avoid an f.seek(0) and an other iteration over the file. Not ideal. Definitely not the right choice for the purpose.
lines = []
with open(data_file) as f:
    for line in f:
        line = line.strip()
        print(line)

        lines.append(' '.join(replace(chunck, threshold) for chunck in line.split()))

Easier to read: an explicit loop reduce the complexity to decode the list-comprehension. It also allows to clean the lines before printing them and we still avoid an unnecessary f.seek(0). However, there is still a list-comprehension that might be hard to read (even with the comments) depending on your audience.
lines = []
with open(data_file) as f:
    for line in f:
        line = line.strip()
        print(line)

        converted = []
        for chunck in line.split():
            converted.append(replace(chunck, threshold))
        lines.append(' '.join(converted))

Each line is now easily understandable on its own.

I however prefer the second version since it is understandable and teaches good practices without being too aggressive. (the use of a generator expression is recommended here since we don't need the intermediate list.)

Talking about good practices:

using join is definitely better than the double for loop you use at the end of your code;
the if __name__ == '__main__': construct is recommended but can be confusing, remove it if you think it will be too much for your audience.


WPF: Model to View Model data binding to implement Two Step View

Here is how I redefined it now. Demo:

public MainWindow()
{
    InitializeComponent();

    var dvm = new DemoViewModel();
    var dm = new DemoModel();
    dvm.Text = dm.Select(m => m.Text); // bidirectional
    dvm.Text2 = dm.Select(m => m.Text); // bidirectional
    dvm.IsReadOnly = dm.Select(m => m.Text.Length > 4); // calculable
    DataContext = dvm;
}

Where:

class DemoModel : Model
{
    string _text = "";

    public string Text
    {
        get { return _text; }
        set { Set(() => Text, ref _text, value); }
    }
}

And (too verbose, but it is a stupid WPF thing):

class DemoViewModel : ViewModel
{
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(DemoViewModel));

    public static readonly DependencyProperty Text2Property =
        DependencyProperty.Register("Text2", typeof(string), typeof(DemoViewModel));

    public static readonly DependencyProperty IsReadOnlyProperty =
        DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(DemoViewModel));

    public Binding<string> Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetBinding(TextProperty, value); }
    }

    public Binding<string> Text2
    {
        get { return (string)GetValue(Text2Property); }
        set { SetBinding(Text2Property, value); }
    }

    public Binding<bool> IsReadOnly
    {
        get { return (bool)GetValue(IsReadOnlyProperty); }
        set { SetBinding(IsReadOnlyProperty, value); }
    }
}

Library classes:

class Model : ObservableObject
{
}

And:

Outdated - see below:

class ViewModel : FrameworkElement
{
    protected BindingExpressionBase SetBinding<T>
        (DependencyProperty dp, Binding<T> property)
    {
        var binding = new Binding("Value")
            { Source = property, Mode = BindingMode.TwoWay };

        return SetBinding(dp, binding);
    }
}

Now

public class ViewModel : DependencyObject
{
    protected BindingExpressionBase SetBinding<T>(DependencyProperty dp, Binding<T> property)
    {
        var binding = new Binding("Value")
        {
            Source = property,
            Mode = BindingMode.TwoWay
        };

        return BindingOperations.SetBinding(this, dp, binding);
    }
}

And:

public static class ModelBinding
{
    public static Binding<T> Select<TM, T>(this TM m, Expression<Func<TM, T>> mapper)
    {
        Mapping<TM, T> mapping = mapper;
        return new Binding<T>(() => mapping[m], v => mapping[m] = v, m);
    }
}

And:

public class Binding<T> : ObservableObject
{
    public static implicit operator Binding<T>(T value) => new Binding<T>(() => value);
    public static implicit operator T(Binding<T> property) => property.Value;

    public Binding(Func<T> getter, params object[] dataSources)
        : this(getter, v => { throw new NotSupportedException(); }, dataSources)
    {
    }

    public Binding(Func<T> getter, Action<T> setter, params object[] dataSources)
    {
        Getter = getter;
        Setter = setter;
        foreach (var npc in dataSources.OfType<INotifyPropertyChanged>())
            npc.PropertyChanged += (s, e) => RaisePropertyChanged("Value");
    }

    public T Value
    {
        get { return Getter(); }
        set { Setter(value); }
    }

    Func<T> Getter { get; }
    Action<T> Setter { get; }
}

And:

class Mapping<TSource, TTarget>
{
    public static implicit operator Mapping<TSource, TTarget>(Expression<Func<TSource, TTarget>> mapping) =>
        new Mapping<TSource, TTarget>(mapping);

    [DebuggerHidden]
    public Mapping(Expression<Func<TSource, TTarget>> mapper)
    {
        Getter = mapper.Compile().Invoke;

        try
        {
            var newValue = System.Linq.Expressions.Expression.Parameter(mapper.Body.Type);
            var assign = System.Linq.Expressions.Expression.Lambda<Action<TSource, TTarget>>(
                System.Linq.Expressions.Expression.Assign(mapper.Body, newValue),
                mapper.Parameters[0], newValue);

            Setter = assign.Compile().Invoke;
        }
        catch (ArgumentException)
        {
        }
    }

    public TTarget this[TSource source]
    {
        get { return Getter(source); }
        set { Setter(source, value); }
    }

    Func<TSource, TTarget> Getter { get; }
    Action<TSource, TTarget> Setter { get; }
}


I see two improvements, one of which Gert Arnold pointed on in a comment.

If an API method returns a list, collection or IEnumerable of anything, worse case scenario you should return an empty collection. I wouldn't even recommend returning a 404 Not Found because you are searching for multiple things. If returning a single resource, a 404 Not Found is appropriate, but not for returning a collection.
Abstract away the searching and generation of your view models into their own service. This makes it much easier to test your controller.

Moving query logic into a service

This is a three part process:

Create an interface for your service that exposes the minimal methods and parameters required for your controller to work
Create the service class that implements the interface
Use this service object in your controller through its interface

First, the interface:

public interface IVehicleService
{
    List<GlassModel> GetGlassModelQuantitesByCountry(string[] filterValues);
}

This has a single method that accepts the filter values, and returns a list of view models. I called it IVehicleService because the actual entity your are querying against is a Car (which really is a "vehicle" in the generic sense).

Before diving into the implementation of the IVehicleService interface, let's look at how the controller will use it.

public class LookupController : ApiController
{
    // GET api/Lookup
    [CacheOutput(ServerTimeSpan = 3600, ClientTimeSpan = 3600)]
    public List<GlassModel> Get(string filter)
    {
        if (string.IsNullOrEmpty(filter)) throw new ArgumentNullException(nameof(filter));

        using (var db = new LookupDbContext())
        {
            IVehicleService service = new VehicleService(db);
            IEnumerable<string> filterValues = filter.ToUpper().Split(',');

            return service.GetGlassModelQuantitesByCountry(filterValues );
        }
    }
}

This makes the controller very slim and easy to read. The ugliness of the query is hidden away in the service class.

public class VehicleService : IVehicleService
{
    public VehicleService(LookupDbContext context)
    {
        this.context = context;
    }

    private LookupDbContext context;

    public List<GlassModel> GetGlassModelQuantitesByCountry(IEnumerable<string> filterValues)
    {
        var salesCodes = GetSalesCodes(filterValues);
        var queryGlass = context.Countries
            .Where(c => salesCodes.Contains(c.Eurocode))
            .GroupBy(c => new { c.Countrycode })
            .Select(g => new
            {
                g.Key.Countrycode,
                Quantity = g.Sum(p => p.Quantity)
            });

        // build model
        return queryGlass.ToList().Select(x => new GlassModel
        {
            Coordinates = LocationHelper.GetCoordinatesByCountry(x.Countrycode),
            Country = x.Countrycode,
            Quantity = x.Quantity
        }).ToList();
    }

    private GetSalesCodes(IEnumerable<string> filterValues)
    {
        var make = filterValues[0];
        IQueryable<Car> filter;

        if (filterValues.Length == 1) // make
        {
            filter = context.Cars.Where(c => c.VehicleMakeName.Contains(make));
        }
        else if (filterValues.Length == 2) // make, model
        {
            var carModel = filterValues[1].Trim();

            filter = context.Cars.Where(c => c.VehicleMakeName.Contains(make)
                                          && c.VehicleModelName.Contains(carModel));
        }
        else // make, model, year
        {
            var model = filterValues[1].Trim();
            var year = Convert.ToDouble(filterValues[2]);

            filter = context.Cars.Where(c => c.VehicleMakeName.Contains(make)
                                          && c.VehicleModelName.Contains(model)
                                          && (c.FromYear <= year || c.FromYear == null)
                                          && (c.ToYear >= year || c.ToYear == null));
        }

        return filter
            .GroupBy(c => new { c.SalesCode })
            .Select(g => g.Key.SalesCode).ToList();
    }
}

Move "filter" logic into its own class

There is a slight problem here. The "filter" is a comma separated value string. We can improve this too by making a class called VehicleSearchFilter which will give you a strongly typed way to define the search parameters:

public abstract class VehicleSearchFilter
{
    public static VehicleSearchFilter Parse(string filter)
    {
        if (string.IsNullOrEmpty(filter))
            throw new ArgumentNullException(nameof(filter));

        string[] filterValues = filter.ToUpper().Split(',');
        string make, model;
        int? year;

        if (filterValues.Length > 0)
        {
            make = filterValues[0];
        }

        if (filterValues.Length > 1)
        {
            model = filterValues[1];
        }

        if (filterValues.Length > 2)
        {
            year = int.Parse(filterValues[2]);
        }

        return year == null
            ? new VehicleSearchFilter(make, model)
            : new VehicleSearchFilter(make, model, year);
    }

    public VehicleSearchFilter(string, make string model)
    {
        Make = make;
        Model = model;
    }

    public VehicleSearchFilter(string make, string model, int year)
    {
        Make = make;
        Model = model;
        Year = year;
    }

    public string Make { get; set; }
    public string Model { get; set; }
    public int? Year { get; set; }
}

Now your vehicle search service can use a VehicleSearchFilter object instead of a list of strings:

public class LookupController : ApiController
{
    // GET api/Lookup
    [CacheOutput(ServerTimeSpan = 3600, ClientTimeSpan = 3600)]
    public List<GlassModel> Get(string filter)
    {
        if (string.IsNullOrEmpty(filter)) throw new ArgumentNullException(nameof(filter));

        using (var db = new LookupDbContext())
        {
            IVehicleService service = new VehicleService(db);
            VehicleSearchFilter searchFilter = VehicleSearchFilter.Parse(filter);

            return service.GetGlassModelQuantitesByCountry(searchFilter);
        }
    }
}

And then a few changes to the VehicleService class to use this:

public class VehicleService : IVehicleService
{
    public VehicleService(LookupDbContext context)
    {
        this.context = context;
    }

    private LookupDbContext context;

    public List<GlassModel> GetGlassModelQuantitesByCountry(VehicleSearchFilter filter)
    {
        var salesCodes = GetSalesCodes(filter);
        var queryGlass = context.Countries
            .Where(c => salesCodes.Contains(c.Eurocode))
            .GroupBy(c => new { c.Countrycode })
            .Select(g => new
            {
                g.Key.Countrycode,
                Quantity = g.Sum(p => p.Quantity)
            });

        // build model
        return queryGlass.ToList().Select(x => new GlassModel
        {
            Coordinates = LocationHelper.GetCoordinatesByCountry(x.Countrycode),
            Country = x.Countrycode,
            Quantity = x.Quantity
        }).ToList();
    }

    private GetSalesCodes(VehicleSearchFilter filter)
    {
        var make = filterValues[0];
        IQueryable<Car> filter;

        if (filter.Year == null && filter.Model == null)
        {
            filter = context.Cars.Where(c => c.VehicleMakeName.Contains(filter.Make));
        }
        else if (filter.Model != null)
        {
            filter = context.Cars.Where(c => c.VehicleMakeName.Contains(filter.Make)
                                          && c.VehicleModelName.Contains(filter.Model));
        }
        else
        {
            filter = context.Cars.Where(c => c.VehicleMakeName.Contains(filter.Make)
                                          && c.VehicleModelName.Contains(filter.Model)
                                          && (c.FromYear <= filter.Year || c.FromYear == null)
                                          && (c.ToYear >= filter.Year || c.ToYear == null));
        }

        return filter
            .GroupBy(c => new { c.SalesCode })
            .Select(g => g.Key.SalesCode).ToList();
    }
}

This gives you some compile time checks for your queries, plus it centralizes the parsing of the make, model and year values (which is generic enough I imagine you use it elsewhere too).


Hashtag Creator: Find frequent words and display their occurrences

From what I can tell, the "weirdest" thing in your code is the following:
Avoid list comprehensions if all you want are side-effects
In your Word class you have the following:
def add_sentences(self, *sentences):
    [self.sentences.append(s) for s in sentences]

That is a weird function because generally list comprehensions are created because we care about the list they actually build, not because we want side-effects.
Therefore, if you wanted to create a loop to do the .append you do, you would write something like
def add_sentences(self, *sentences):
    for s in sentences:
        self.sentences.append(s)

Having said that, your sentences is an iterable so what you can do is
def add_sentences(self, *sentences):
    self.sentences.extend(sentences)

*args is nice but not always necessary
Now, if we keep dissecting this function, we see that it is often called with a single argument, which is an iterable (usually a list), so while the *args pattern is nice, it is useless if everything you are going to do is call the function with
word.add_sentences(*iterable)

The *args syntax is useful for when you don't know how many arguments you are getting and it makes sense to call the function with many arguments.
For your use case, I don't think we will see things like
the = Word("the")
the.add_sentences("The cat is nice", "I love the Python language")

This means that you can very well define your code to be
def add_sentences(self, sentences):
    self.sentences.extend(sentences)

And later you call it with
word.add_sentences(list_of_sentences)


Normalize Sparse Matrix along rows in C++ Eigen

I'd put the Eigen headers below the STL headers.  Also, <math.h> should be <cmath>, the latter being the C++ library incorporated into the std namespace.
You can define main() below the other functions, allowing you to save a bit of room by eliminating the function prototypes.
You don't need that flushing with std::endl.  To get just a newline, output a "\n".
main() doesn't need an explicit return 0.  As reaching this point implies success, the compiler will do this return for you.
You shouldn't use an int here:

for(int i = 0; i < weights.size(); ++i)
  {
    sm_weights.insert(i,i) = weights[i];
  }

If you had your compiler warnings up high (and they should be), you should've been told about a type-mismatch here.  The type for i should instead be std::size_type (an unsigned type), which is the return type of size() for each STL container class.
For this for loop:

for (int j = 0; j < sm.row(i).nonZeros(); ++j)
  {
    my_sum += (*val_ptr * (*val_ptr));
    val_ptr++;
  }

val_ptr++ can still be put into the loop statement:

for (int j = 0; j < sm.row(i).nonZeros(); ++j, val_ptr++)
{
    my_sum += (*val_ptr * (*val_ptr));
}

I'm also unsure about all the raw pointer use here.  Raw pointers in C++ should be kept to a minimum, so there may be a way to do this without using any of them.
You pass sm by value in both of your functions, however, it doesn't look like you're trying to allow the compiler to perform move semantics.  But you're also using the argument in such a way that it's only being read for writing to other values.  In such a case, you should pass sm by const&.


Program that removes comments from C and C++ programs

I see some things that may help you improve your code.

Use all required #includes

The program uses the bool type and assert() but doesn't have the associated required includes.  Fix that by adding this:

#include <stdbool.h>
#include <assert.h>

Use required #defines

As noted in http://en.cppreference.com/w/c/io/fopen :

  As all bounds-checked functions, fopen_s is only guaranteed to be available if STDC_LIB_EXT1 is defined by the implementation and if the user defines STDC_WANT_LIB_EXT1 to the integer constant 1 before including .

Because it's an optional part of the C11 standard, it's also non-portable in a strict sense.  For portability, you may wish instead to use the standard fopen and do your own error checking instead.

Think of the user

There are a few user-oriented things I think could be improved.  First, it would probably be better to have the filenames passed in via the command line rather than being hardcoded, and second, it would probably be good to allow the user to specify whether the timing is displayed or not.

Fix the bug

There is a problem with the parser at the moment.  If we have lines like these:

/* comment one *///  comment two

the code should remove both comments, but at the moment, it only removes the first one.

Use better variable names

Variables named s_QUOTED and d_QUOTED are OK because their names suggest their meanings, but c, d and flag are not good names.

Consider using named states

It would likely make the code easier to write correctly with named states.  One convenient way to do that is to use an enum.

enum { INCODE, INQUOTE, INDBLQUOTE, INCOMMENT, GOTSLASH } state = INCODE;

Use one line per declaration

The code currently includes lines like this:

bool DOUBLESLASH_Comment = 0, ASTERISK_SLASH_Comment = 0, flag = 0;

It makes things a little bit harder to read than if you put them on separate lines like this:

bool DOUBLESLASH_Comment = 0;
bool ASTERISK_SLASH_Comment = 0;
bool flag = 0;

Additionally, while it's not strictly incorrect, it helps the reader if the code uses false and true rather than numeric values for boolean variables.

Simplify your code

The code currently includes this compound if statement:

if (flag == 1)
    flag = 0;
else
    flag = 1;

This can be simplified:

flag = !flag;

Use braces appropriately

In a number of cases, as with the if statement mentioned above, curly braces ({}) were not used, but they are used for each case statement.  In fact, they're not needed in either case, but I'd recommend using braces for constructs such as for, while and if and omitting them for case.

Return something useful from functions

The RemoveComments function is currently written to return int but the only value it ever returns is 0. I'd recommend either returning something useful, such as, for instance a number of comments removed, or to change it to a void function.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Improvment of and looping in a regular expression pattern

Firstly, just for anyone who might read this: DO NOT take this as an excuse to parse your XML with regular expressions. It generally a really really bad idea! In this case the XML is malformed, so its the best we can do.

The regular expressions looping constructs are * and {4} which you already using. But this is python, so you can construct your regular expression using python:

expression = """
<menu>
<day>\w{2} (\d{2}\.\d{2})\.</day>
<description>
"""

for x in xrange(3):
    expression += "<p>(.*)</p>"

expression += """
</description>
</menu>
"""


Lagrange Interpolation over quadrilateral points

I would use a struct with copy constructor instead of a class with clone. Performance wise it would be better and would be more readable.

Extract function for your condition in the while.

Add explicit parenthesis on complex arithmetic expressions (normal people don’t read operator precedence fluently). ( I think about this part B * Y / 4 )

Seems like you do six times the same thing with your points. Extract method somehow and name it appropriately (cross or whatever it is).


Implementation of the linked list data structure in C++

Namespace

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

The term "linked list" is a common term. So I would expect somebody out there is already using the macro LINKEDLIST_H. When somebody uses that library and your library then you will get some funny interactions.

As a result I would make the include guards a little more unique. When I define header guards they include the full namespace and the the file name in the include guard.

Which brings me to namespace. All your work is in the global namespace. Which can lead to collision in names (Again LinkedList is a common type name). So creating a unique namespace for your code could be useful (I like the Java method of using your domain name).

#ifndef THORSANVIL_UTIL_LINKED_LIST_H
#define THORSANVIL_UTIL_LINKED_LIST_H

namespace ThorsAnvil
{
     namespace Util
     {

class LinkedList
{
};

     }
}
#endif

Containers Vs Smart Pointers

There are two common techniques for managing dynamic memory: Containers and Smart Pointers. Since the job of the container is to perform memory management so delegating this to Smart pointers is counter productive.

Secondly shared_ptr should not be your first choice of smart pointer. The shared pointer has significant overheads.

template <typename T> using ptr = std::shared_ptr<T>;

Given the choice I would prefer std::unique_ptr when you are expressing ownership, but simply use a normal RAW pointer inside function where no owner knowledge is needed.

Private Membership

template <typename V>
class LinkedList
{
private:
    class Node
    {

The class LinkedList::Node is exposed as public. Exposing this class exposes implementation details. Exposing implementation details makes your class much more brittle and harder to change.

Constructor

default constructor

    public:
        Node() : next{} {}

A default constructor. Do you need it. This can only be used when the object type V os default constructible. Conversely if the type V is not default constructible this constructor can not be used. Which would mean that certain portions of your class are unusable.

Construction

        Node(V _data) : next{}, data{_data} {}

This constructor passes _data by value. This means _data is copied into the function then it also copied again into the member. So you have multiple copies. Normally I would pass by const reference to avoid at least one copy.

Additionally in C++11 we introduced move semantics. This can thought of as an optimized copy. You should try and define your class to use move semantics so that you can remove the additional copy.

Also introduced in C++11 were variadic templates and perfect forwarding. This can be used to build objects in place using their own constructors very easily. This allows us to build the objects into the container with creating an external copy.

So if we put all three of these together I would write the Node class like this.

        struct Node
        {
            Node*   next;   // not owned.
            V       data;

            Node(V const& data)
                : next(nullptr)
                , data(data)
            {}
            Node(V&& data)
                : next(nullptr)
                , data(data)
            {}
            template<typename... Args>
            Node(Args&& args...)
                : next(nullptr)
                , data(std::forward<Args>(args)...)
            {}
        };

Head Tail Vs Sentinel

    ptr<Node> head;
    ptr<Node> tail;

Sure you can use a singly linked list and head and tail. Personally I prefer to use a doubly linked list and a sentinel (there are several other questions on code review where I explain this technique in detail).

Using a sentinel object allows you to write code without having to worry about nullptr this can considerably simplify the code.

The additional benefit (of the sentinel technique) is that you have a node in your chain that can be used by the end iterator (one past the end of the list).

Const member functions

    size_t size(){ return _size; }

    bool isEmpty(){
        if(head == nullptr) return true;
        else return false;
    }

Functions that do not mutate the state of the object should be marked const. Note: When passing around large objects to functions it is quite common to pass them by const reference. This means you can only call const methods on the object.

    size_t size() const { return _size; }

if test anti pattern

    bool isEmpty(){
        if(head == nullptr) return true;
        else return false;
    }

This is an anti pattern. There is no need to perform a test and return true/false. Simply return the value of the test.

    bool isEmpty() const
    {
        return (head == nullptr);
    }

Error

What happens when index is greater than size?

    V operator[](int index){
        int _c {};
        ptr<Node> tmp = head;
        while(tmp!=nullptr){
            if(_c == index){
                break;
            }
            tmp = tmp->getNext();
            _c++;
        }

        // I bet this de-reference a null ptr
        // Does it.
        return tmp->getData();
    }

Name your function appropriately

This may traverse the list. But that is not what it is actually doing. The traverse is just a side effect of the action you are taking.

    void traverseList(){
        {
            ptr<Node> tmp = head;
            while(tmp!=nullptr){
                std::cout << tmp->getData() << std::endl;
                tmp = tmp->getNext();
            }
        }

To me this looks like a print function name it as such. Also it always prints to std::cout. Why not pass the stream you want to print to (it can default to std::cout.

     void printList(std::ostream& str = std::cout)
     {
         // Code as before
     }
     // Then just for giggles we add a friend function to make
     // printing more C++ like.

     friend std::ostream& operator<<(std::ostream& s, LinkedList const& ll)
     {
         ll.printList(s);
         return s;
     }


Filter non-duplicate objects from collection

The important flaw in your code is runtime complexity.  reduce, indexOf and includes all have runtimes that are linear (O(n)) in the size of the array.  You're running the latter two once for every iteration of reduce, giving a quadratic (O(n2)) runtime.  Doubling the length of the input will quadruple the running time.

A secondary flaw is excess regular human-brain complexity: it's more lines of code and data structures than are needed.

The typical approach involves a single hash table to count duplicates and just two lines of code: one to count, one to filter:

var countKeys = {};
values.forEach( value => countKeys[value.name] = (countKeys[value.name] || 0) + 1 )
const duplicates = values.filter( value => countKeys[value.name]>1 );

const values = [
  {
    name: 'Duplicate 1',
    value: [1,2,3],
  },
  {
    name: 'Duplicate 2',
    value: [1,2,3],
  },
  {
    name: 'Duplicate 1',
    value: [1,2,34],
  },
  {
    name: 'Duplicate 2',
    value: [1,2,3],
  },
  {
    name: 'Duplicate 2',
    value: [1,2,3],
  },
  {
    name: 'Not Duplicate',
    value: [1,2,3],
  },
];

var countKeys = {};
values.forEach( value => countKeys[value.name] = (countKeys[value.name] || 0) + 1 )
const duplicates = values.filter( value => countKeys[value.name]>1 );
console.log(duplicates)
<p>


CS50 pset-1 itsa Mario - make a half-pyramid using parameters from user input

Organized coding

A line of a pyramid is made by x spaces and y hashes. The number of spaces is given by the total line length minus the number of hashes. The number of hashes increases from 2 to 5, the max line length is 5

static int LINE_LEN = 5;
for (int hashes = 2; hashes <= LINE_LEN; hashes++) {
    print_repeated_char(' ', LINE_LEN - hashes);
    print_repeated_char('#', hashes);
    printf("\n");
 }

Also note the print_repeated_char function avoids repetition.


Compute intersections of all combinations of vectors in a list of vectors in R

Your approach seems reasonable, but there are some simplifications you can make.

First, your construction of name is needlessly complex.  This works just as well:

name <- paste(names(l)[indices], collapse="_")

Second, you can call unique on each element of l at the outset which eliminates the need to specify an init value to Reduce (and thus reducing all the calculations by one call to intersect). It also shortens the arguments to intersect since duplicates have already been eliminated.

l <- lapply(l, unique)

These two give a function

overlap <- function(l) {
  results <- list()
  # Remove duplicates within each entry of l
  l <- lapply(l, unique)

  # combinations of m elements of list l
  for (m in seq(along=l)) {

    # generate and iterate through combinations of length m
    for (indices in combn(seq(length(l)), m, simplify=FALSE)) {

      # make name by concatenating the names of the elements
      # of l that we're intersecting
      name <- paste(names(l)[indices], collapse="_")

      results[[name]] <- Reduce(intersect, l[indices])
    }
  }
  results
}

Further elimination of duplicate work would involve recognizing that higher order interactions, as you are determining them now, are repeating the intersections of the lower orders (that is foo_bar_bat first intersects foo and bar and then intersects that with bat, but the intersection of foo and bar was already determined). And "first" order interactions are just the arguments passed through unique (as they were simplified in the previous iteration).

overlap <- function(l) {
  results <- lapply(l, unique)

  # combinations of m elements of list l
  for (m in seq(along=l)[-1]) {

    # generate and iterate through combinations of length m
    for (indices in combn(seq(length(l)), m, simplify=FALSE)) {

      # make name by concatenating the names of the elements
      # of l that we're intersecting
      name_1 <- paste(names(l)[indices[-m]], collapse="_")
      name_2 <- names(l)[indices[m]]
      name <- paste(name_1, name_2, sep="_")

      results[[name]] <- intersect(results[[name_1]], results[[name_2]])

    }
  }
  results
}

If you really want to eliminate more duplicate calculations, you can assign names(l) outside both loops and length(l) outside the outer loop.


byte sign;
double sum, A0,tmp;

Keep variables to the most inner scope where they can be defined.

sign = 1;
A0 = A[k][k];
if(A0 < 0){
    sign = -1;
}

sign can be assigned to a ternary expression

sign = A0 < 0 ? -1 : 1;

tmp = sign*Math.sqrt(sum);
v[k] = tmp + A0;
tmp = Math.sqrt(2*(sum + A0*tmp));
v[k] /= tmp;

EDIT Oops screwed up, the maths on v[k] evaluation... too many times...

EDIT 2 changing tmp to have the right value for the inner loop.

I would reduce the calculation to this:

    double sqrSum = sign*Math.sqrt(sum);
    double tmp = Math.sqrt(2*(sum + A0*sqrSum));
    v[k] = (sqrSum  + A0) / tmp;

This is trying to store the value in v[k] just once, instead of accessing it twice.

  if there's a better way to return the values than arraylist, like if
  double[][][] would be faster. I have had issues with recasting
  double[][][] arrays to double[][] however.

Well in the end you know that you are returning an Array with two entries, the first being transpose(Q), and the second being A. This is pretty simple to achieve both on the implementation and the caller as long the method is properly documented.

Return on implementation

return new double[][][]{
    transpose(Q),
    A
}

Use on caller

var result = householder(...);
var transpose = result[0]; //documentation says entry 0 has the transpose
var a = result[1]; //documnentation says entry 1 has A

Resulting code

public static double[][] householder(double[][] A) {
    int m = A.length; // rows
    int n = A[0].length; // cols
    double[] v = new double[m];
    double[][] Q = identity(m);
    for(int k = 0; k < n; k++) {
        double sum = 0;
        byte sign = A0 < 0 ? -1 : 1;
        double A0 = A[k][k];
        for(int i = k; i < m; i++) {
            sum += A[i][k]*A[i][k];
        }
        double sqrSum = sign*Math.sqrt(sum);
        double tmp = Math.sqrt(2*(sum + A0*sqrSum));
        v[k] = (sqrSum  + A0) / tmp;
        for(int i = k+1; i < m; i++) {
            v[i] = A[i][k]/tmp;
        }
        for(int j = 0; j < n; j++) {
            sum = 0;
            for(int i = k; i < m; i++) {
                sum += v[i]*A[i][j];
            }
            for(int i = k; i < m; i++) {
                A[i][j] -= 2*v[i]*sum;
            }
        }
        for(int j = 0; j < m; j++) {
            sum = 0;
            for(int i = k; i < m; i++) {
                sum += v[i]*Q[i][j];
            }
            for(int i = k; i < m; i++) {
                Q[i][j] -= 2*v[i]*sum;
            }
        }
    }
    return new double[][][]{
        transpose(Q),
        A
    }
}

  Changing all the ints to shorts, i was concerned with casting

Don't bother with it. In the end all of it will be running mostly on cpu registers which can hold 32 bits, incrementing 16 or 32 bits costs mostly the same and you shouldn't be bothered by that.

  I only need sign to be a bit

This is almost effectively the same as evaluating sign to be +1 or -1 once. keeping this on a variable makes you code cleaner. Pre-optimization is the rule of all evil, first you need to make sure your code is maintainable, understandable, follows design principles, and optimally that you chose the best data structures and kept the algorithm running time to a minimum, although that also falls in the optimization hole is not as aggressive as going into the last details like you referring to.

  should I write sum = 0.0?

Meh floating point is not my area of expertise but what I think is even if there is a difference on the representation between 0 and 0.0 which there isn't, you end up with slightly errors of accuracy.

  should I initialize the for loop int i's and j's outside of the loop
  to save memory?

No. Compilers do a great job optimizing trivial things for you, such as this and also the ones mentioned before. In the end the cpu will need to increment a variable, hopefully that variable will be on the cpu register or in cache, if not will be on the stack (ram). The variations between this can be different depending on how you write your code but it is the sort of things that you if you are truly worried about then you go into onto other languages like C and ultimately assembly.

On variable declaration and assignment.

This seems to be a topic a little bit out of your knowledge, let's get some of those doubts sorted.

Historically, in languages like C, variable names were declared at the beginning of a method, or scope. The reason being that if you didn't do that way the compiler would give you a warning. I suspect that this warning could be due to possible inefficiency on the usage of the stack, but I'm not totally positive for this (at least this seem to be a plausible reason for those warnings).

Thus, like I told you, things on the internals can change a little bit depending how/where you declare you variables. Compilers can use registers differently, stack can be managed differently, cache can be used differently and so on. However in Java this is thing that is mostly out of your control, unless you go to take a peek to the bytecode and how that code would translate into assembly you really can't do much about it. That's why you move onto C or assembly if you are concerned about those things.

Some algorithm pseudo-codes also follow the same strategy.

This is primarily why you will often see declaration of variables at the beginning of a method or scope.

However things work differently on Java and some other languages (I would say most of them but I think that would push the boundaries). In Java the compiler does not give you a warning for where you are declaring a variable. However for readability variables tend to be declared at the beginning the scope, notice that I said scope and not method this time. Variables can also be declared in the first moment when you have everything needed to assign them.

Like I told you tmp in this algorithm can be defined in the first for body, however it could also be defined on the first inner for body. There are two reasons however to why you should declare on the outer for.

tmp is needed to assign a value to v[k].
The evaluation of Math.sqrt(2*(sum + A0*sign*Math.sqrt(sum))) is expensive and only needs to be evaluated once. To make sure that this is only evaluated once for each k, this variable needs to be assigned out of the inner for body.


Throwing exceptions if there is not exactly one box retrieved

I'd suggest you just get rid of the throwing method and throw it in the retrieveBox method like this:

throw new BoxNotFoundException("box not found");

You should catch it outside this method and handle it, do the logging etc when you catch it. Logging is part of exception handling and should be done when the exception is being handled, not before.


Nginx configuration, with global defaults and support for a PHP site

I compared the two server configurations and the only thing that appears to match between the two is the location ~ \.php$ directive, as well as the index directive, though in the latter configuration that is under the directive location /

Perhaps the common configurations could be put into the file included via include (i.e. fastcgi-php.conf).


Parsing JSON in one go using state machine solution

Variable Names

Apart from the odd (non PEP8 compliant) variable casing, you also have a temp variable.  Names like temp are frowned upon as they convey nothing about what that variable represents.

Repeated Tests

You do seem to repeat the tests c==',' or c=='}': a couple of times (lines 26 and 42. I think this could be refactored into using a test string, similar to your NoOps variable.

For example, on line 42, instead of:

        if c in NoOps or c==',' or c=='}':

You could just do

        if c in NoOps or c in CloseOps:

Assuming you had a variable CloseOps defined in the preamble, like this:

 CloseOps = ",}"

The same thing would apply for the repeated use of this test condition on line 26.

Repeated Logic

The following code (lines 45 - 49 inclusive):

        if lastKey:
                result[lastKey]=lastValue
                lastValue=''
                lastKey=''
        state=READY

Appears to be an (almost) verbatim repeat of the logic contained upon lines 29 - 33 (inclusive):

            if lastKey:
                result[lastKey]=lastValue
                lastValue=''
                lastKey=''
                state=READY

Functional Decomposition would dictate that such repeated logic be refactored into it's own function.

Numbers aren't Strings!

There exists a flaw in your code (which was not present in the answer code to your last question), where-by JSON-encoded numbers are turned into strings in your resulting dict.

If you (using your parse function implementation from this question) do:

 >>> type(parse('{"foo":"1"}')['foo'])

This yields:

 <type 'str'>

(Which is fine, since here "1" should be a string.  However:

 >>> type(parse('{"foo":1}')['foo'])

Also yields:

 <type 'str'>

Which indicates an error, as this should be <type 'int'> if the JSON were decoded properly.


Design of Experiments data structure with C++17

Because you're defining your member functions within the class declaration, you don't need to use the inline keyword. All member functions declared in the class declaration are implicitly inline (including the default and copy constructors) are inline.
In your copy constructor, you can make use of member initializers to construct the copied maps directly, rather than default construct and assign:
doe_model(const doe_model& doe): required_explorations(doe.required_explorations),
    next(required_explorations.end()), number_of_explorations(doe.number_of_explorations)
}

There are a few places where you're using two statements but they can be combined.
In update_config, you can decrement in the test:
if (--number_of_explorations.at(config_id) <= 0)

In get_next, you can combine the iterator increment and return statement:
return ++next;

This also uses the preincrement on the iterator, as it avoids creating a copy of the original iterator that is returned by the postincrement version, then immediately discarded.
In add_config, you have the potential of adding a config with a higher number of required explorations than are provided if that config already exists (if required_explorations is assigned to, no change is made to number_of_explorations). This may or may not be a problem.
You should consider adding a move constructor and a move assignment operator, which can avoid creating copies.


Loop through object and send analytics code based on objects properties value

Should I be checking if the main function's argument is an object?

No, document it as it accepts objects, the params are straight forward no need to check them for the consumer

Is there a way I wouldn't have to check if the campaignCode is falsy? Could I check it in the if statement of the for loop?

No need to loop just access the property directly

campaignCode = lookupTable[prop];

Am I declaring the analyticsTrack function in the correct way?

Yes and no, every time you invoke the main function you are allocating the method.  There are no closures around it so it doesn't need to be done.  Just move it outside of the main method but wrap everything in a self invoking method (if you are not already with some other tool) so it won't be global.

If I had to rewrite everything here is how I would do it.  Instead of having a bunch of if path contains x then do something with the campainCode statements I  just put it in an object.  It might be overkill but it is a good pattern to use in other places.  Say you want to handle books instead of adding another if indexof .. just add books to the pathsHandlers object.

(function() {

    function analyticsTrack(id) {
        return Bootstrapper.insertScript('//www.example.com/click/services/Tracking/Click.ashx?CR_EAC=' + id);
    }

    var pathHandlers = {
        topics: function(campaignCode) {
            analyticsTrack(campaignCode)
        },
        courses: function(campaignCode) {
            $(window).on('message', function(e) {

                // check the message from the iframe, fire a RIO tag
                if (e.originalEvent.data === 'play button clicked') {
                    analyticsTrack(campaignCode);
                }
            });
        }
    }

    window.analytics.campaign.main = function(lookupTable) {
        var path = window.location.pathname,
            campaignCode = lookupTable[path],
            handlerKey;

        if (campaignCode) {
            for (handlerKey in pathHandlers) {
                if (pathHandlers.hasOwnProperty(handlerKey) && path.indexOf(handlerKey) > -1) {
                    pathHandlers[handlerKey](campaignCode);
                }
            }
        }
    };

})();

--edit to answer comment

Your function was defined in the main function but it didn't need to be because it wasn't using any locally scoped variables in main (no variables being accessed in the function via closure).

If the method was for example :

window.analytics.campaign.main = function (lookupTable) {
    var path = window.location.pathname,
        campaignCode = '',
        prop;

    function analyticsTrack (id) {
        console.log('current path is ' + path)
        return Bootstrapper.insertScript('//www.example.com/click/services/Tracking/Click.ashx?CR_EAC=' + id);
    }

The method couldn't be moved outside of main because it is referencing the path variable within a closure.


Find Triangle Triplets from a list of given numbers

First thing to comment on after copying and pasting into my IDE, the following line gives a warning:

int size = vec_input.size();

  Implicit conversion loses integer precision: 'size_type' (aka 'unsigned long') to 'int'

Apparently, the size() method of Vector returns an unsigned long, and we should use this type for our size, rather than int.

unsigned long size = input.size();

Functions that return void but accept (and modify) an argument passed by reference are always a warning sign for me.  Here, I don't think there's a particularly good reason to do so.

Here, I can't see any good reason to be doing so.  We create and return a vector within the function, and only accept the input argument.

Another problem I see: the result we're giving the caller is a vector of vectors, and the inner vectors are supposed to always have exactly 3 values in it.  Why don't we create a struct to represent the triplets?

struct Triplet {
    int a;
    int b;
    int c;
}

Now we can return a vector of these.

I would also abstract that complex conditional into its own function.

bool isTriplet(int a, int b, int c) {
    return ((a + b) > c) && ((a + c) > b) && ((b + c) > a);
}

Now, putting all that together, without changing the algorithm or any of the logic, the code looks like this:

#include<vector>
#include<iostream>

struct Triplet {
    int a;
    int b;
    int c;
};

bool isTriplet(int a, int b, int c) {
    return ((a + b) > c) && ((a + c) > b) && ((b + c) > a);
}

std::vector<Triplet> findTriangleTriplets(std::vector<int> input) {
    std::vector<Triplet> triplets;
    unsigned long size = input.size();

    for(int i=0;i<size;++i) {
        for(int j=i+1;j<size;++j) {
            for(int k=0;k<size;++k) {
                int a = input.at(i);
                int b = input.at(j);
                int c = input.at(k);

                if(isTriplet(a, b, c)) {
                    Triplet t = Triplet{a,b,c};
                    triplets.emplace_back(t);
                }
            }
        }
    }

    return triplets;
}

int main()
{
    std::vector<Triplet> triplets;
    std::vector<int> vec_input { 1, 2, 3, 4, 5, 6 };

    triplets = findTriangleTriplets(vec_input);
    for ( auto &x : triplets)
    {
        std::cout<<x.a<<" "<<x.b<<" "<<x.c<<"\n";
    }

    return 0;
}


make_auto implementation for C++03 compilers

Disclaimer: this is not an attempt to answer your technical question, but suggesting alternatives to reach some compromise of your stated goals. It wouldn't fit in a comment :-)

I am not sure it is a good idea to actually write a make_auto. It is akin to rearranging the deck chairs on the Titanic. After it hit the iceberg.

You'd be better off with emulating a std::unique_ptr using C++98/03 features. Howard Hinnant has one version on his website. You might even get lucky and get its macro variadic version to work nicely with the std::make_unique proposal by Stephan T. Lavavej.

I'd take that as the preferred option, with using boost::shared_ptr or boost_scoped_ptr as the preferred alternative option. If you insist on keeping std::auto_ptr, make its use as painful as possible. Without pain, you'll find it more difficult to convince your colleagues to upgrade to C++11.

Please also make sure to introduce your team to the other language emulation features that Boost provides (Foreach, Move).


Don't use the Singleton pattern

  But do you think it is really thread safe good singleton?

Please excuse my pedantry and let me say that the only good use of the Singleton pattern is to not use it at all. This is not to say that a program should never have just a single instance of a class. On the contrary, it is a perfectly reasonable thing at times. Just don't couple the “unique object” property to the type itself as the pattern does. Instead, write a normal class with a public constructor and let another class provide a unique instance of it. The internet is full of rants about the Singleton pattern and good reasons why not to use it so I'll leave it at that.

Watch your #includes

If you're using the typeid operator, you must #include the <typeinfo> header first.

The #include "stdafx.h", on the contrary, is non-portable and annoying. Get rid of it.

For std::runtime_error, you don't need the <exception> but the <stdexcept> header.

Use vertical and horizontal white-space for better readability

It might be just an artifact of copying and pasting your code from your editor into the web browser but as it stands, your code is not very well formatted.

I would put a blank line between functions and classes as well as after the #include directives at the top. The only blank line in your code is – in an empty function body.

There are many opinions about the optimal amount of horizontal space you use to indent your code and I'm okay with most styles. What is not okay is inconsistency. Pick one style and stick to it. Some lines of your code appear completely off. For example, the closing brace of Singleton::getinstance (looks as if it were the end of the class) or the try in main.

Any decent editor can re-indent the code for you at the press of a button.

What's this std::atomic_flag?

I'm not sure what problem exactly the Singleton::flag member is supposed to solve but I'm pretty sure that there's a better way. If you don't want client code to instantiate your singleton class directly (which, as mentioned, is a poor decision, but ignore that for now) just make the constructor private. Then the compiler can enforce at compile-time that nobody except the singleton provider instantiates it. This is much better than checking at run-time and crashing the program.

Reconsider the heap allocation

I don't see why you have to allocate your singleton instance dynamically. The only situation where I could imagine a problem with static deinitialization is if you refer to the object from within a function registered as an std::atexit handler. On the contrary, dynamically allocating the object and then “leaking” it might cause leak detectors such as Valgrind to give you “false” positives that obscure more severe issues with your code. I prefer code to always clean up everything such that it is Valgrind clean. If you're writing a library, it is even more frustrating for your users to get leaks reported that they cannot do anything about.

Returning a reference is fine

I see many Singleton implementations for C++ returning a pointer just because they can. I like your choice of using a reference better.

You don't need an empty destructor

Your inline definition of a non-virtual empty destructor adds nothing. It might only confuse people whether you might have actually forgotten to put a delete of the instance there. (In which case it would of course have been better to use a std::unique_ptr and again write no destructor.)

Make deleted member functions public

It might sound counter-intuitive at first but making deleted members functions public gives you better error messages. It also makes sense if you think about it: The fact that your type is not copyable is part of its public interface.

Did you mean MyClass to inherit privately from Singleton<MyClass>?

I think it would be less surprising if you'd inherit publicly because then you could also say MyClass::getinstance() instead of the more verbose and less intuitive Singleton<MyClass>::getinstance().

The code in MyClass is completely redundant

If you delete everything inside the MyClass body, your program does the exact same thing. I'm sure that you did intend something by writing it but made some mistake (such as accidentally making the constructor public) that renders it useless as it stands.

Get rid of the getchar abomination in main

Don't make your program block on an I/O operation just because you want the terminal emulator window stay open. Instead, learn how to use the emulator such that the window stays open even after the program finished.

If you really want it, it should be std::getchar and you need the <cstdio> header.

How I would do it

Putting the previous advice together, I would solve the problem like this.

template <typename T>
struct singleton_provider
{
  static T&
  instance()
  {
    static T theinstance {};
    return theinstance;
  }
};

struct my_class
{
  my_class(const my_class&) = delete;
  my_class& operator=(const my_class&) = delete;
};

using my_class_provider = singleton_provider<my_class>;

It is a lot simpler, more efficient, doesn't leak memory and – most of all – doesn't couple the logic how objects of a class are instantiated and their lifetime is managed in a program to its type.


Use a better container

The main issue is that std::vector<int> is a bad container for storing a set of ASCII characters. Every vector allocates on the heap, and an empty vector is likely 24 bytes in size. So this is huge waste. Why not use a container designed to hold a series of ASCII characters, like... std::string!

Do you need to store all possible combinations in memory?

You are first building a vector of all possible combinations with the desired sum. But the only thing you are doing with it afterwards is writing the result to a file. That's a huge waste of memory, and maintaining the vector of vectors in itself costs some CPU time as well. Why not write the results to a file immediately?

Exit early when your combination has already exceeded the desired sum

You always try to fill the vector values with characters elements, and try each possible element at each position. However, in brute(), you should calculate the partial sum of elements 0 up to n, and then just check in the for loop whether adding i to that sum would be equal to or higher than the desired sum. If so, if it's equal output the combination, but in any case return at that point instead of trying other values.

Use \n consistently to end lines

You are mixing \n, \r\n and std::endl in your code. Stick to \n, it is the standard way of ending a line in C and C++. The underlying I/O routines will automatically convert the newlines to \r\n on Windows.

std::endl is equivalent to \n plus a call to flush(). Unless there is a good reason to, you don't want this extra flushing to happen, since it reduces the performance of your program. Normally, std::cout is line-buffered, so if something ends with a \n, it is already flushed automatically. This also means you should remove the explicit call to cout.flush().


Proper techniques for allowing many views to subscribe to window.unload?

An opinion question, always tricky;

I think we can all agree that the second approach is not KISS and requires more bandwidth to download to the browser. As far as I can tell, this will not save any memory either..

I would strongly suggest to use the first approach.

Furthermore:

unsubscribe could be reduced to:

unsubscribe: function (view) {
  this.get('views') = _without( this.get('views') , view );
}

Production code should not use console.log
subscribe could use _.union()
subscribe could be reduced to:

subscribe: function (view) {
  this.get('views') = _union( this.get('views') , view );
}


Find the third largest element in the array in linear time

I think overall it is well done, it is clear and readable. Some general tips:

You can make the parameter a varargs, which makes it easier to call:

public static int findThirdLargest(int... numbers)
...
int thirdLargest = findThirdLargest(1, 2, 3);

Since you check for the size of the array, you could perhaps also check if it is not null.
This is somewhat personal, but I would always declare and initialise each variable on a separate line, e.g.:

int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
int thirdLargest= Integer.MIN_VALUE;

To me it helps readability and potentially refactoring later on.

I'd remove the newline after the for loop opener. It decreases readability for me.

Nice that you added tests! You covered some good cases. You could take a look at Hamcrest matchers, you can create some nice declarative tests with it. They can also show quite decent messages in case a test fails.

Some extra tips about the current tests:

I'd split up the tests in a couple of different methods
Personally, I like to use static imports, so you can write:

assertEquals(1, findThirdLargest(1, 2, 3))

Also do not forget to test for failing cases. Test that when you pass less than 3 numbers, you expect an exception.

And what should the output of findThirdLargest(1, 1, 2, 2, 3, 3) be?

Lastly, a follow up exercise: how would you implement it if the user wants to find the k-th largest element?


Parsing very simple CSS into selector and declarations (as as single piece)

Some helper functions can make the query look a lot cleaner. LINQ is quite readable on it's own but in your case it has gotten a bit more complex and it's not exactly easy to modify something.

Example of how the main method can look:

public static IDictionary<string, string> Parse(string css)
{
    return GetSelectorMatches(css.Minify())
        .Select(match => new {match, selectors = ExtractSelectorsByPattern(match, ",")})
        .SelectMany(t => SelectorToDeclarationValue(t.selectors, t.match))
        .ToDictionary(pair => pair.Key, pair => pair.Value);
}

Where the methods have similar implementation to this one.

private static IEnumerable<Match> GetSelectorMatches(string css)
{
    return Regex.Matches(css, @"(?<selectors>[a-z0-9_\-\.,\s#]+)\s*{(?<declarations>.+?)}",
        RegexOptions.IgnoreCase).Cast<Match>();
}

private static IEnumerable<string> ExtractSelectorsByPattern(Match match, string pattern)
{
    return Regex.Split(match.Groups["selectors"].Value, pattern).Where(s => !string.IsNullOrEmpty(s));
}

private static IEnumerable<KeyValuePair<string, string>> SelectorToDeclarationValue(
    IEnumerable<string> selectors, Match match)
{
    return selectors.Select(selector => new KeyValuePair<string, string>(
        selector.Trim().ToLowerInvariant(),
        match.Groups["declarations"].Value.Trim()));
}

I'm not sure if it makes sense to have .Where(s => !string.IsNullOrEmpty(s)) in the method like this maybe additional bool parameter removeEmpty can decide that.

Besides that you can use some Dependency Injection to modify the delegates passed in most of the methods as they're quite specific I really cant provide an example of that as I'm not aware what makes sense to your project to be modifiable and what not.

You can even go one step further and implement some sort of class hierarchy and pass interfaces instead.


A few points:

You can simplify the if loop by using the else condition.
Getting input should be at the beginning of the while loop, because it makes more logical sense to put it there. It's what happens every time you restart.
You can use the simple condition of True for your while loop.
You don't need the continue keyword, as it is at the end of your loop.

count = 0
while True:
    userName = input("Hello! Welcome to FaceSnap! \n\nUsername: ")
    password = input("Password: ")
    count += 1
    if count == 3:
        #tells user bye
        break #exit
    else:
        if userName == 'elmo' and password == 'blue':
            #let them in
            break #they are in, exit loop
        else:
            #tell them it is wrong and have them retry, stay in loop


Calculating mesh centers runs very slowly

There are two things I would try to change:

Is it necessary, that center_x and center_y are 2-dimensional arrays? In your code, the 2nd dimension holds redundant information and should be avoided.
The biggest problem with pure Python (but often the greatest benefit ;) ) is that it is an interpreted language and numerically heavy operations should be handled with library functions. In your case, I would try to exploit numpy's array features and calculate the center as

center_x = 0.5 * (delta_x[:ncol-1] + delta_x[1:])


Disclaimer: I don't know Android. I've wrote two or three programs for it.

Also, I don't have your full code so can't be sure about some of the classes this code relies on.

Test name has an "and", seems like two tests?
Test throws Exception, do you have tests for that?
You don't need to start test name with tests, unless you use JUnit 3.
When LooperThread runs, it calls Looper.prepare() and Looper.loop(). What these do?
LooperThread extends Thread, why not implement Runnable? You only implement run() then?
Further reinforcement to point 1) - you have more than one assertion. If verify buckles, other assertions aren't tested. Is that fine?
Why do you need a final boolean[] threadBlocked = {true}; over just a final boolean? I found no other reference than to that one element, via threadBlocked[0]?
Is this test alone it it's class? If so, I'd extract mocking out of it. Readability / clarity / easier to spot things.
Have you tried structuring the test into classic given - when - then or assess - act - assert?


HTML

Your HTML should have a DOCTYPE declaration.  Nowadays, the HTML 5 doctype (<!DOCTYPE html>) is considered standard practice.

You should always declare a charset, and the charset should be UTF-8.  The <title> element is required.

In an  tag, the alt attribute is considered mandatory, and in this case there are very obviously appropriate descriptions to assign to each image.

You are using a
 to do the layout, for content which is not semantically tabular.  This is considered vulgar in HTML: the document should represent the meaning, and the layout should be performed using CSS.  (The user agent might not be a typical graphical browser; it might be a screen reader for the sight-impaired.)  The semantically appropriate element to use should be an
 ordered list.  The fruits should be listed in first, second, and third place in the document.

CSS

For ease of maintenance, avoid repeating declarations.  For example, you can set the font-family just once on an ancestor element.  Also, you can write the transform: scale(0.75) declaration just once, using a .silver, .bronze selector.

How can we change the display order using CSS?  Using the CSS order property would be really nice, but it relies on CSS flex boxes, which is a newer feature.

body {
    background-color: #AAFF00;
    font-family: 'Lato', sans-serif;
    text-align: center;
}

div.fruits {
    display: inline-block;
    width: auto;
}
div.fruits p {
    margin-top: 0;
    color: #000000;
    font-size: 50px;
}
div.fruits p span.score {
    font-weight: bold;
}

ol, li { /* CSS reset: make lists not work like lists */
    list-style: none;
    margin: 0;
    padding: 0;
}

ol {
    display: flex;
}
li {
    display: inline-block;
}
li.silver {
    order: -1;
}
.silver, .bronze {
    transform: scale(0.75);
}

li img {
    display: block;
}
li span.score {
    position: relative;
    top: -25px;
    border: 1px solid black;
    padding: 12.5px;
    font-size: 25px;
}
li.gold .score {
    background-color: gold;
}
li.silver .score {
    background-color: silver;
}
li.bronze .score {
    background-color: #CD7F32;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Top three fruits</title>
    <link rel='stylesheet' type="text/css" href='https://fonts.googleapis.com/css?family=Lato'>

Highest Fruit Score: 83

 83

 65

 34

For compatibility, we can resort to using floats to put the silver element on the left.  A very unfortunate consequence of that hack is that the width of the list needs to be hard-coded to help position the floats properly.

body {
    background-color: #AAFF00;
    font-family: 'Lato', sans-serif;
    text-align: center;
}

div.fruits {
    margin-left: auto;
    margin-right: auto;
    width: 750px; /* Unfortunately hard-coded width */
}
div.fruits p {
    margin-top: 0;
    text-align: center;
    color: #000000;
    font-size: 50px;
}
div.fruits p span.score {
    font-weight: bold;
}

ol, li { /* CSS reset: make lists not work like lists */
    list-style: none;
    margin: 0;
    padding: 0;
}

li {
    display: inline-block;
    width: 250px;
}
.silver, .bronze {
    transform: scale(0.75);
}

/* Change the display order to silver-gold-bronze */
li.silver {
    float: left;
}
li.bronze {
    float: right;
}
ol:after {
    clear: both;
}

li span.score {
    position: relative;
    top: -25px;
    border: 1px solid black;
    padding: 12.5px;
    font-size: 25px;
}
li.gold .score {
    background-color: gold;
}
li.silver .score {
    background-color: silver;
}
li.bronze .score {
    background-color: #CD7F32;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Top three fruits</title>
    <link rel='stylesheet' type="text/css" href='https://fonts.googleapis.com/css?family=Lato'>

Highest Fruit Score: 83

 83

 65

 34


Generating random permutation with forced change of order (Secret Santa)

I would suggest breaking the actual permutation algorithm out into its own function, since it’s useful on its own. That would pretty much solve the readability problem.
And then I would suggest doing the permutation with indices, rather than copying the whole input vector. (Indices would also work for other range types, especially if you limit the input range type to random-access, which is not unreasonable for a sorting algorithm.) Once you’re dealing with indices, detecting positions that are unchanged is trivial, and quick:
template <std::sized_range Rng, typename Gen>
requires std::uniform_random_bit_generator<std::remove_reference_t<Gen>>
auto get_fully_permuted_indices(Rng const& rng, Gen&& gen)
{
    auto idxs = std::vector<std::size_t>(std::ranges::size(rng));
    std::iota(idxs.begin(), idxs.end(), std::size_t(0));

    auto permuted = false;
    do
    {
        std::ranges::shuffle(idxs, gen);

        permuted = true; // hope for the best!
        for (auto i = std::size_t(0); i < res.size(); ++i)
        {
            // if the value at i is the same as i, then this is not properly permuted
            if (i == idxs[i])
            {
                permuted = false;
                break;
            }
        }
    } while (not permuted);

    return idxs;
}

Once you have that, your main function is trivial:
std::map<std::string, std::string> getPermutation(const std::vector<std::string>& participants)
{
    auto const idxs = get_fully_permuted_indices(participants, std::mt19937{std::random_device(){}});

    auto res = std::map<std::string, std::string>{};
    for (auto i = std::size_t(0); i < std::ranges::size(participants); ++i)
        res.emplace(participants[i], participants[idxs[i]]);

    return res;
}

I would also suggest moving the creation of the RNG out of the function, and passing the RNG in as an argument:
template <typename Gen>
requires std::uniform_random_bit_generator<std::remove_reference_t<Gen>>
auto getPermutation(const std::vector<std::string>& participants, Gen&& gen)
{
    auto const idxs = get_fully_permuted_indices(participants, std::forward<Gen>(gen));

    auto res = std::map<std::string, std::string>{};
    for (auto i = std::size_t(0); i < std::ranges::size(participants); ++i)
        res.emplace(participants[i], participants[idxs[i]]);

    return res;
}

This goes with the doctrine of “one function, one job”, and allows both reusing the RNG, and testing the function with a known RNG.
If you want to go even further, an “is-fully-permuted-indices” algorithm, to remove that for loop in get_fully_permuted_indices(), also seems useful:
template <std::input_range Rng>
requires std::equality_comparable_with<std::ranges::range_value_t<Rng>, std::size_t>
constexpr auto is_fully_permuted_indices(Rng const& rng)
{
    auto idx = std::size_t(0);
    for (auto&& item : rng)
    {
        if (item == idx++)
            return false;
    }

    return true;
}

template <std::sized_range Rng, typename Gen>
requires std::uniform_random_bit_generator<std::remove_reference_t<Gen>>
auto get_fully_permuted_indices(Rng const& rng, Gen&& gen)
{
    auto idxs = std::vector<std::size_t>(std::ranges::size(rng));
    std::iota(idxs.begin(), idxs.end(), std::size_t(0));

    do
    {
        std::ranges::shuffle(idxs, gen);
    } while (not is_fully_permuted_indices(idxs));

    return idxs;
}


Convert hex to base64 (Cryptopals challenge 1)

pub fn hex_to_base64(hex: &str) -> String {
    encode(&hex_to_bytes(hex))

I would not use self::base64::encode and instead refer to base64::encode here so that it is clearer what is being encoded.

}

pub fn hex_to_bytes(hex: &str) -> Vec<u8> {
    hex.chars()
        .collect::<Vec<_>>() //convert to slice-able

Given that you are doing hex, which is all in the ASCII range, you may want to use as_bytes() which will give you a slice of bytes without copying the whole string into a new Vec.

        .chunks(2)           //each char is one nibble

What happens if the string length isn't a multiple of two?

        .map(|byte| byte.iter().collect::<String>())

byte isn't correct here as it is a slice of chars. Further, if you don't use chars() as I suggest as above, you can use std::str::from_utf8 to get a &str without allocating a new String.

        .map(|byte| u8::from_str_radix(&byte[..], 16).unwrap())

byte really isn't correct here as you have a String.  Additionally, there is no need to take a slice.

        .collect()
}


Because you're comparing your performance with that of the WriteableBitmapEx project, you might like to compare your algorithm with theirs, which is here on github: WriteableBitmapShapeExtensions.cs

You say your performance isn't much slower than theirs (100 versus 170 MPixels/second).

A difference between yours and there's might be that yours is using float or double arithmetic, whereas theirs is using int arithmetic.

Their code is much longer (more lines of code) than yours, but their inner loop is something like this:

        for (int x = x1; x <= x2; ++x)
        {
           pixels[index] = color;
           ys += incy;
           y = ys >> PRECISION_SHIFT;
           if (y != previousY)
           {
              previousY = y;
              index += k;
           }
           else
           {
              ++index;
           }
        }

Note:

Only int (not double)
Few branches
Every write is to a significant pixels (in your algorithm if you write a line at 45 degrees then you do 1.414 writes per pixels).