Calisthenics objects, and primitive wrapped in Objects

That cannot work with this Object hierarchy. You have a contradiction in your katas, that requires some messy stuff.

Here's an extract of the katas of your previous similar Question (emphasis mine):

  One level of indentation per method
  Don’t use the ELSE keyword
  Wrap all primitives and Strings
  First class collections
  One dot per line
  Don’t abbreviate
  Keep all entities small (50 lines)
  No classes with more than two instance variables
  No getters/setters/properties

You're dealing with two double values of distinct meaning (a discount rate and a cost). Because of kata Wrap all primitives, you wrap them both in two, distinct object.

Now you need these primitives (the doubles) to interact (multiply). No Object  can access both values, since the kata No getters prevents one from accessing the other's internal values!

A Solution

You've successfully made two primitives interact elsewhere. It was in the Euro class:

public Euro add(Euro valueToAdd) {
    Euro newPrice = new Euro(amount + valueToAdd.amount);
    return newPrice;
}

A primitive wrapper is able to make interactions with a primitive wrapper of the same type, or with a subclass of it. Then that is what you should do: all double wrappers that will want to interact must extend a common double wrapper. (Note 1: I didn't spot any rule against subclassing, yet you did not subclass anything. Note 2: does subclassing bypass kata No classes with more than two instance variables? Don't need it, just curious).

So here's the code:

MonetaryQuantity.java (Edit: Changed the name, fits better) is a parent class to all stuff that will ever interact with money etc.)

public class MonetaryQuantity {
    protected double value; // Can be accessed by any Money-related class
    public MonetaryQuantity(double theValue) {
        value = theValue;
    }
}

Euro.java:

public class Euro extends MonetaryQuantity{
    public Euro(double amount) {
        super(amount);
    }
    public Euro apply(Discount discount) {
        Euro newAmount = discount.applyOn(this);
        return newAmount;
    }
    public Euro add(Euro valueToAdd) {
        Euro newPrice = new Euro(value + valueToAdd.value);
        return newPrice;
    }
}

Discount.java:

public class Discount extends MonetaryQuantity{
    public Discount(double theValue) {
        super(theValue);
    }
    public Euro applyOn(Euro price) {
        // Discount can access Euro.value because both handle money (similar business sphere)
        return new Euro(price.value * value);
    }
}

Notes on style

Why do you apply a Euro on a Discount? Usually, we apply a Discount on a Price. I prefer price.apply(discount). I kept discount.applyOn(price).

Naming value on Euro is a bit clumsy. It may be a cost, or a price, those things are different. Maybe two subclasses?

Naming value on Discount is just bad. It should be a rate. The Object might even be called a DiscountRate, because you could have an AbsoluteDiscount (-10€). Discount would be an interface with a Euro applyOn(Euro price) method. Note I moved the implementation of the discount from the Euro class to the Discount class for just that reason. Euro just forwards it to Discount.

Note: with these Katas, I cannot extract an add and a multiply method into the wrapper class (although I would really like it!) because it would have to return the proper Wrapper sub-class (not the primitive result). It would only work with C-style result-passing in parameters AND require a setValue():

public class MonetaryQuantity {
    public <T extends MonetaryQuantity> T add(MonetaryQuantity valueToAdd, T returnValue) {
        double newValue = value + valueToAdd.value;
        returnValue.set(newValue); // This is against a kata!
        return newValue;
    }
}

This is all quite frustrating.

The equals() method

It's broken everywhere. It fails with ClassCastExceptions, NullPointerExceptions etc. Make instanceof checks and handle the mismatch cases properly.


Removing the logging and using set comprehension :

def _mounted_drives(possible_device_letters=string.ascii_uppercase):
    return {l for l in possible_device_letters if os.path.exists(l + ':')}

If you do want the logging but you do not care about it being done once every device is found :

def _mounted_drives(possible_device_letters=string.ascii_uppercase):
    s = {l for l in possible_device_letters if os.path.exists(l + ':')}
    for l in s:
        logging.info('Found device ' + l)
    return s


Decorator to convert a function's result into the desired units

Your proposal…

Length.from_velocity_time(100*u.km/u.s, 100*u.h, result_unit=u.AU)

… is less conventional and not any better than

Length.from_velocity_time(100*u.km/u.s, 100*u.h).to(u.AU)

In addition, monkey-patching the from_velocity_time() function to support a special result_unit named parameter feels slimy.

The only drawback with .to(…) is that pure numbers wouldn't support such a method.  But that would mean that the calculation is complete nonsense anyway.


TL;DR: See end of answer for updated code with suggested improvements

While I don't have many suggestions regarding nested for-loops, as you only seem to have two of them, I do have a few other suggestions:

Suggestions

1. Use with for file opening

You use try/finally to open/close your files, and while you're absolutely right to close your files, Python's with statement takes care of this for you. Another lesser-known characteristic of the with statement is that you can "nest" them in a single line, which is useful in your case.

So, I would recommend updating

try:
    input_file = open(input_file_path)
    output_file = open(output_file_path, 'w')
    ...  # Do stuff
finally:
    input_file.close()
    output_file.close()

to

with open(input_file_path) as input_file, open(output_file_path, "w") as output_file:
    ...  # Do stuff

When the context of the with statement is exited, your opened files will automatically be closed.

2. Clean up variable naming

Python convention is to use lower snake-case for normal variable names and function names - Camel-case (upper) is usually only used for class definitions. Therefore, I would recommend renaming your checkSequenceCharacters and checkSequenceLength functions to check_sequence_characters and check_sequence_length, respectively. This might be considered nitpicking, but maintaining consistent naming conventions always makes things easier for me.

3. Use str in str, instead of checking individual equality

In check_sequence_characters, you can more easily ensure that each character in seq is in an allowed set of characters using the following:

if any(c not in "AGTC" for c in seq):
    raise ValueError("Not a valid sequence (A/G/T/C ONLY)")

4. Raise Exceptions, instead of printing "ERROR"

There are a few places in your example where you print error messages. That's fine if you really don't want to raise actual exceptions, but that does seem to be the behavior your code is dancing around. I would recommend reading Python's documentation on raise if you're unfamiliar with it.

5. Use if __name__ == "__main__" when running module as source

If you don't know what if __name__ == "__main__" means, check out this explanation. Basically, my recommendation is to start using this pattern even if it may not be strictly necessary in your example (although it does protect you from the lurking seq name-shadowing bug). This will facilitate maintenance of your code should you need to import your example code as a module in the future, for example.

6. Use enumerate to loop through input_file with line index

Instead of using the line_location variable, you can remove the line_location = 0 line, and change

for line in input_file:
    line_location = line_location + 1

to

for line_location, line in enumerate(input_file):

If you still want line_location to be 1-indexed, just add 1 when you print/write it below.

Other Notes

For more recent versions of Python, you'll need to use input instead of raw_input
If there is any chance your output file has not already been created by you (which seems likely), you should open it using mode="x", which will create and open the file
If any of the subdirectories in the output file path have not already been created, you'll need to use something like os.makedirs to handle directory creation
The line print("[*] FILE CREATED AT: " + output_file_path) near the bottom may be misleading, as the output file is created when you call open, not when you call write. This means that even if count == 0, an output file was created (albeit a blank one)
In the provided suggested code, I removed the lines variable, since it isn't used; however, if you actually do need it for something not shown in your example, it can be safely re-added, along with the lines.append(line) line
I would recommend embracing Python's string format method, instead of using + to construct strings

TL;DR

If you decide to follow the above suggestions, your code will probably end up looking something like this:

import os
import re

def check_sequence_characters(seq):
    if any(c not in "AGTC" for c in seq):
        raise ValueError("Not a valid sequence (A/G/T/C ONLY)")

def check_sequence_length(seq):
    if len(seq) != 5:
        raise ValueError("Has to be exactly 5 letters long!")

def _execute():
    seq = raw_input("Enter a 5 basepair sequence using only A,G,T,C: \n")
    count = 0
    check_sequence_characters(seq)
    check_sequence_length(seq)
    input_file_path = os.getenv("HOME") + "/Desktop/sequencer/inputfile.txt"
    output_file_path = os.getenv("HOME") + "/Desktop/sequencer/output/" + seq + ".txt"

    with open(input_file_path) as input_file, open(output_file_path, 'x+') as output_file:
        for line_location, line in enumerate(input_file):
            arr = re.findall(seq, line)

            if arr and arr[0] == seq:
                count += 1
                print("[+] Sequence found at line " + str(line_location + 1))
                output_file.write("Line " + str(line_location + 1) + ": " + line + "\n")

        if count != 0:
            print("[*] Matches: " + str(count))
            print("[*] FILE CREATED AT: " + output_file_path)
        else:
            raise RuntimeError("No matches found!")

if __name__ == "__main__":
    _execute()


Check input

Your comments mention that url shouldn't be null, so it's best to make sure that it really isn't:

    if (url == null) {
        throw new IllegalArgumentException("url cannot be null");
    }

Nested if statements

        if (paramParts.length == 1) {
            if (name.equals(paramParts[0])) {
                return null;
            }
        }

You have this principle three times. It can be written as:

        if (paramParts.length == 1 && name.equals(paramParts[0])) {
            return null;
        }

Although I would rewritten your if statements like this:

        if (paramParts.length > 0 &&  name.equals(paramParts[0])) {
            switch(paramParts.length) {
                case 1:
                    return null;
                case 2:
                    return paramParts[1];
                default:
                    return param.substring(name.length() + 1);
            }
        }

And are you sure that paramParts.length == 2 (now case 2) is really needed? I think the other cases cover it.

Use early return

If you return early, you can reduce nesting:

if (split.length != 2) {
    return error;
}

Tests

The specification for prosperos says:

  each field/value pair is separated from each other and from the rest of the URL by a ";" (semicolon).

You are never testing if this would work, and it wouldn't:

String prosperoParam = prospero.getProsperoParam(new URL("http://a:a@a.a.a/a.a;a=a;b=b"), "b", null);
assertEquals(prosperoParam, "b");

If you want to change the spec, I would comment on it in the Java doc (something like: See RFC 4157, but note that this implementation uses '&' instead of ';' for the separation of field/value pairs (it still does use ';' for the separation between the first field/value pair and the rest of the URL).

Also, sometimes you use == to compare strings in your tests, I would replace it with equals.


I think at least the relationship between Professor and Course is many to many.

courses_professors = db.Table(
    db.Column(db.Integer(), db.ForeignKey("course.id"),
    db.Column(db.Integer(), db.ForeignKey("professor.id"))

class Course(db.Model):
    id = db.Column(db.Integer(), primary_key=1)
    name = db.Column(db.String(128), unique=1)

class Professor(db.Model):
    id = db.Column(db.Integer(), primary_key=1)
    name = db.Column(db.String(64))
    courses = db.relationship("Course", secondary=courses_professor, backref=db.backref("professors")

If the relationship between Professor and College is also many to many, you can also define a association table between them as preceding codes.


Simplify simple object clear function with Javascript

The clear function relies on the global data variable. This could be more portable by passing the object in as the first argument, and then the fields as the second argument

clear(data); // clear all
clear(data, "one"); // clears the "one" field
clear(data, ["one", "two"]); // clears multiple fields

Checking if (fields !== undefined) will accept null values as a field name. A "truthy" check is probably what you need:

if (fields) {
  // ...
} else {
  // ...
}

What does "clear" mean? Your code assumes that all fields in an object should be cleared out to an empty string. What if the original value was a boolean, or number? Maybe you want to set that field to null instead. Better yet, maybe set it to null then delete the field:

data[field] = null;
delete data[field];

Other than that, it looks pretty good.


TypeScript, checking for keys and subkeys and its variants

Find invalid cases first then return early. In this case, it looks like the initial goal.status check is primarily for presence check. You can remove that from the entire logic and put it up front, returning 0 early.

Now the whole point of TypeScript is to provide types to your data so you won't be doing unnecessary type checks in code. In the case of pendingIncoming, pendingOutgoing and investedAmount, they're numbers. The type for status should at least define them as number. Without a value, they should at least be initialized to 0. That should remove the unnecessary conditions.

With that, your code is essentially just:

getAlreadySaved(goal: GoalModel): number {
  const status:Status = goal.status;

  if(!status) return 0;

  // If we can assume they're numbers, we can safely say we can do math.
  return status.investedAmount + status.pendingIncoming - status.pendingOutgoing;
}


Parsing an XML file with elements for keys and values

This isn't the answer you want. But, _ is most commonly the discard variable.
You use it when you don't want to use the variable, but you need to specify a variable.
Take:

for _ in range(10):
    print('hi')

We don't want the output from the range, we just want to print 'hi' ten times.
And so you should not use this for the variable you use .clear() on.

I'd use zip rather than the try-except.
Sure there's Look Before You Leap (LBYL) and Easier to Ask for Forgiveness than Permission (EAFP).
But you don't need to use either here.
Also, by using zip you can change your while loop to a for loop too.

And so you should be able to get something like:

import xml.etree.ElementTree

elements = {}
xml_iterator = xml.etree.ElementTree.iterparse('file.xml')

for (_, elem1), (_, elem2), (_, elem3) in zip(xml_iterator, xml_iterator, xml_iterator):
    elements[elem1.text] = elem2
    elem1.clear()
    elem2.clear()
    elem3.clear()


The complexity of your approach is actually
$$\mathcal{O}\Big((N + M)\frac{(N + M - 2)!}{(N-1)!(M-1)!}\Big),$$ but using a dynamic programming algorithm you can drop it to \$\Theta(MN)\$:

#include <iostream>
#include <chrono>

#define ROW 15
#define COL 15

void pathCount(int (&matrix)[ROW][COL], int M, int N, int m, int n, int &paths) {
    if (m == M - 1 && n == N - 1 && matrix[m][n]) {
        ++paths;
        return;
    }

    if (m == M || n == N || !matrix[m][n]) {
        return;
    }

    pathCount(matrix, N, M, m, n + 1, paths);
    pathCount(matrix, N, M, m + 1, n, paths);
}

int pathCount(int (&matrix)[ROW][COL], int M, int N) {
    int paths = 0;
    pathCount(matrix, M, N, 0, 0, paths);
    return paths;
}

int pathCountV2(int (&matrix)[ROW][COL], int M, int N) {
    if (!matrix[0][0])
    {
        // The starting cell is not traversable.
        return 0;
    }

    int aux[ROW][COL];

    bool zero_encountered = false;

    for (int y = 0; y < ROW; ++y)
    {
        if (zero_encountered)
        {
            aux[y][0] = 0;
        }
        else if (!matrix[y][0])
        {
            aux[y][0] = 0;
            zero_encountered = true;
        }
        else
        {
            aux[y][0] = 1;
        }
    }

    zero_encountered = false;

    for (int x = 1; x < COL; ++x)
    {
        if (zero_encountered)
        {
            aux[0][x] = 0;
        }
        else if (!matrix[0][x])
        {
            aux[0][x] = 0;
            zero_encountered = true;
        }
        else
        {
            aux[0][x] = 1;
        }
    }

    for (int y = 1; y < ROW; ++y)
    {
        for (int x = 1; x < COL; ++x)
        {
            aux[y][x] = matrix[y][x] ? aux[y - 1][x] + aux[y][x - 1] : 0;
        }
    }

    return aux[M - 1][N - 1];
}

static long long get_milliseconds() {
    return std::chrono::duration_cast<
           std::chrono::milliseconds>(
           std::chrono::system_clock::now().time_since_epoch()).count();
}

int main(int argc, char** argv) {
    int matrix[ROW][COL];

    for (size_t y = 0; y < ROW; ++y) {
        for (size_t x = 0; x < COL; ++x) {
            matrix[y][x] = 1;
        }
    }

    matrix[ROW / 2][COL / 2] = 0;
    matrix[2][3] = 0;

    long long ta = get_milliseconds();
    int path_count = pathCount(matrix, ROW, COL);
    long long tb = get_milliseconds();

    std::cout << "Paths: " << path_count << " in " << tb - ta << " ms."
              << std::endl;

    path_count = 0;

    ta = get_milliseconds();
    int path_count2 = pathCountV2(matrix, ROW, COL);
    tb = get_milliseconds();

    std::cout << "Paths: " << path_count2 << " in " << tb - ta << " ms."
              << std::endl;

    return 0;
}

The space complexity of the above algorithm is also \$\Theta(MN)\$, but it can be easily improved to \$\Theta(\min\{M, N\})\$ by processing one column or row at a time.


HexToString function returning maximum of 16kb

Just a few comments.

First, I'd change the loop a bit. Instead of:

for (int i = 2; i < HexString.Length / 2; i++)
// ...
     HexString.Substring(i * 2, 2);

I'd use something like:

for (int i=2; i<HexString.Length-1; i += 2)
// ...
    HexString.Substring(i, 2);

Note the Length - 1 though--if we happen to be passed a string with odd length, we don't want to index beyond its end.

Secondly, at least for general use, you almost certainly do not want this to catch the exception and display a MessageBox. The basic reason for using exception handling to start with is that a low-level function like this doesn't know (and shouldn't care) how such an exception will be handled/displayed, whether to continue execution after it happens, etc.


Use an array and a function

You've got quite a few pieces of code that look very similar. The more menu items you have, the worse this gets. This is almost always a sign you should start using a function. Here's how to do that:

<?php

  $menuItems = array('Link One'   => 'one.php',
                     'Link Two'   => 'two.php',
                     'Link Three' => 'three.php',
                     'Link Four'  => 'four.php');

  function navigationItem($title,$page)
  {
    $class = (strpos($_SERVER['REQUEST_URI'],$page) !== false) ? ' class="active"' : '';
    return '
'.$title.'
'.PHP_EOL;
  }

?>

      <button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

      </button>
      Company Name

<?php

  foreach ($menuItems as $title => $page) echo navigationItem($title,$page);

?>

As you can see I've put both lines, which you repeat four times, inside the function and simply call that function four time. I could have done that by simply writing:

<?php
  echo navigationItem('Link One','one.php');
  echo navigationItem('Link Two','two.php');
  echo navigationItem('Link Three','three.php');
  echo navigationItem('Link Four','four.php');
?>

but I prefer to have the menu at the top of the file in an array. This makes it easier to find and edit.

This was probably the next step you were looking for. But it should not be your last.

You could easily generalize the navigationItem() function for all list items you will make. And the foreach loop basically builds a list, why not make a function out of that?

After that you could make a class which could build a whole menu bar for you. The functions will become methods of that class.

Why not put the array in a seperate file with the other stuff that defines your site? Perhaps eventually create a database table with menu items?

There are many ways in which you can improve this tiny piece of code.

What you should definately NOT do is: Build a whole site with Bootstrap HTML code interspersed by piece of loose PHP code. That will be chaos, and very difficult to maintain and expand. Be systematic about it.

Preferably try to avoid putting piece of PHP code inside HTML pages. It's just so ugly. Personally I prefer to write in pure PHP, and generate the HTML using objects similar to the class I suggested for your menu bar.


Writing to file using TPL with ConcurrentQueue

Let’s try to get rid of ConcurrentQueue. And Task.Run – those are expensive ones. It also makes sense to use async file access – which is a way more lightweight.

public class LogWriter
{
    public static LogWriter Instance = new LogWriter();

    LogWriter()
    {
        Enabled = true;
        Cts = new CancellationTokenSource();
        Task = Task.CompletedTask;
    }

    bool Enabled { get; set; }
    CancellationTokenSource Cts { get; set; }
    Task Task { get; set; }
    string Path => $"Log_{DateTime.Now:yyyyMMMdd}.txt";

    public void Start() => Enabled = true;

    public void Stop(bool discard = false)
    {
        Enabled = false;
        if (discard)
        {
            Cts.Cancel();
            Cts = new CancellationTokenSource();
            Task = Task.ContinueWith(t => { });
        }
    }

    public void Write(string line) =>
        Write(line, Path, Cts.Token);

    void Write(string line, string path, CancellationToken token)
    {
        if (Enabled)
            lock(Task)
                Task = Task.ContinueWithAsync(
                    t => AppendAllTextAsync(path, line + NewLine, token),
                    token);
    }
}

Where missing part would be:

static class AsyncContinuations
{
    public static async Task ContinueWithAsync(this Task task, Func<Task, Task> continuationFunction, CancellationToken cancellationToken)
    {
        await task;
        cancellationToken.ThrowIfCancellationRequested();
        await continuationFunction(task);
    }
}


I would not show any UI from WebPostRequest. For a fast solution you can just wrap the whole upload part and provide some sort of a listener whose methods will be called to notify about progress.

Thus WebPostRequest will not know nothing about UI layer. UI will not be blocked and be able to track upload progress.

Here's a C#-like pseudo code that illustrates what I mean:

class ProgressListener
{
    public void OnProgress(OperationContext)
    {
        //notiy UI in the thread-safe way -> use Control.Invoke for Windows Forms
    }

    public void OnFinish(OperationContext)
    {
        //show success message in UI
    }

    public void OnError(OperationContext)
    {
        //show detailed error message in UI
    }
}

//on UI class
void PerformUpload()
{

    ProgressListener listener = new ProgressListener(Form f);

    Thread thread = new Thread(() =>
    {
        try
        {
            try
            {
                WebPostRequest webPostRequest = new WebPostRequest(url);
                webPostRequest.Add("key_1", "value_1");
                webPostRequest.Add("key_2", "value_2");

                webPostRequest.UploadPdf("key_3", "pdf_name_1", userControl1);

                listener.OnProgress( /*operaton context*/)

                webPostRequest.UploadPdf("key_4", "pdf_name_2", userControl2);

                listener.OnProgress( /*operaton context*/)
                webPostRequest.UploadImage("key_5", "picture_name_1", image1);

                listener.OnProgress( /*operaton context*/)
                webPostRequest.UploadImage("key_6", "picture_name_1", image2);

                listener.OnProgress( /*operaton context*/)

                string response = webPostRequest.GetResponse();
                if (response != WebPostRequest.Success)
                {
                    listener.OnProgress( /*operaton context*/)

                    throw new Exception(response);
                }
                success = true;

                listener.OnFinish( /*operaton context*/)
            }
            catch (Exception ex)
            {
                listener.OnError( /*operaton context*/)
                //display error messaage
            }
        }
        catch(Exception ex)
        {
            listener.OnError( /*operaton context*/)
            //logging
        }
    });

    thread.Name = "uploader";
    thread.Start();
}


Code Review questions don't have a concept of duplicates per se. You're looking for people to look at your code, not my code! :-)

In so saying, here are my comments:

The most important thing I noted is that your function doesn't seem to maintain sort stability. At least, I don't see any active effort to keep the sorting stable.
Comments on merge:

Your merge uses "right-folding" (whereas my merge uses "left-folding"), which is why it looks so different, but both are legitimate strategies.
Your code doesn't correctly handle the case where two elements compare "equal" though (where (cmp a b) and (cmp b a) both return false). In particular, it will loop endlessly.

Comments on split:

Your split zigzags the elements between the two output lists rather than splitting midway, which was what made me doubt the sort stability.
The inner function splitr could be reformulated using a named let, which is more idiomatic in Scheme:

(define (split l)
  (let loop ((l l)
             (left '())
             (right '()))
    (if (null? l)
        (list left right)
        (loop (cdr l) right (cons (car l) left)))))

Personally, I'd use (values left right) instead of (list left right), to return the sublists as two values. I'll explain why in the final point.

In the outer mergesort function:

You should merge the first two cond tests into a single (or (null? l) (null? (cdr l))) test.
Instead of the sequential let* binding of parts then left then right, you should use either this:

(let ((parts (split l)))
  (let ((left (car parts))
        (right (cadr parts)))
    ...))

or, if you took my suggestion to have split return (values left right), you could do:

(let-values (((left right) (split l)))
  ...)

which is much more succinct.

In summary, I'd suggest two fixes:

You should make the function handle "equal" elements correctly.
You should make the function provide stable sorting, namely that if two elements in the input list are "equal" to each other, you should keep their relative order in the output list (see my test case below).

You can use this as a test case:

(mergesort '((3 . 1) (1 . 4) (4 . 1) (1 . 5) (5 . 9)
             (9 . 2) (2 . 6) (6 . 5) (5 . 3) (3 . 5))
           (lambda (x y) (< (car x) (car y))))

The correct result should be:

((1 . 4) (1 . 5) (2 . 6) (3 . 1) (3 . 5)
 (4 . 1) (5 . 9) (5 . 3) (6 . 5) (9 . 2))


Find all distinct combinations of letters in a string

Minor remarks

Since the sortedness of the input is a precondition of getPermutations, I would either do this step in the function itself, or at least add a check for this condition.
Passing string by reference instead of by value: I recommend passing const std::string & instead of std::string. In this way, the string does not get copied to the stack. This matters especially, if the string is very long.

Alternative

While the recursive approach is elegant and easily understandable, it might be less convenient for very long inputs. I suggest another solution, based on the idea, that if you want all permutations, then each character can either be part, or not be part of a permutation. This gives us 2^N possible permutations, where N is the length of the input. So, you can just generate this number (2^N), and then iterate from 0 to 2^N-1, and calculate the corresponding perm. for each number. So, if the number is represented as binary digits, then 1 means that the character at the corresponding position should be part of the permutation, 0 that it should not. (If you do not need the empty perm., just start the iteration from 1, instead of 0.)

With your example, 'AA2', this would work as follows: N=3, so iterate from 0 to 7 (=2^3 - 1). 0 corresponds to the empty set. 1 = 001b, so '2' is part of the permutation. 2 = 010b, so only (the second) 'A' is part of the permutation. 3 = 011b, so the perm. is A2, etc.

Remarks:

This approach would yield two identical 'A2' perms., but you can avoid that by storing the return value in a set, as you are currently doing it (unless you do want both).
With this solution, it is not needed to sort the input.
Other representations are possible as well, e.g a vector of booleans, instead of a number (especially convenient very large inputs).


A better isprime check

At the moment, your function returns that 0 and 1 are prime, this is not what I have learnt.

A faster isprime check

You check primality by testing divisibility of various candidates between 2 and (x + 2)/2 (non included). You'd better check for candidates between 2 and sqrt(x) (included) as the smallest divisisor will be no bigger than this.

Here's the corresponding code from my toolbox :

def is_prime(n):
"""Checks if a number is prime."""
if n < 2:
    return False
return all(n % i for i in range(2, int(math.sqrt(n)) + 1))

Itertools is good

Instead of going through n by incrementing it, you can use itertools.count

for n in itertools.count(2):
    if isprime(n) & isprime(n + 2):
        if inputIndex == tempIndex:
            print "%d,%d" % (n,n+2)
            break
        else:
            tempIndex += 1

A bit of math

You know that twin primes will be odd (if you are not convinced of this, just think about it). Therefore, you can limit yourself to the search of odd numbers : for n in itertools.count(3, 2):.

Don't check things twice

At the moment, the primality of the same number is checked twice. A way not to do so would be to generate prime numbers and to check this to generate twin pairs.

def yield_odd_primes():
    for n in itertools.count(3, 2):
        if isprime(n):
            yield n

def yield_twin_pairs():
    p1, p2 = 0, 0
    for p in yield_odd_primes():
        p1, p2 = p2, p
        if p1 + 2 == p2:
            yield p1, p2

inputIndex = 1500
for i, (p1, p2) in enumerate(yield_twin_pairs()):
    if i + 1 == inputIndex:
        print "%d,%d" % (p1, p2)
        break

Better user experience

When I ran your code for the first time, nothing happened and I thought Python was just crunching numbers. After a while, I had a look at the code and realised that the script was waiting for some input.
By adding a prompt, you make this much clearer :

inputIndex = int(raw_input('Please enter an index: '))

Code organisation

At the moment, when one imports your code, he gets the prompt and everything. The usual way to do is to put the code "actually doing something" behind an if-main guard.

More code organisation

Your can split your code into smaller function. I found quite useful writing the following function to take the nth element of an iterable :

def get_nth_element(iterable, index):
    for i, e in enumerate(iterable):
        if i == index:
            return e

Tests

For such an algorithmic oriented problem, it is easy and a good habit to write test to ensure you do not break anything as you go through modifications.

The hard part is sometimes to rewrite your code in such a way that testing is made easy. It is now the case with my final version of the code.

Final code

import math
import itertools

def isprime(n):
    if n < 2:
        return False
    return all(n % i for i in range(2, int(math.sqrt(n)) + 1))

def yield_odd_primes():
    for n in itertools.count(3, 2):
        if isprime(n):
            yield n

def yield_twin_pairs():
    p1, p2 = 0, 0
    for p in yield_odd_primes():
        p1, p2 = p2, p
        if p1 + 2 == p2:
            yield p1, p2

def get_nth_element(iterable, index):
    assert index >= 0
    for i, e in enumerate(iterable):
        if i == index:
            return e

if __name__ == "__main__":
    inputIndex = int(raw_input('Please enter an index: ')) - 1
    print(get_nth_element(yield_twin_pairs(), inputIndex))

Some math to make the code faster

At the moment, we check the primality of each and every odd numbers. We can do better by considering division by 6 : all numbers can be written :

6k + 0 -> divisible by 2 & 3
6k + 1 -> potential prime
6k + 2 -> divisible by 2
6k + 3 -> divisible by 3
6k + 4 -> divisible by 2
6k + 5 -> potential prime

Thus, except for the obvious pair (3, 5), the only way two prime numbers can be separated by two are if they can be written (6*k + 5, 6*k + 7).

Once you have this, the code pretty much writes itself :

def yield_twin_pairs():
    yield (3, 5)
    for i in itertools.count(5, 6):
        if isprime(i) and isprime(i+2):
            yield (i, i+2)


I don't immediately see something wrong with your base case. Perhaps it could be simplified, checking only for low > high. You would need to think about what happens if you pass Integer.MAX_VALUE as high then though.

That being said, the implementation contains a major bug. low + high will overflow when the sum of them is greater than Integer.MAX_VALUE. You can use some mathematical tricks to solve this. Or use some bitwise operations, like (low + high) >>> 1.

The bitshift solution works for positive low and high (which they are). Although the sum can indeed still overflow, the unsigned shift operator >>> shifts a zero in the most significant side. Mathematically, you could think of it as dividing the number interpreted as unsigned by two. As an example:

0111 1111 1111 1111 1111 1111 1111 1111 = Integer.MAX_VALUE
0111 1111 1111 1111 1111 1111 1111 1111 = Integer.MAX_VALUE
--------------------------------------- +
1111 1111 1111 1111 1111 1111 1111 1110 = -2 ((2^32)-2 if interpreted as unsigned)

This sum overflows. Now, the difference between division (which would be the same as signed shift >>) and unsigned shift:

(-2) / 2   = 1111 1111 1111 1111 1111 1111 1111 1111 = -1
(-2) >>> 2 = 0111 1111 1111 1111 1111 1111 1111 1111 = Integer.MAX_VALUE

Also note that the recursive calls may lead to a stack overflow in Java. Although it is a tail recursive implementation, this is not optimized in Java. So for a real world implementation, prefer iteration.

Final note: always try to use braces with if/else blocks.


Fahrenheit / Celsius temperature converter - follow-up

shift shifts the command line argument list by n, or by 1 if n is unspecified.
For example, given -c 25, the value of $1 is -c.
After you call shift without parameters,
it shifts the parameters by 1, so $1 becomes 25.
You used it correctly.

Use here-documents

This is hard to read:

echo -e "usage: temp [-f][-c]|[number]|[-h]\nExample:\n\ttemp -f 54\n\ttemp -c 24.5\n"

Using a here-document, it becomes much easier to read:

usage() {
    cat << EOF
usage: temp [-f][-c]|[number]|[-h]
Example:
    temp -f 54
    temp -c 24.5
EOF
}

Simplify conditions

This can be written slightly simpler:

if [ "$1" = "" ]; then

Like this:

if [ ! "$1" ]; then

This can be written much simpler:

elif [[ "$3" != "" ]]; then
    usage
    exit 1
fi
while [ "$1" != "" ]; do

Like this:

elif [[ "$3" ]]; then
    usage
    exit 1
fi
while [ "$1" ]; do

Simplify the bc calls

These statements are unnecessarily complicated:

-f )    shift
        RES="$(echo "scale=2; (${1}-32)*5/9" | bc -q -l; printf "\b˚C")"
        echo "${1}˚F = "${RES}
        exit
        ;;

-c )    shift
        RES="$(echo "scale=2; ${1}*9/5+32" | bc -q -l; printf "\b˚F")"
        echo "${1}˚C = "${RES}
        exit
        ;;

That is:

Doing part of the output formatting when you create RES and the other part when you echo it is confusing, it would be better to separate
Printing a backspace character becomes unnecessary when you separate the calculation and display formatting of RES
The quoting around $(...) is unnecessary
Instead of echo-ing the command for bc, a here-string would be better

Like this:

RES=$(bc -q <<< "scale=2; ${1}*9/5+32")
echo "${1}˚C = ${RES}˚F"

Notice how the assignment of RES has only calculation logic, no display logic. All the display logic is on the next line.
The result is cleaner and shorter.


Read the (email address: syntax) article on Wikipedia  for what is allowed. Your current validation will produce a lot of fails for valid email addresses.


Creating membership list with Parallel.ForEach

Before going parallel I'd first try to understand which part of that code is slow. Maybe there is something you can do which will boost performance even more. That said I have few notes:

userandGroup does not follow naming conventions, types should be PascalCase.
There is no benefit to abbreviate names to usrgp and obj. is usrgrp a...group? Call it group (or userGroup if owner isn't clear from context). obj says what it is (an object), not what it does (the object which is used as synchronisation context). You may rename it (at least) to syncRoot (name used also in the framework itself for this purpose).
If lst is local then you do not need obj and you can directly lock on it.
You do not need to cast ProviderUserKey to Guid to call ToString(): usr.ProviderUserKey.ToString() or (if ProviderUserKey is object and it might be null) maybe Convert.ToString(usr.ProviderUserKey).
Object initialisation may be simplified:

Using Object Initialization syntax:

var group =  new userandGroup
{
    id = usr.ProviderUserKey.ToString(),
    Name = usr.UserName
};

Follow naming convention also here, id should be Id. Also move Profile creation before group and you can initialise everything in this way.

DisplayName initialisation may use string interpolation:

As before:

DisplayName = $"{profile.GetPropertyValue("FirstName")} {profile.GetPropertyValue("LastName")}"

If FirstName or LastName may be empty then you're adding a spurious space. Handle the case (or at least add a call to Trim().)
true boolean parameters are a pain, I see the call and I need to go to check the prototype to know what it means. More than that: if I need another option then I need to add more and more parameters.

Use named parameters if you can't change the prototype (name is fictional in this case):

profile.Initialize(usr.UserName, loadUserProfile: true);

Or, better, use an enum with the [Flags] attribute to make clear - at calling point - what parameter means.

You initialised Profile with the user name as parameter in its ctor, do you need it again here?
If lst is local then you can simplify your code.

Move the logic to create group into a separate function (basically all the code you have inside the parallel loop) then:

var groups = userlist.AsParallel()
    .Select(CreateGroup)
    .ToList();

Where CreateGroup is something like this (note that I moved the hard-coded user string to a constant defined elsewhere and I moved the possibly complex logic for DisplayName to a separate function):

UserAndGroup CreateGroup(MembershipUser user)
{
    var profile = new Profile(user.UserName);
    profile.Initialize(user.UserName, true);

    return new UserAndGroup
    {
        Id = user.ProviderUserKey.ToString(),
        Name = user.UserName,
        Type = UserGroupType,
        DisplayName = ResolveDisplayName()
    };

    string ResolveDisplayName()
        => $"{profile.GetPropertyValue("FirstName")} {profile.GetPropertyValue("LastName")}";
}


WITH Dates AS (
    SELECT EntryDate
         , DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SundayDate
         , DATEADD(DAY, 7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SaturdayDate
        FROM MyTable
), Coming AS (
    SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) AS Sunday
)
SELECT EntryDate
     , SundayDate
     , SaturdayDate
     , CONVERT(VARCHAR, SundayDate, 103) + ' - ' + CONVERT(VARCHAR, SaturdayDate, 103) AS Week
    FROM Dates, Coming
    WHERE SundayDate <= Coming.Sunday
    ORDER BY 2;

The simplifications I've made are:

Extracted most of the query into a Common Table Expression named Dates to reduce redundancy.
Removed the pointless CAST(... AS DATE), since DATEADD() already produces dates.
Used a column number for ORDER BY.  With the Common Table Expression, though, we could just as easily ORDER BY SundayDate.
Extracted DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) into a Common Table Expression named Coming.  This doesn't reduce the complexity of the query, but helps make the WHERE-clause read more like English.

SQLFiddle

Edit

Since the benefits of the last two suggestions are debatable, you may prefer a milder approach that incorporates just the first two suggestions:

WITH Dates AS (
    SELECT EntryDate
         , DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SundayDate
         , DATEADD(DAY, 7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SaturdayDate
        FROM MyTable
)
SELECT EntryDate
     , SundayDate
     , SaturdayDate
     , CONVERT(VARCHAR, SundayDate, 103) + ' - ' + CONVERT(VARCHAR, SaturdayDate, 103) AS Week
    FROM Dates
    WHERE SundayDate <= DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE())
    ORDER BY SundayDate;


I do not see anything immediately wrong with your addUser() and getUser() implementations.
Your hash() implementation could be improved in two areas though.

Salt
As already indicated by Bill Barry in the comments, your should use a better salt.
Some rules to keep in mind when handling salts,

Salts should be unique per password.
 Every password should have a unique salt. Sharing a salt reduces its effectiveness.
Salts should be unpredictable
You should generate a salt using a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).

You may want to try using crypto.randomBytes(size, [callback]) if available.
Salts should be large
 PKCS#5 recommends a salt be no smaller than 64-bits (8 bytes).
I like to start with 128-bit salts (16 bytes), favoring higher salt-lengths for more passwords and better security.
Salts are not secret
Although purposefully disclosing the salt isn't a good idea, you can store them in cleartext.

Key stretching / Iterations
Wikipedia has a good description on Key Stretching,

  key stretching refers to techniques used to make a possibly weak key, typically a password or passphrase, more secure against a brute force attack by increasing the time it takes to test each possible key.

The crypto module does not appear to offer key stretching natively for sha512.

You should look into using crypto.pbkdf2(password, salt, iterations, keylen, callback) which uses HMAC-SHA1. You shouldn't use SHA1 on its own, but pbkdf2 using HMAC-SHA1 is still secure.
See Password-Based Key Derivation Function 2 for more information.

You will want to set the number of iterations as high as possible while still maintaining an acceptable responsiveness for your application. Though PKCS#5 recommends a minimum of 1000 iterations, 10000+ iterations is fairly typical; computers are only getting faster.


The URL encoding looks correct. However, that doesn't mean that users cannot enter something malicious that will trigger some bug in the server. But that's up to the server implementation to be robust to malicious inputs. Also note that anybody with access to this script can read your API key and make arbitrary API calls.

Many lines end with ;. This is pointless, you should remove all those ;.

The exit code of a Bash script is the exit code of the last command.
So you could replace the last if-else condition with this simple line, and get the exact same effect:

[ "$responseCode" -eq "202" ]


Make a Deal program - using sets in Python

You can do this in \$O(1)\$ space and time, where you're doing it in \$O(n)\$ space and time. I cleaned your code and got roughly the same as Graipher's code:

def make_a_deal(doors, doors_to_open):
    doors = range(1, doors+1)
    price = set(random.choice(doors))
    choice_1 = set(random.choice(doors))
    doors = set(doors)
    open_doors = set(random.sample(doors - price - choice_1, doors_to_open))
    choice_2 = set(random.sample(doors - open_doors - choice_1, 1))
    return choice_1 <= price, choice_2 <= price

But there are some changes you can make to make it faster.

After generating price and choice_1 you can check if the user has won, and return True, False.
You don't need to randomly select price, this is as you can rotate the doors until price is the first, always. And so you can make price = 0.
Expanding on the above we now know that 0 is the only door with the price, and so \$1 \to n\$ are all loser doors. From this we know that one of the doors we picked was a loser door, and so we can remove that door, and shift all the other doors down. Which is the same as removing the last door.
Expanding on the above, you can remove \$k\$ more loser doors, as they are randomly selected.
And so the second choice has a range of \$0 \to n - k - 1\$.

And so you can get \$O(1)\$ space and time:

def make_a_deal(doors, doors_to_open):
    price = 0
    choice_1 = random.randrange(doors)
    if choice_1 == price:
        return True, False

    choice_2 = random.randrange(doors - 1 - doors_to_open)
    return False, choice_2 == price


I think your use-case and the Wiki description are different. Technically, the Multiton should return the exact same intance for the exact same key, always, but, because your multitons Map is not a static instance, you can simply create multiple instances of the Multiton and each one will generate different instances for the same key.

This is OK in your case, because you create a private static final anonymous implementation of the class.... so you handle that problem at a higher level.

I think, otherwise, the algorithm is good.... (i.e. it will work as advertised).

There are two changes I can recommend....

Why is the Creator<K,V> a public abstract static class? This is a broken pattern, and it should simply be an interface public interface Creator<K,V>
This is complicated, the rest of the answer is about change 2....

I believe you have unnecessary indirection. Your inner class:

  private class Prayer {
    private final Creator<K, V> creator;

    public Prayer(Creator<K, V> creator) {
      this.creator = creator;
    }

    public Callable<V> pray(final K key) {
      return new Callable<V>() {

        @Override
        public V call() throws Exception {
          return creator.create(key);
        }

      };
    }

  }

This is overkill.... if you make the Prayer class Extend Callable, you win:

  private class Prayer implements Callable<V> {
    private final K key;

    public Prayer(K key) {
      this.key = key;
    }

    @Override
    public V call() throws Exception {
      // creator is accessible as a final field on the Multiton instance.
      return creator.create(key);
    }

  }

Then, instead of keeping a final instance to Prayer in your main class:

private final Prayer prayer;

you should instead hold the simple Creator:

private final Creator<K,V> creator;

And, instead of calling prayer.pray(), you only need do:

FutureTask<V> ft = new FutureTask<V>(new Prayer(key));

Note: It is much better to request a new Prayer(...) than it is to demand one with prayer.pray() !!!

Hope this all makes sense.... I have reworked your original code as:

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class Multiton<K, V> {
  // Map from the key to the futures of the items.
  private final ConcurrentMap<K, Future<V>> multitons = new ConcurrentHashMap<K, Future<V>>();
  // A Creator is used to construct the Callable that is attached to the FutureTask.
  private final Creator<K,V> creator;

  public Multiton(Creator<K, V> creator) {
    this.creator = creator;
  }

  /**
   * There can be only one.
   *
   * Use a FutureTask to do the creation to ensure only one construction.
   *
   * @param key
   * @return
   * @throws InterruptedException
   * @throws ExecutionException
   */
  public V getInstance(final K key) throws InterruptedException, ExecutionException {
    // Already made?
    Future<V> f = multitons.get(key);
    if (f == null) {
      // Plan the future but do not create as yet.
      FutureTask<V> ft = new FutureTask<V>(new Prayer(key));
      // Store it.
      f = multitons.putIfAbsent(key, ft);
      if (f == null) {
        // It was successfully stored - it is the first (and only)
        f = ft;
        // Make it happen.
        ft.run();
      }
    }
    // Wait for it to finish construction and return the constructed.
    return f.get();
  }

  /**
   * Use a Prayer to pass the key to the Creator.
   *
   * @param <K>
   * @param <V>
   */
  private class Prayer implements Callable<V> {
    private final K key;

    public Prayer(K key) {
      this.key = key;
    }

    @Override
    public V call() throws Exception {
      return creator.create(key);
    }

  }

  /**
   * User provides one of these to do the construction.
   *
   * @param <K>
   * @param <V>
   */
  public interface Creator<K, V> {
    // Return a new item under the key.
    abstract V create(K key) throws ExecutionException;

  }

}


I assume you are using point.in.polygon from the sp package. The function can take any number of points, so you should rewrite your algorithm as a single loop: for each polygon in pols, make a single call to point.in.polygon to check if all the points in coords are inside or not. This should save you a lot of time. Then you'll only have to do a little work reformatting the output. I can help with the code if you can please clarify what coors looks like.

Edit: Here is now an example of how you could code this into a single loop. It is possible you will have to work it a bit as you have not really shown us how you want to store your output.

First, some sample data:

coors <- replicate(5, {n <- sample(5:10, 1);
                       data.frame(x = runif(n), y = runif(n))},
                   simplify = FALSE)

pols <- replicate(3, {n <- sample(5:10, 1)
                      data.frame(x = runif(n), y = runif(n))},
                  simplify = FALSE)

Here, we concatenate all the points in coors together, but keep a vector of group indices which we will use later for splitting by group:

all.coors  <- do.call(rbind, coors)
num.points <- sapply(coors, nrow)
group.idx  <- rep(seq_along(coors), num.points)

Now the single loop:

results <- vector("list", length(pols))
for (j in seq_along(pols)) {
   print(j)
   results[[j]] <- split(point.in.polygon(all.coors[,1], all.coors[,2],
                                          pols[[j]][,1], pols[[j]][,2]),
                         group.idx)
}

I am confident this will significantly speed up your computations. However, if this is still too slow, I agree you'll have to consider parallelization. Good luck.


Implementing a shared array cache without locking

It's not clear from you're post whether owner is unique for each thread or if two threads can call the functions with the same value of owner. If two threads can call the functions with the same value for owner, your code is incorrect.

If one thread is executing point_catch_store() and another thread calls point_catch_fetch() while the first thread is between these two lines, you'll get the old value (from the previous owner of the entry), not the new one:

g_atomic_pointer_set(&(slot->owner), owner);
slot->value = value;

As far as I can tell, swapping those two lines would solve that problem.


Better way of clone and then replace some attributes with jQuery

The current code does essentially this:

Clone the dirtied first item and append to the end
Modify the dirtied first item to make it clean again

It would be better to use a clean prototype / template from which you can easily create clean new instances. Then the operations can become:

Move the dirtied first item to the end
Recreate the first item from the clean template

The first approach is not so good, because:

Cloning is always a suspicious operation. For example, you have to make sure that:

all fields correctly copied
no references accidentally leaked
deep objects correctly deep-copied: although this is not a concern in this specific example, but I'm adding it anyway as a reminder of general concerns about the concept of cloning

Reseting an object to a clean state is always a suspicious operation. For example, you have to make sure that:

all fields are correctly reset: often duplicating the same logic that must exist (explicitly or implicitly) in the initializer / constructor

The new approach doesn't have any of these tricky issues.
It's conceptually much cleaner, with much fewer hidden traps and bugs waiting to happen.


How about something like this.  It's pretty much what you have but all I have done is seperated a couple of the parts into methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;
using WebMatrix.WebData;

using Appsomniacs.Web.Filters;

namespace Appsomniacs.Web.Handlers
{
    public class BasicAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var identity = Thread.CurrentPrincipal.Identity;

            if (identity == null && HttpContext.Current != null)
            {
                identity = HttpContext.Current.User.Identity;
            }

            if (identity != null && identity.IsAuthenticated)
            {
                var basicAuth = identity as BasicAuthenticationIdentity;

                if (basicAuth != null)
                {
                    if (WebSecurity.Login(basicAuth.Name, basicAuth.Password))
                    {
                        return IsAllowedUser(basicAuth.Name) || IsAutenticatedInRole(basicAuth.Name);
                    }
                }
            }

            return false;
        }

        private bool IsAllowedUser(string name)
        {
            if(this.Users.Length == 0) return false;

            var allowedUsers = this.Users.ToUpperInvariant()
                .Split(',');

            return allowedUsers.Contains(basicAuth.Name.ToUpperInvariant());
        }

        private bool IsAutenticatedInRole(string name)
        {
            if (this.Roles.Length > 0)
            {
                var userRoles = System.Web.Security.Roles.GetRolesForUser(basicAuth.Name);

                var allowedRoles = Roles.Split(',');
                var matches = userRoles.Intersect(allowedRoles).ToArray();

                return matches.Length > 0;
            }

            return true;
        }
    }
}


CSS

Since this is a single document, not a webpage of a website, it's fine to use internal CSS in the style element instead of linking to an external stylesheet. However, if you plan to write more letters in the future, you should create a stylesheet that includes all the shared styles that are typical for a letter and link to it from each letter (<link rel="stylesheet" href="letter.css" />).

You could name your classes more meaningful, but this is only a good practice, not a requirement.

You could omit the class on body.

Encoding/Charset

You should add the encoding to the document. If you want to use UTF-8 (recommended), add <meta charset="utf-8" /> as the first child of the head element.

title element

You are missing the title element, which is required. Add it as child of head: <title>Vertretung während Reise – 1. Dezember 2012</title>

Return address

The use of
 is correct here. However, the date is not part of the address, and therefor it shouldn't be separated by br. Put the date in its own element instead. HTML5 offers the time element.

Because this is your address (and not the recipient address), you should enclose it in the address element.

You could enclose the return address and the date in the header element. It might also be possible to enclose the return address in a footer element and the time in a header (probably together with the h1), but this could be overkill ;)

Subject line / Betreff

Instead of using a meaningless div for the subject, you should use h1 here, as it is the heading of the whole document.

Salution / Anrede

It's arguably if the salution is a paragraph on its own, or if it is part of the first paragraph. I think when followed by a comma, it should be part of the following paragraph. But this is not undisputed (I have no detailed knowledge about the semantics of a letter).

Greets

The use of the br element to separate the greeting from your anme is correct here. But don't use several br elements just because you want to add more spacing. Use only one and apply a class to it, so that you can give it a higher vertical margin (CSS).

Also, include this in a p instead of a div.

Example

So your letter could look like:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Vertretung während Reise – 1. Dezember 2012</title>
    <link rel="stylesheet" href="letter.css" />

      <address class="return-address">
        Lopes de Almeido, Evanildo

        Bläsiring 161

        4057 Basel

      </address>

      <time datetime="2012-12-01">01 Dezember, 2012</time>

      Betreff:  Vertretung waehrend Reise

          Sehr geehrte Frau Graf,

          Ich fliege nach Brasilien am 29. Dezember 2012 für 6 Wochen.
          Meine Nichte kann mich vertreten.  Sie arbeitet sehr gesissenhaft.
          Sie heisst Yasmin.  Ihre Nummer ist xxx.

          …

        Freundliche Grüsse

        Evanildo Lopes do Almeida

        Hauswart Binningerstrasse 19/23


Keep it like that. It is perfectly readable, easy to understand, everything is fine.
Naturally you could do some lambda trickery along the lines of:
public static String extractFromMessageOrQuery(
       Update update,
       Function<Update, String> messageExtractor,
       Function<Update, String> queryExtractor,
       String defaultValue) {
   if (updateHasMessage)
       return messageExtractor.apply(update);
   else if (updateHashCallbackQuery(update))
       return queryExtractor.apply(update);
   return defaultValue;
}

public static String getInputUserData(Update update) {
    return extractFromMessageOrQuery(
        upd -> upd.getMessage().getText(),
        upd -> upd.getCallbackQuery().getData(),
        null
    );
}

But: would that make the code

easier to understand? No
easier to extend? No
easier to maintain? No

Thus: take note that these possibilities exist, and keep the code as-is.


If both new and old messages are sorted it's basically a merge of two sorted arrays, similar to the merge step in merge sort. It can be done O(n + m) time. I'd suggest you to look into how that's implemented.


Loading Files from a Directory in Haskell

The loadData function looks just fine to me. I don't see a way it could be any more elegant given what it's doing. I do actually like the way you have separated reading the file and parsing it. That's the way to go.

Your concern about "avoiding the IO monad" shouldn't be a concern. On the contrary, that's actually a "best practice", known as "pushing I/O to the boundary". It means that the majority of your program should be pure, and only a thin shell should deal with external world. This way you can easily test and debug the majority of your program.

The only thing I might do is make the last three lines one expression:

traverse readFile prefixed
  <&> map parseTsv
  <&> zip filtered

I find this a bit more readable, but that's just a matter of personal taste.

But the parseLine function could sure use some improvement.

First, the control flow. Look what it's doing: compute a Maybe value, then if it's Just, compute another Maybe value from its contents. That's exactly what "bind" does! This means it can be nicely represented as a do block.

Second, read is a partial function. This means it can fail at runtime if there is a non-number in the file. I understand this probably Should Never Happen™, but you'd be surprised how many things that "should never happen" do, in fact, happen all the time. :-)

But since you're already in the Maybe context, it would be easy to use readMaybe instead, and skip the malformed numbers.

Applying both points:

parseLine line = do
    i <- elemIndex '\t' line
    let (word, strCount) = splitAt i line
    count <- readMaybe strCount
    return (word, count)


Eliminating empty spreadsheet cells from a range

You're working off Selection. That's "good enough" for macro-recorder code, which mimicks a user's interactions with a worksheet.

VBA code can do that, sure. But why merely mimick a user's interactions with a worksheet when you have the entire Excel object model in your hands?

But before we look at different/better ways to accomplish what this code does, let's take a look at what it's doing:

h is initialized at an arbitrary value of 1000. See this SO answer for a very detailed explanation of various ways to locate the last row that contains data on a worksheet. For example this would set h to the last row with data in column A:

h = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row

By working off the actual last row, you avoid extraneous iterations later, and avoid having to modify your code if/when the worksheet starts containing more than 1000 rows.
We Select the first cell in the 999th row, and then start looping from 1 to 999.

If the ActiveCell is empty, we move up a row; else, we... wait a minute... we reassign the loop variable back to 999??

It's pretty hard to understand what's happening here, and more importantly, why - and explaining why something is happening is exactly what comments are for!

'this loop sets n to the last row with data (right?)

Okay, let's stop here, and look again at what we're trying to accomplish.

We want to delete rows where column A is empty. By adapting this answer to Conditionally deleting rows in a worksheet, we can enormously simplify what's going on here - the key being this little function:

Private Function CombineRanges(ByVal source As Range, ByVal toCombine As Range) As Range
    If source Is Nothing Then
        Set CombineRanges = toCombine
    Else
        Set CombineRanges = Union(source, toCombine)
    End If
End Function

Equipped with this simple tool, we can now iterate our rows once, "union" all empty cells, and delete them all at once:

Public Sub CleanUpActiveSheet()

    Dim target As Worksheet
    Set target = ActiveSheet

    Dim lastRow As Long
    lastRow = target.Range("A" & target.Rows.Count).End(xlUp).Row

    Dim toDelete As Range

    Dim currentRow As Long
    For currentRow = 1 To lastRow
        If IsEmpty(target.Cells(currentRow, 1)) Then
            Set toDelete = CombineRanges(toDelete, target.Cells(currentRow, 1))
        End If
    Next

    If Not toDelete Is Nothing Then toDelete.Delete xlUp

End Sub

Notice:

Consistent indentation makes it easier to identify where code blocks begin and end.
Meaningful variable names make it easier to understand what's going on and why.
Variables being declared closer to their usage (as opposed to "at the top of the procedure") makes reading the code more fluid.
Working with object references instead of against the current Selection makes the code much more straightforward.
Variables meant to hold a row number are declared as Long, because a 64-bit worksheet can have [many] more than 65,535 rows.
Procedure names are PascalCase; avoid using underscores in procedure names, VBA uses them for private Object_EventName handlers and Interface_Member implementation procedures.


Align your code better.
It probably has tabs (replace them with space before pasting) in it that make reading it hard on a website.

Please declare one variable per line:

int t,ret,numthreads = 0,thread_success = 0,*iptr;

You are not saving anything be doing this. But you are making it harder to read fot the next person. Anyway when you get a job (sorry I assume you are in college (forgive me if I am wrong)) no company coding standard will let you get away with it. So best not to get in the habit to start with.

Your detection of bad input is spread over two print statements. Do all the tests that make the input bad in one place then use one print statements. Whose normal content is a description of usage. If you want to be fancy describe what they did wrong. But most people just do it wrong in the first place to see the useage comment.

if ( argc < 2 )
 {
    printf("Less number of Args -Pl. enter a valid number of threads to be created\n");
    exit(1);
}
numthreads = atoi(argv[1]);
if ( 0 > numthreads )
{
    printf("Pl. enter a valid number of threads to be created\n");
    exit(1);
}

// I would have done:

if (( argc < 2 ) || ((numthreads = atoi(argv[1])) == 0))
{
    printf("Usage: %s <number>\nThe number represents the number of threads to start\n", argv[0]);
    exit(1);
}

Your only bug (that I can see) next:

ret  = pthread_create(&threads[t],NULL,thread_entry,(void*)iptr);

You can't see it until you read further and note you are joining on threads[t] even if not all the threads worked. So you need some method to track which threads actually failed and pass that information forward to the join section (what I did below) or you need to re-use the t slot in the thread array (If you loop over the array using thread_success as the limit then you can not leave any blank slots in the array).

typedef struct ThreadAndData
{
    pthread_t   thread;       // Keep all thread info in one place
    int         value;        // That way the master can potentially look at the value
    int         status;       // while the thread is running.
} ThreadAndData;
threads = calloc(numthreads,  sizeof(ThreadAndData));

threads[t].status  = pthread_create(&threads[t].thread,NULL,thread_entry,(void*)&threads[t].value);
if(threads[t].status)
{
    printf("Printf Error Creating Thread");
}

// Now in the joining phase.
// You only need to to join on threads that have a 0 status.
if (thread[t].status == 0)
{
    ret  = pthread_join(threads[t].thread,&thread_result);
}


Good interface for reverting effect of function

def revert(func):
    @wraps(func._revert)
    def wrapper(*args,**kwargs):
        return func._revert(*args,**kwargs)
    return wrapper

You are returning a wrapper, which takes arguments, calls a function, and returns results...
I'm pretty sure that is just a long way of writing:
def revert(func):
    return func._revert

This begs the question: why store the revert function as func._revert, when you could store it as func.revert?  Then instead of:
revert(do_stuff)('something')

you could write:
do_stuff.revert('something')

which is one character shorter.  Even better: autocomplete can tell you whether there is a .revert member for do_stuff, which is not possible using revert(...).


A game called Bocce played on a Cartesian grid

Bocce, as far as I know it, counts all the balls of one player that are closer to the jack than the closest one of his opponent.

That would mean that the distances from origin are irrelevant, instead, you need the distances from the balls to the jack:

auto dx = ball.x - jack.x;
auto dy = ball.y - jack.y;
auto distance2 = dx*dx + dy*dy;

Note that I avoided std::pow in favour to multiplying with itself, as std::pow inefficient for this purpose.

Note, too, that as the root function is strictly monotonely rising, you don't need to calculate it, but you can compare the squares as well and still will get the same results.

I personally strongly recommend that you create a class Ball containing three members: x, y for the coordinates and distance for the distance to jack:

class Ball
{
     int x, y;
     int distanceToJack2;
};

I'm not too happy with int as data type - it depends on the range of valid coordinates, though, if it is suitable or not. Assuming we have 32-bit int, then if the valid ranges for x and y can be covered with 16 bit, you will be safe from overflow while multiplying (this would yield undefined behaviour!), otherwise you'd need to calculate in next larger data type. For selecting the correct data types more safely, you might prefer the data types from <cstdint> header, e. g.:

 int32_t x, y;
 int64_t distanceToJack2;

Or you simply have coordinates and distance in double right away. Be aware that with double, you can quickly get issues due to rounding, so if you compare for one value being less than the other, you should consider them only so if difference is larger than some yet to be defined epsilon value (minimum distance for two values for not considering them equal). You could get some hints to from this question. Sure, it is java, but as long as both C++ and Java follow IEEE 754 for floating point values, it applies for both languages equally. On the other hand, you could then use std::hypot for calculating the distances in a very safe manner (thanks Toby for the hint).

Then you might add:

 void Ball::calculateDistance(Ball const& jack)
 {
     uint64_t dx = static_cast<uint64_t>(x) - jack.x;
     uint64_t dy = static_cast<uint64_t>(y) - jack.y;
     distanceToJack2 = dx*dx + dy*dy;
 }

Finally, you can sort your balls according to the distances to jack and select all balls from one vector of which the distance is smaller than the distance of the first element in the respective other vector.

One last point: std::string is a rather bad key type for the map if you only have two fix values (beware of typos, additionally, map mangement is rather expensive). You might prefer an enum instead: enum class Color { RED, BLUE }; and use this one as key instead. Even better: don't use a map at all, instead:

std::string bocce(std::vector<Ball>& red, std::vector<Ball>& blue, Ball const& jack);

Note that as you need to calculate the distances, which are stored in the balls, you cannot have const references for the two vectors (which otherwise would have been preferrable). From point of view of design, this is at least questionable (but at least, it's quite some improvement already). Ideally, the design would allow to pass in const vectors, but that would require some overhead, so for pragmatism, we might decide to live with the current design...


The maybeAirline variable isn't necessary. Note that the type annotation in the declaration is optional, and can easily be inferred by the compiler. So I would change that to:

def getFlightsForAirline(id: Long): Try[Option[List[Flight]]] =
  Airline.getById(id) match {
    case Some(airline) => Success(Flight.getFlightsByAirline(airline))
    case None => Failure(new RecordNotFoundException("Couldnt find airline"))
  }

Notice that the Scala style guide suggests putting a space after the colon in a type annotation – name: Type instead of name:Type.
Every time you destructure an Option with match/case, they kill a puppy because you should have probably used map. Well, almost every time, because the Failure is an important part of this function's behaviour. But this still is somewhat of a code smell.
The return type Try[Option[List[Flight]]] strikes me as rather weird: What is the difference between Success(Some(List())) and Success(None())? I guess the latter might occur if getFlightsByAirline isn't passed a valid airline.

Try, Option and List are essentially the same thing (either you get a result, or there isn't anything there: Failure, None or empty List). Therefore it does not make much sense to nest them, and it would be better to return a Try[List[Flight]]. This could be implemented along the lines of:

def getFlightsForAirline(id: Long): Try[List[Flight]] =
  Airline.getById(id) flatMap { Flight.getFlightsByAirline(_) } match {
    case Some(flights) => Success(flights)
    case None => Failure(new RecordNotFoundException("Couldnt find airline"))
  }

This way, the Failure is returned if either of the getXByY methods returns None.

Interestingly, there is no builtin way to transform an Option to a Try (along the lines of maybe toTry { MyException("Reason") }) while there is a try.toOption method.
Your RecordNotFoundException will have a much more Scala-ish vibe if you use a case class here. This way, you can omit the new to create a new instance, and just write: Failure(RecordNotFoundException("..."))


A general-use For-comprehensible Loan Pattern

As long as you restrict yourself to simple uses, I think it's ok. When you try complex tricks, however, the lack of definition of the filter (or withFilter) method leads to certain inconveniences. Here are examples:

Binding to a tuple

for {
  // opens two files at once and returns a tuple of Input/OutputStreams
  (is, os) <- withIOStream("input.txt", "output.txt") // (doesn't work)
} { ... }

This doesn't work because assigning to a tuple (or more generally, a pattern) involves a call to filter. If you want to use pattern matching, bind it to a variable first, and then match it against a tuple in the for expression.

Guards

for {
  // handle only if the file is not empty
  is <- withInputStream("input.txt") if is.available() > 0 // (doesn't work)
} { ... }

This doesn't work because an "if" guard is translated to a call to filter. Since the guard (usually) depends on the loaned object (in this example, is), such conditionals must be put into the body of the for expression.

The trait is still "safe" because both of the above are catched at compilation time. However, experienced Scala programmers may find it cumbersome when they write up a complex generator and then get errors.

Can we get them work? A naïve approach is to define filter and withFilter like:

// unsafe, incorrect for certain uses
trait ForComprehensible[+A] {
  ...

  // ignore the filtering and just return itself
  def filter(f: A => Boolean): ForComprehensible[A] = this
  // not essential here, just to suppress compiler warnings
  def withFilter(f: A => Boolean) = filter(f)
}

this enables binding to a tuple (for some reason I don't fully understand), but causes guards to be silently ignored (i.e. assumes true). This makes ForComprehensible an unsafe construct.

If we are to implement filter (and withFilter) properly, we have to open a FileInputStream (in our example) in the filter method. It means the stream must be opened twice (in filter and apply), or we open it once in filter and then keep it open using some magic until the callback of apply returns. The former is simply unacceptable, and the latter would make the implementation of the trait too complicated.

EDIT: after some more experiments, I found out that a guard on ForComprehensible is not an implementation problem but rather a semantic problem.

Consider:

for {
  is <- withInputStream("input.txt") if is.available() > 0
} yield { ... }

note the yield. What this whole expression has to return if the guard is.available() > 0 doesn't hold?

It depends on the body of the for-expression. For example, if it loads the lines of the file into a Seq[String], it would return Seq(). If it counts the number of lines in the file, it would return 0 (if the body returns Int) or None (Option[Int]).

Guards, or filters, only make sense when they operate on a collection (Option can be considered a kind of collection whose maximum size is 1). Since ForComprehensible is just a syntactic trick to enable a loaner-function to be in for-generators, I conclude for now that we should stick to for-body if we want to check some conditions for acquiring resources.


As to the algorithm

The general rule here is don't search when you can calculate.

XOR is fundamentally a bitwise operation. Think about what the XOR operation is doing, on a bit by bit basis.

First, consider a simpler problem where you have to maximise the result with any number at all. (limited only to the number of bits in your input number) Suppose your input is an 8 bit number, perhaps 01100111. You want the output to be 11111111. (or 255 in decimal) So find the number that XORs with your input to give that: the first bit should be 1, the next 0, and so on until you get 10011000.

Unfortunately, you can't necessarily do that because you're restricted in the numbers you're allowed to use. Even so, to maximise the number, you need to have bits end up hot if possible, starting with the most significant bit. Work out which ranges within the provided region would leave the most significant bit hot, then look at the next bit, and repeat until there is only one candidate remaining. That way you'll have a loop running the number of bits in your number (say, 8) instead of a loop running the number of possible candidates (say, 256).

In more general commentary on the code:

Python preferred style is to words separated by underscores in function names, as in max_xor.
Although single letter variable names are probably acceptable with such narrow scope, descriptive names are better. E.g. l and r are not obviously lower and upper bounds.
Although max_ is legal, I would personally avoid being that close to a reserved word.
Speaking of that particular reserved word, I'd replace that if with running_max = max(running_max, temp)
If we're being very pythonic, and not changing your algorithm, you could use a generator comprehension expression for the whole thing. It would look like return max(x^y for y in range(l, r+1))


Animation Template Method for Snake Game

const VectorFactory = require("./model/vector");
const _ = require("lodash");
const Animator = require('./animators/animator');

Consider using ES6 and imports. That way, your code will be a bit more future-proof. The caveat is that you need to have a build system and a transpiler. Since you have require, I suppose you do have a build system in place. You just need the transpiler.

Now I suppose you use the code this way:

const SnakeAnimator = require('./animators/snake-animator');

const snakeAnimatorInstance = _.extend(SnakeAnimator);

snakeAnimatorInstance.canvas = referenceToCanvas

snakeAnimatorInstance.initialise();

gameLoop(snakeAnimatorInstance.animate);

Looks ok, but it would be nice to automate much of the setup using a factory function that accepts params, and pops it in to a composed object.

const SnakeAnimator = require('./animators/snake-animator');

snakeAnimatorInstance = SnakeAnimator.createInstance({
  canvas: referenceToCanvas,
  // other options for initialization
});

gameLoop(snakeAnimatorInstance.animate);

Now for the properties

vectors: [],
canvas: null,
xAdd: null,
canvas_context: null,
canvas_height: 0,
canvas_width: 0,

Looks like the only public property is canvas. All the others appear to be only used by internal functions like initialize. It would be nice to indicate that they shouldn't be modified directly. By convention, a _ is prefixed to the name.

Also, JS follows the camelCase convention in naming (notice innerWidth and innerHeight). Suggesting you follow for consistency.


Find the greatest gcd among the pairs of two equal sized arrays and prints the sum of that pair

int gcd,sum,maxgcd=0,maxsum=0;

You don't need to declare gcd and sum yet.

    int maxGcd = 0;
    int maxSum = 0;

It's also generally better not to initialize more than one variable per line.  It's not a functional difference.  It's a readability thing.

The Java standard is to capitalize the second and later words.

            sum = A[A_i] + B[B_i];
            gcd = gcdcalc(A[A_i], B[B_i]);

This could be

            int sum = A[A_i] + B[B_i];
            int gcd = gcdcalc(A[A_i], B[B_i]);

You don't use these outside the current iteration.  So you can declare and initialize them at the same time.

            if(maxgcd == gcd)
            {
                if(maxsum < sum)
                    maxsum = sum;

This could be

            else if (maxgcd == gcd && maxsum < sum)
            {
                maxsum = sum;

If the maxgcd is less than gcd, then they won't be equal.  So we don't need to check both.  The else makes it so that we only check for equality if not less than.

You don't need two if statements.  One statement with two clauses is sufficient.  Due to the way that short circuit comparisons work, this will be the same efficiency as the original code.

I prefer to have a space between the if and the (.  I find it easier to see that it is an if and not a method call that way.

I would encourage you to add more vertical whitespace.  Again, I find breaking up the statements into logical groups makes it easier to read.

   if(y == 0)
   {
       return x;
   }
   return gcdcalc(y, x%y);

This could be just

   return (y == 0) ? x : gcdcalc(y, x%y);

Same efficiency, just a bit terser.

If you find yourself trying to wring out every bit of efficiency, there is an iterative version of this that is probably faster.


New Game - Am I going down the right path for DOM manipulation?

Personally instead of using .find I prefer passing context to the jQuery selector like this;

$('.remSpeed', y);

Which will find all instances of .remSpeed that are within the element y.


Calculating the seconds between 2 numbers in a specific place in a string

If you want to support an insane large file with a small hardware footprint you should use streaming. Something like

public static class Program
{
    public static void Main(string[] args)
    {
        string text =
            @"SOME OTHER TEXT
WHITE SPACES AND NEW LINES

[HitObjects]
109,192,7241,1,0,0:0:0:0:
256,192,7413,1,0,0:0:0:0:
475,192,75865,1,0,0:0:0:0:
329,192,86524,1,0,0:0:0:0:
182,192,256242,1,0,0:0:0:0:
256,192,306521,1,2,0:0:0:0:

WHITE SPACES AND NEW LINES
";

        Task.Run(async () =>
        {
            using (var reader = new StringReader(text)) //This should be streamed from a disk or network stream or similar
            {
                string line;
                var inScope = false;
                int? start = null;
                int last = 0;

                while ((line = (await reader.ReadLineAsync())) != null)
                {
                    if (inScope)
                    {
                        var values = line.Split(',');
                        if (values.Length != 6)
                            break;

                        last = int.Parse(values[2]);

                        if (!start.HasValue)
                            start = last;

                    } else if (line.StartsWith("[HitObjects]"))
                        inScope = true;
                }
                Console.WriteLine(last - start);
            }
        });

        Console.ReadLine();
    }
}


Wiegand 26-Bit Calculator - Transforming a decimal number into an 26-Bit binary number

Here are a number of ideas that may help you improve your program.

Separate calculation from I/O

The Serial.println(); call from within getWeigand really shouldn't be there.  It's better if the function does just one thing, and that is to calculate and return the number.

Don't leak memory

The code calls new but there isn't any matching delete which means that the program leaks memory.  It's better to make sure all memory is freed, but better still, see the next suggestion.

Avoid using new and delete

Modern C++ doesn't use new and delete as much as it used to.  In this case, much better than passing around a raw array pointer and hoping the other end knows what the size is, is to use std::array instead.  That is an improvement over a plain array because it works with all of the standard container algorithms and has its own .size() operator. See I.13 for more details on why passing around a single array pointer is not a good idea.

Prefer single bit shifting to multi-bit shifting

Many processors have hardware optimizations for multi-bit shifts, but not all do.  That means on some machines, multi-bit shifts take longer.  For that reason, and because I think it's more readable, I'd suggest changing the first for loop to this:

for (int i = 24; i > 0; --i) {
    wiegandNum[i] = dec & 1;
    dec >>= 1;
}

Simplify your code

Instead of doing things like this:

if(even) {
    wiegandNum[0] = 0;
} else {
    wiegandNum[0] = 1;
}

just use the value directly:

wiegandNum[0] = !even;

Use whitespace for readability

Lines like this one:

for(int i=1;i<13;i++) {

are much easier to read with a little more whitespace:

for (int i = 1; i < 13; i++) {

Create a test routine

With code like this, it's usually good to do extensive testing to make sure it does what you intend.  I am not using an Arduino, but created a version that runs on Linux (or really any computer that supports C++):

#include <string>
#include <iostream>
#include <iomanip>
std::string weiString(unsigned int dec)
{
    std::string str{};
    auto answer = getWiegand(dec);
    for (const auto digit: answer) {
        str.push_back(digit ? '1' : '0');
    }
    return str;
}

int main()
{
    struct {
        unsigned n;
        std::string expected;
        bool operator()() const {
            std::string calculated = weiString(n);
            bool ok{calculated == expected};
            std::cout << std::hex << n
                << std::dec
                << '\t' << expected
                << '\t' << calculated
                << '\t' << (ok ? "OK" : "incorrect!")
                << '\n';
            return ok;
        }
    } tests[]{
        {12679548,  "01100000101111001011111000" },
        {0xffff,    "00000000011111111111111111" },
        {0x1ffff,   "10000000111111111111111111" },
        {0xffffff,  "01111111111111111111111111" },
        {0xdecade,  "01101111011001010110111101" },
        {0xfffffff, "01111111111111111111111111" },  // ignore high bits
    };

    for (const auto& test: tests) {
        test();
    }
}

Results

Here's the alternate version that uses these suggestions.  It also uses the exclusive-or operator ^ to simplify parity calculations:

#include <array>

std::array<unsigned, 26> getWiegand(unsigned int dec)
{
    std::array<unsigned, 26> wiegandNum;
    for (int i = 24; i > 0; --i) {
        wiegandNum[i] = dec & 1;
        dec >>= 1;
    }
    // check for parity of the first 12 bits
    bool even = false;
    for (int i = 1; i < 13; i++) {
        even ^= wiegandNum[i];
    }
    wiegandNum[0] = even;

    // check for parity of the last 12 bits
    bool odd = true;
    for (int i = 13; i < 25; i++) {
        odd ^= wiegandNum[i];
    }
    wiegandNum[25] = odd;

    return wiegandNum;
}

Even shorter is to process one of the parity bits over the entire array as it's generated and then recalculate just the other one and adjust.  It might be less obvious why this works, but it does.  See if you can see why.

std::array<unsigned, 26> getWiegand(unsigned int dec)
{
    bool odd = true;
    std::array<unsigned, 26> wiegandNum;
    for (int i = 24; i > 0; --i) {
        wiegandNum[i] = dec & 1;
        odd ^= wiegandNum[i];
        dec >>= 1;
    }
    // check for parity of the first 12 bits
    bool even = false;
    for (int i = 1; i < 13; i++) {
        even ^= wiegandNum[i];
    }
    wiegandNum[0] = even;
    wiegandNum[25] = odd ^ even;
    return wiegandNum;
}


I transcribed the comments from @user3629249 into this community wiki answer:

Regarding this line:

symbol* newnode = (symbol*) malloc(sizeof(symbol));

In C, do not cast the returned value from malloc and family of functions. This is because the returned value is a void*, so can be assigned to any other pointer and maintenance becomes much easier as there is no need to fix the casting.
Always check (!=NULL) the returned value to assure the operation was successful.
The expression sizeof(char) is always 1, so adds nothing to the value passed to malloc()

Regarding this line:

const char *datatype[]={"char","double","float","int"};

To avoid having the execution re-create this every time the function is called, add a static modifier. I.E. static const char *datatype[]={"char","double","float","int"};
Regarding:

char *token = strtok(statement,delimiters)

On every call to strtok(), always check (!=NULL) the returned value to assure the operation was successful. A failure of the call to strtok() will result in isIdentifier() trying to read from address 0. This is undefined behaviour and can lead to a seg fault event.
In general, when checking the parameters (as in the openfile() function) When the code finds a problem with the command line parameters, it should display a usage statement, so the user is informed of exactly what they should have done.
When a system function returns an error indication, such as the returned value from fopen(), the next line of code should be perror(); so the related system error message gets output to stderr.
When #defineing numeric values, always wrap the numeric value with parens so there are no 'text replacement' errors.
Due to each new token being inserted at the beginning of the linked list, when the list is displayed, the tokens will be displayed in the reverse order. Is this what you want?
A symbol table needs to contain info on any modifiers being applied to a symbol. including when a modifier is a function name, a returned value, a returned type, etc etc linked values, such as struct's enum's, union's, etc need links between the type, the name, and the associated fields with their types, names, and order. The current code handles none of that.
The isDeclaration() function will treat parens, braces, and other similar items incorrectly. The parsing needs to keep a 'state' history, so as to know how to treat the next token. (all part of lexical and syntax analysis) The posted code does not properly handle strings in double quotes and single quotes. The posted code does not handle a '\' at the end of an input line.
The max token length is set to 31 characters+string delimiter. what is this code was reading a C source file? while only the first 32 characters may be significant, an identifier can be much longer. the code will overrun the token buffer in such an instance, resulting in undefined behaviour, leading to a seg fault event.


F# Either computation expression with while loop

There are a few things I would probably add or change about your implementation.  When I create a new computation builder, I typically put the logic in a module, and then just call the functions in that module from the builder.

Another thing I would do is prefer the use of discriminated unions for Error types.  This makes it possible to match on the error, and also lets you use a little trick with the implementation of delay/run on the computation builder to wrap up any unhandled exceptions that occur inside your computation expression as an Error as well, so you don't have to wrap things in try/with.

Next, I would implement some common operators like >>=, <*>, and <!>, as well as lift and apply functions.  These will make it easier to work with the Results outside of the computation expression and interface with functions that don't natively work with Results.

Finally, I would implement at least all the standard members for the computation builder, including TryWith/TryFinally/Using/For.  An example implementation might look like the following:

module Either =
    open FSharp.Reflection
    open System

    let inline bind f x =
        match x with
        | Ok s -> f s
        | Error e -> Error e

    let inline ok x = Ok x

    let inline zero () = Ok ()

    let inline convertExceptionToResult<'result,'event> (ex: exn) =
        let union = FSharpType.GetUnionCases(typeof<Result<'result, 'event>>)
        if typeof<'event>.IsAssignableFrom(typeof<exn>)
        then FSharpValue.MakeUnion(union.[1], [|[ex] |> box|]) |> unbox<Result<'result, 'event>>
        elif FSharpType.IsUnion typeof<'event>
        then let cases = FSharpType.GetUnionCases(typeof<'event>)
             match cases |> Seq.tryFind (fun case -> case.GetFields().Length = 1 && case.GetFields().[0].PropertyType.IsAssignableFrom(typeof<exn>)) with
             | Some case -> FSharpValue.MakeUnion(union.[1], [|[FSharpValue.MakeUnion(case, [|ex |> box|]) |> unbox<'event>] |> box|]) |> unbox<Result<'result, 'event>>
             | None -> failwithf "No Union Case of Event Type %s Supports Construction from an Unhandled Exception: \r\n%O" typeof<'event>.Name ex
        else failwithf "Unable To Construct a Failure of type %s from Unhandled Exception: \r\n%O" typeof<'event>.Name ex

    let inline delay<'result,'event> (f: unit -> Result<'result, 'event>) = fun () ->
        try f()
        with | ex -> convertExceptionToResult ex

    let inline run<'result,'event> (f: unit -> Result<'result, 'event>) =
        try f()
        with | ex -> convertExceptionToResult ex

    let inline (>>=) result f = bind f result

    let inline apply wrappedFunction result =
        match wrappedFunction, result with
        | Ok a, Ok b -> Ok (a b)
        | Error e, Ok s -> Error e
        | Ok s, Error e -> Error e
        | Error e, Error _ -> Error e

    let inline (<*>) wrappedFunction result = apply wrappedFunction result

    let inline lift f result = apply (ok f) result

    let inline (<!>) f result = lift f result

    type EitherBuilder() =
        member __.Zero() = zero()
        member __.Bind(x, f) = bind f x
        member __.Return(x) = ok x
        member __.ReturnFrom(x) = x
        member __.Yield(x) = ok x
        member __.YieldFrom(x) = x
        member __.Combine (a, b) = bind b a
        member __.Delay f = delay f
        member __.Run f = run f
        member __.TryWith (body, handler) =
            try body()
            with | ex -> handler ex
        member __.TryFinally (body, compensation) =
            try body()
            finally compensation()
        member this.Using(d:#IDisposable, body) =
            let result = fun () -> body d
            this.TryFinally (result, fun () ->
                match d with
                | null -> ()
                | d -> d.Dispose())
        member this.While (guard, body) =
            if not <| guard ()
            then this.Zero()
            else bind (fun () -> this.While(guard, body)) (body())
        member this.For(s:seq<_>, body) =
            this.Using(s.GetEnumerator(), fun enum ->
                this.While(enum.MoveNext,
                    this.Delay(fun () -> body enum.Current)))

    let either = EitherBuilder()

Looking at your example usage of the EitherBuilder, I would probably change the while loop to a tail-recursive function.  You can still use while loops with the new EitherBuilder if you want, but using a tail-recursive function allows you to eliminate the mutable state, and correctly defining your Error cases as a discriminated union will allow you to access the failing values if you need to without having the global state i.  That would look something like this:

open Either

type Errors =
| OutOfRange of int
| UnhandledException of exn // This is required to allow conversion from Exceptions to Errors

let func i =
  if i < 3 then Ok(i)
  else Error <| OutOfRange i

let result =
    let rec loop i res =
        either {
            if i < 10
            then let! output = func i
                 return! loop (i + 1) output
            else return res
        }
    loop 0 0

In which case, result has the value:

Result<int,Errors> = Error (OutOfRange 3)


Calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999)

In an interview setting it is quite hard to come with an efficient solution (unless you happen to be very good in mental multiplication; however a \$99 * 91\$ example is a strong hint). The key to an efficient solution is an observation that

\$999999 * 999001 = 999000000999\$

is a quite large palindromic product. It means that you don't have to test the entire 6-digit ranges of multiplicands. It is enough to test multiplicands only in \$[999001.. 999999]\$ range. Just \$10^6\$ candidate pairs rather than \$10^{12}\$.

BTW, a similar identity holds for products of longer numbers as well.

Next, you may notice that there are just one thousand palindromic numbers larger than \$999000000999\$ (they are in form of 999abccba999), and to qualify as a solution is must have a 6-digit factor larger than \$999001\$. This implies the following algorithm (in pseudocode):

base = 999000000999
abc = 999
while abc >= 0
    cba = reverse_digits(abc)
    number = base + abc * 1000000 + cba * 1000
    for factor in 999001 to sqrt(number)
        if number % factor == 0:
           return number
    abc -= 1

The reverse_digits of a 3-digit number could be done extremely fast (a lookup table, for example). Still a \$10^6\$ or so rounds, but no expensive tests for palindromicity.

All that said, since the problem stems from Project Euler #4 it is possible that it admits a more elegant number-theoretical solution.