The biggest issues I see with this code is naming of Classes/Properties/Methods and proper separation of concerns.

I find the best way to think about separation of concerns is to think in terms of "has a" relationships to see if they make sense. For example, you might question whether a "Checkup has an employment status". When you put it that way, it's pretty clear that a Checkup doesn't make sense to have an employment status, but a Person might. It's pretty easy to fall into the trap of saying "I don't need to make a Person class because it's not that complex yet". This will come back to bite you later whether it's another developer that can't understand your code (maybe even yourself) or wishing you could more easily modify functionality because the elements are so tightly coupled.

Here's an example of how you might better organize your classes:

public class CheckUp
{
    public DateTime AppointmentTime { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }

    public Clinician Clinician { get; set; }
    public Patient Patient { get; set; }

    // A type of test might be a ColorVisionTest.
    public List<Test> TestsRun { get; set; }
}

public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

public class Clinician : Person
{
    public List<Licenses> Licenses { get; set; }
}

public class Patient : Person
{
    public List<Checkups> Checkups { get; set; }
}

public static class DatatableTestParser
{
    public static List<Test> ParseTests(DataTable dt)
    {
        // Parsing logic here.
    }
}

To keep harping on the separation of concerns, let's talk about a comment of yours:

  I am racking up my brain on how to create a Checkup Class, that can
  load the basic data form the data table

Typically you don't want to have something like a Checkup class also be concerned with parsing from things like a datatable. Again, a Checkup should only be concerned with being a Checkup and nothing more. You could have another class that did parsing from a DataTable or other data source, but the key is to separate it from the Checkup itself. Hopefully this helps.


Sure,

you are basically copy pasting to keep accessing arTab and promilleTab, you might instead just derive the indexes in arTab from bruddListe and arListe, like this:

function skrivUt(Event:MouseEvent)
{
  txtSvar.text = "I " + arTab[bruddListe-1][arListe-1] + " ble det anmeldt " + promilleTab[bruddListe-1][arListe-1] + " for promillekjøring";

etc. etc.

or you could keep things a bit more readable, by splitting it up, I dont know if this is correct ActionScript, but conceptually you should grok this:

function skrivUt(Event:MouseEvent)
{
  var ar:String =  arTab[bruddListe-1][arListe-1];
  var promille:String = promilleTab[bruddListe-1][arListe-1];
  txtSvar.text = "I " + ar + " ble det anmeldt " + promille + " for promillekjøring";

Furthermore, some other observations :

Try to keep your variables and function Names in English, it's the right thing to do
it seems as if bruddListe and arListe are global variables, you should avoid those


Linked List design and implementation - C++

You can simplify your code a lot.

    if(head == NULL)
    {
        n->prev = NULL;
        n->next = NULL;
        head = n;
    }
    else
    {
        n->next = head;
        n->prev = NULL;
        head = n;
    }

Both sides of this else look identical.
I think you can shorten your code with:

void list:: add_to_head(int num)
{
    nodePtr oldHead = head;
    head = new node{num, oldHead, nullptr);
    // Also you forget to do this bit.
    if (oldHead) {
        oldHead->prev = head;
    }
}

@pm100 covered the temporary variable.

nodePtr temp;
nodePtr prev;

You don't need these as a class member. It should be local to the member functions where they are used.

If I was you I would add another member though.

nodePtr tail;

Then you don't need to search for the tail every time you add a new element.

Const correctness. In a lot of code we pass variables by reference and const reference. If you pass an object by const reference you can only call const members on it.

So you should take care to mark functions that don't mutate the object as const. This will allow you to call the methods from a const reference. Also it enables some compiler optimizations when it knows you are not mutating the object.

So the following functions should probably be const.

void check_duplicates(int) const;
void print() const;

Your print() is fine. But I would make it more generic. Rather than print to std::cout you should print to a generic stream (you can always default to std:::cout.

print(std::ostream& str = std::cout) const;

Also in C++ printing is usually done via operator<<. So I would add this function. All it needs to do is call the print function passing the stream.

std::ostream& operator<<(std::ostream& str, List const& data)
{
     data.print(str);
     return str;
}


Checking if a date comes after another in Java

The obvious

As mentioned in @mtj's comment, we have three different JDK APIs for doing this, so you really shouldn't have to resort to reinventing-the-wheel.

java.util.Date.after(Date)
java.util.Calendar.after(Object)
java.time.LocalDate.isAfter(ChronoLocalDate)

Naming

Ok, maybe this is some simple assignment that you need to do... how about the naming? You should try to avoid using the same class name from the JDK, as it will get messy understanding which class is actually being used. For example, the wrong usage of your class might lead to confusing toString() representation, or syntax errors when trying to do a Date.getTime().

Also, since you are already using English mostly, you should translate that French-sounding method name to the English equivalent too, e.g. isAfter(). Whether you should have your entire codebase in non-English is another debating topic altogether. :)

Validation

You should be checking whether day and month are valid or not... you wouldn't want your bespoke class to start representing the 99th day of the 555th month of the 18288th year... assuming we're still talking about the Greogorian calendar.

null check

Next, assuming you have renamed this class, you should consider handling null properly: do you want to throw a NullPointerException as it is currently, or return a default value?

Boolean expressions

Finally, you can chain the boolean expressions together using && and || so that the method returns true the moment any of the expression is true too:

return dateToCompare != null && // assuming returning false for null values
        year > dateToCompare.getYear() || (year == dateToCompare.getYear() &&
            (month > dateToCompare.getMonth() || (month == dateToCompare.getMonth() &&
                day > dateToCompare.getDay())));

Admittedly, this is getting hard to comprehend.

(thanks to @JS1's answer for the update)


I can't comment on how secure your code is, however there are a couple of other problems that I would like to point out.

Clutter

Your using directives can be cut down to:

using System;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

Naming

Let me show you what I think of when I see a class called Sock:

You need to give that class a better name, for instance SslSocketMonitor. Actually, I don't know enough about your class to find a good name; use your brain to find a better one.
Let me show you what I think of when I see a class called Wrapper:

Because you are using it as a parameter to an event, this ought to be called something like SslSocketEventArgs, but certainly not Wrapper.
Decide on one naming convention and stick to it. You are using three different conventions for naming private fields:

private Dictionary<string, byte> Connections; // UpperCase
private Socket _sock;                         // _lowerCasePrefixed
private X509Certificate certificate;          // lowerCase

Your event names are nonstandard and not particularly clear.
Instead of AnnounceNewConnection try Connected,
instead of AnnounceDisconnection try Disconnected,
and instead of AnnounceReceive use ReceivedData.

API problems

.NET programmers are familiar with events. Therefore, it makes sense to implement the pattern properly:

SslSocketEventArgs (formerly Wrapper) needs to be derived from System.EventArgs
Instead of using Action:

public event Action<Wrapper> AnnounceNewConnection;
public event Action<Wrapper> AnnounceDisconnection;
public event Action<byte[], Wrapper> AnnounceReceive;

use the more expressive and conventional EventHandler<T>:

public event EventHandler<SslSocketEventArgs> Connected;
public event EventHandler<SslSocketEventArgs> Disconnected;
public event EventHandler<SslSocketEventArgs> ReceivedData;

It's not safe to directly invoke event handlers as they could easily be null. So define the following extension method to safely invoke the event handlers:

public static class EventHandlerExtensions
{
    public static void InvokeSafely<T>(this EventHandler<T> eventHandler,
                       object sender, T eventArgs) where T : EventArgs
    {
        if (eventHandler != null)
        {
            eventHandler(sender, eventArgs); // syntactic sugar for .Invoke
        }
    }
}

and replace all the usages:

Disconnected.InvokeSafely(this, wr);
Received.InvokeSafely(this, wr); // etc...

I'm not a fan of beginning listening in the constructor. It would be better to invoke that explicitly in a separate method.
There should be a way to cancel listening. Write a public method to enable this.

Programming errors

Your field Dictionary<string, byte> Connections is initialized but never used. Delete it.
You have lines like these spread throughout your code:

wr.sslStream.Close();
wr.sslStream.Dispose();

That scares me. What if you forgot to close it somewhere? It would be best to enclose all uses of the class in using statements where possible.
In ReceiveData, you make the following (constant) assignment:

SocketError error = SocketError.Disconnecting;

So the following condition will always be false:

if (error == SocketError.Success && size != 0)

What you are probably trying to do is instead of catch (Exception):

catch (SocketException e)
{
    // handle properly!
    Console.WriteLine(e.SocketErrorCode);
}


Initializing super class's variable from sub class

It is ok to have more than two layers if you have a good reason for it. But, because the code shows only a little part, you probably have other subclasses of ZmqSubscriber.

In SensorCollector you are hiding variables by defining new variables with the same name. This leads to a bad bug which is difficult to hunt down. In case you set the local variables and calling a method of the parent class, this method doesn't use the values of your local variables, so the method doesn't behaves like you would expect, but it is not the method's fault. You probably shouldn't hide the parent's variables.

In Collector.init() you assign a variable to itself, so those three assigns don't do anything.

Here a little prove. Note: I compare super.a and this.a with == to show that their reference are equal, which means they occupy the same memory.

class Parent { String a = "foobar"; }

class Sub extends Parent {
    Sub() { System.out.println(super.a == this.a); }

    public static void main(String[] args) {
        new Sub();
    }
}

I think init()-methods in general are doing the same job a constructor does. So in my opinion you should use constructors instead. If you cannot use a constructor have a look at the builder pattern.

This is my suggestion using constructors. I defined the variables of ZmqSubscriber as final because I think they should never change in the lifetime of the object. So you only have getters or you can make them public (but this is very controversial, depends on your coding standards).

abstract class ZmqSubscriber {
   protected final String zmqPort, zmqIp, zmpTopic;
   public ZmqSubscriber(String zmqPort, String zmqIp, String zmpTopic) {
      this.zmqIp = zmqIp;
      this.zmqPort = zmqPort;
      this.zmqTopic = zmqTopic;
   }
   public void start() {
      // connect to zeroMQ with initialized zmq port, ip, topic and receive data
   }
   // getters for zmq port, ip, topic
}

abstract class Collector extends ZmqSubscriber {
   public Collector(String zmqPort, String zmqIp, String zmpTopic) {
      super(zmqPort, zmqIp, zmpTopic);
   }
   public void otherMethod() { /*blablabla*/ }
}

class SensorCollector extends Collector {
   public SensorCollector(String zmqPort, String zmqIp, String zmpTopic) {
      super(zmqPort, zmqIp, zmpTopic);
   }
}

Is zmpTopic a typo? Shouldn't it be zmqTopic?


In this case, your indentation makes the code drift over to the right so does make the code difficult to read so does need some changes.

First I would note that a lot of code is repeated and also as noted a switch after converting the condition to an int is possible.

However in this case your code is effectively doing multiple lookups so I would look at using NSDictionaries (or NSArrays if the conditions are 0 to a number) and then do a straight lookup

e.g.
setup

NSDictionary* conditionsImages = [NSDictionary dictionaryWithObjectsAndKeys:
                @"113", @"Sun.png",
                @"116", @"Mostly_Sunny.png",
     ...
                nil];

Or read the dictionaries from a file

Access them by

- (void)updateImages:(ICB_WeatherConditions *)condition {
    conditionsImageView.image = [UIImage imageNamed:
                   [conditionsImages objectForKey:condition]];
    BGView.image = [UIImage imageNamed:[otherImages objectForKey:condition]];

  ...
}


Exception, errors handling, best practice in WebApi Core

Exceptions are pretty costly so as a general rule of thumb they should be avoided. Especially when we talk about REST endpoint where response time is crucial.

Also, to my taste you're messing up command-query separation principle in your code. I would have rewritten it roughly like this

[HttpPut("{taskId}/{userId}")]
[Authorize(Roles = "Developer, Manager")]
public IActionResult TakeTaskByUser([FromRoute] int taskId, [FromRoute] string userId)
{
    var task = this.taskService.GetTask(taskId);
    if (task == null)
        return this.NotFound();
    var taskValidationResult = this.taskValidator.Validate(task);
    if (!taskValidationResult.IsSuccess)
    {
        //handle validation failure
    }

    task = this.taskService.TakeTaskByUser(task, userId);

    return this.Ok(task);
}
```


I'm going to hit the high notes on my phone and swing back later with details unless someone beats me to it.

Allow null

Add a separate boolean field to track when next holds the actual next element rather than using null as a signal that it needs to be populated so that null elements can be supported.

Avoid Recursion

In this case, there's no reason for moveToNext to call itself. Continuing the loop should have the same effect.

Use Generics

Even though you're stuck using Object for variables which may hold an element or an iterable, you can still add a generic type T to the class and specify it as the return type from next. At least, I think you can. :)

Testing

When using the @Test annotation, you don't have to prefix each test method name with test. However, you really need more descriptive method names, and each test should validate one specific condition.

Burn this into your brain: Arrange, Act, Assert. Arrange the test fixture in the initial state, perform the action being tested, and assert the results. It can become tedious to setup the fixture each time, but helper methods can ease the pain and promote DRYness.


Add protocols inside the same file as controller

Consider nesting your types:
If you have two types that start with the same prefix, it's possible that one type is better nested inside the other.
For example: SendPINUseCase raises SendPINUseCaseError's
class SendPINUseCase {
    enum Error {
        case invalidPhone
        case couldNotSend
    }
}

Now you have a type called SendPINUseCase.Error, it's scoped to the SendPINUseCase. If you want to use throwing functions instead of returning Result<..., Error>'s, then you would make your SendPINUseCase.Error enum conform to Swift.Error
Protocols can't be nested, but in this case you could avoid them entirely by changing your design so that, for example, execute function takes, as arguments, the callback functions involved. If you eliminate the protocols, then there's no worry about which file to put them in, and protocols are not without their problems, I would say protocols are not the right abstraction in this case.
Your SendPINUseCase is a class but doesn't encapsulate any state, so consider making it a struct.
You have execute function take a String as input, and then validate that string is a 'phone'. Instead, consider making a struct Phone that has a failable initializer, so that only valid 'Phone's can be constructed. Then execute function would take a Phone struct that you know is valid, that eliminates the invalidPhone error case entirely.


Update dictionary in constant time in Python

You can accomplish this using the standard collections.OrderedDict. According to the docs:

  Deleting an entry and reinserting it will move it to the end.

By default, the presentation will be in insertion order. For you, that is reversed, so you will want to reverse the ordering when you iterate (using .keys() or .items()).

Update

To use the ordered dictionary, you'll have to import collections (unless you're using python3.6, where I think dictionaries become ordered by default- check that).

So:

import collections

od = collections.OrderedDict()

def insert(ticker, price):
    '''
    Insert a ticker->price pair. If ticker is already stored, move it
    to the end (last updated).
    '''
    if ticker in od:
        del od[ticker]

    od[ticker] = price

def each_ticker():
    '''Return ticker symbols in reverse order of insertion'''
    return reversed(od.keys())

def each_ticker_price():
    '''Return (ticker, price) pairs in reverse order of insertion'''
    return reversed(od.items())

insert('AAPL', 100)
insert('MSFT', 200)
insert('GOOG', 300)
insert('AAPL', 400)
insert('MSFT', 350)

for name, price in each_ticker_price():
    print(name, "trading at", price)

Output is:

$ python test.py
MSFT trading at 350
AAPL trading at 400
GOOG trading at 300


Programming in German results in an awkward mix of English and German identifiers, with conflicting capitalization conventions.  I suggest sticking to English, though I will make an attempt to accommodate your language preference here.

The code is duplicated not only for each eye, but also for each axis, resulting in four copies.  The copy-and-pasted code is hard to follow because you have pasted them in an order that is not quite parallel:

var abstandV1 = …;
var pupilleL1 = …;
var augeLinks = $("#augeLinks")
var distanceX=…;
var distanceY=…;
if …
var abstandH1 = …;
var pupilleL2 = …;
if …

A more logical order would be:

var augeLinks = $("#augeLinks");
var abstandLY = …;
var pupilleLY = …;
var distanceLY = …;
if …
var abstandLX = …;
var pupilleLX = …;
var distanceLX = …;
if …

Instead of using if-statements the enforce the lower and upper bounds, I suggest using Math.min() and Math.max().

Using the same code for the left and right eyes is easy: just make smarter use of jQuery selectors:

$('.pupille').each(function() {
    var $pupille = $(this);
    var $auge = $(this).closest('.auge');
    …
});

Writing one version of the code for both the horizontal and vertical axes is tricker.  I suggest defining a horizontal and a vertikal object to extract the relevant attributes.

var horizontal = {
    groesse:  function($el) { return $el.width(); },
    position: function($el) { return $el.position().left; },
    offset:   function($el) { return $el.offset().left; },
    cursor:   function(event) { return event.pageX; },
};
var vertikal = {
    groesse:  function($el) { return $el.height(); },
    position: function($el) { return $el.position().top; },
    offset:   function($el) { return $el.offset().top; },
    cursor:   function(event) { return event.pageY; },
};

function koordinate($pupille, $auge, cursor, achse) {
    var augeGroesse = achse.groesse($auge) - achse.groesse($pupille);
    var abstand = achse.cursor(cursor) +
                  achse.position($pupille) -
                  achse.offset($pupille) -
                  achse.groesse($pupille) / 2;
    return Math.max(0, Math.min(augeGroesse, abstand));
}

$(document).on('mousemove', function(event) {
    $('.pupille').each(function() {
        var $pupille = $(this);
        var $auge = $(this).closest('.auge');
        $pupille.css({
            left: koordinate($pupille, $auge, event, horizontal) + 'px',
            top:  koordinate($pupille, $auge, event, vertikal) + 'px',
        });
    });
});
.auge {
  position: relative;
  display: inline-block;
  width: 150px;
  height: 150px;
  border: 10px solid black;
}
.pupille {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 30px;
  height: 30px;
  background-color: blue;
  border-radius: 15px;
}


Using this-> to refer to class members
Ditch this. It's unnecessary unless you need to have to refer to inherited members or disambiguate any other variables or parameters.


First of all: Use a StringBuilder instead of System.out.println so you can easily compare the result of your method with an expected output.

Your test could look like: (I renamed you method to draw and moved the size to the instance.)

@Test
public void test4()
{
    StringBuilder expected = new StringBuilder();
    expected.append( "   * \n" );
    expected.append( "  * * \n" );
    expected.append( " * * * \n" );
    expected.append( "* * * * \n" );
    expected.append( " * * * \n" );
    expected.append( "  * * \n" );
    expected.append( "   * \n" );
    assertEquals( expected.toString(), new Diamond( 4 ).draw() );
}

After you have all your tests (I have just created some for 0-4) you can try to extract some methods with duplicate code.

public class Diamond
{
    private int size;

    public Diamond( int size )
    {
        this.size = size;
    }

    public String draw()
    {
        StringBuilder result = new StringBuilder();
        for( int ucount = size; ucount > 0; ucount-- )
        {
            appendSpaces( result, ucount - 1 );
            appendStars( result, size - ucount + 1 );
            newLine( result );
        }

        for( int lcount = 1; lcount < size; lcount++ )
        {
            appendSpaces( result, lcount );
            appendStars( result, size - lcount );
            newLine( result );
        }
        return result.toString();
    }

    private void newLine( StringBuilder result ) // just for better readability
    {
        result.append( "\n" );
    }

    private void appendStars( StringBuilder result, int count ) // just for better readability
    {
        repeat( result, "* ", count );
    }

    private void appendSpaces( StringBuilder result, int count ) // just for better readability
    {
        repeat( result, " ", count );
    }

    private void repeat( StringBuilder result, String string, int count )
    {
        for( int c = 0; c < count; c++ )
            result.append( string );
    }
}

If you want to get rid of one of the loops you could even merge it to:

public String draw()
{
    StringBuilder result = new StringBuilder();
    for( int ucount = size; ucount >= -size; ucount-- )
    {
        boolean isMiddleRows = ucount == 0 || ucount == -1;
        if( isMiddleRows ) continue;
        appendSpaces( result, Math.abs( ucount ) - 1 );
        appendStars( result, size - Math.abs( ucount ) + 1 );
        newLine( result );
    }
    return result.toString();
}

It's pretty cool to have enough tests do try such refactoring :)


How can I make this primality test algorithm faster?

Avoid dealing with BigDecimals at all costs - they are slow. I changed the formula to work with "twice the number", so my s is actually 2*s. Further keep the numbers in the loop small by "modding" the intermediate results, too. Finally I tried to simplify the syntax and the initial conditions for s a little bit.

import java.math.BigInteger;

public class WPT {

    private final static BigInteger _1 = BigInteger.ONE;
    private final static BigInteger _2 = _(2);
    private final static BigInteger _4 = _(4);

    public static BigInteger _(long n) {
        return BigInteger.valueOf(n);
    }

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);

        BigInteger m = _(n);

        BigInteger s =
                (m.mod(_(4)).equals(_1)) ? _(3) :
                        (m.mod(_(6)).equals(_1)) ? _(11) :
                                (m.mod(_(12)).equals(_(11)) &&
                                        (m.mod(_(10)).equals(_1)) ||
                                        m.mod(_(10)).equals(_(9))) ? _(27) : _(33);
        BigInteger r = s;

        BigInteger W = _2.pow(n).add(_1).divide(_(3));

        int k = (n - 1) / 2;

        for (int i = 0; i < k; i++) {
            BigInteger s2 = s.modPow(_2, W);
            BigInteger s4 = s2.modPow(_2, W);
            s = s4.subtract(s2.multiply(_4)).add(_2).mod(W);
        }

        System.out.println(s.equals(r) ? "prime" : "composite");
    }
}


Count the word frequencies within a given directory

#!/usr/bin/python3
import os
import re
from os.path import join
from collections import Counter, OrderedDict

def count_words(directory, ext): # don't use the name dir, it's a builtin function
    """Counts word frequencies in a directory of files.

    Keyword arguments:
    directory -- count_words will search this directory recursively
    ext -- the extension of files that you wish to count

    Returns an OrderedDict, from most to least frequent.

    (You don't strictly need a docstring, but it's a good habit to get into.
    See PEP 257.)"""

    # Initialize the counter
    word_counter = Counter()

    # Personally I like to break my code into small, simple functions
    # This code could be inline in the loop below,
    # but I think it's a bit clearer this way.
    def update_counter(word_counter, filename):
        '''updates word_counter with all the words in open(filename)'''
        with open(filename, 'r') as f:
            try:
                # Two things:
                # First, I'm updating counter here,
                # instead of creating an enormous string.
                # Each file string only exists long enough for me to search it.

                # Second and less important,
                # I chose to lower the full text first, to make the regex simpler.
                word_counter.update(re.findall('[a-z_]+', f.read().lower()))
            except UnicodeDecodeError:
                # In python3 if your file isn't UTF-8
                # then read() throws an exception.
                # Maybe you want this behavior,
                # but I'd rather just warn and continue.
                print("Warning: couldn't decode", filename)

    # Using os.walk instead of glob
    for root, dirs, files in os.walk(directory):
        for fname in files:
            if fname.endswith(ext):
                update_counter(word_counter, join(root, fname))

    # words_counter.most_common() does exactly the sort you are looking for
    return OrderedDict(word_counter.most_common())


onSaveInstanceState() - ensuring a call to super instance

I think it is a very good practice.

As a side note, if you want to design a method like those, I'd suggest you to make the API method final and let the custom behaviors to be injected with the strategy design pattern (if you want to use composition, which is what I like the most) or with the implementation of an abstract method (if you want to use inheritance).

In that way it won't be possible to skip, even on purpose, the call to the superclass method.


Logic for an init function in email parser

Notes:

Personally I prefer to keep the initialization method simple and lean. Just setup the minimum state of the object, let subsequent calls to methods do the real job when it's needed. Otherwise, why use a class? Maybe you don't need a class at all and just a function would do?
assert isinstance(message, basestring): Python is a dynamic language, embrace the fact and don't lose a second checking whether every argument has the type you expect (instead, write good docstrigs so the user knows how to call it). Another question is checking that given values satisfy some precondition (i.e assert len(s) >= 10).


All modern browsers support ES5 which means array.forEach will exist. You can use that to replace $.each. The overhead of $.each comes from checking if it's an array or object and using the appropriate loop operation.

The same goes for the creation of li and ul. You can simply replace it with document.createElement. The overhead of $() is because it's a multi-purpose function. It can create an element, alias document.ready, wrap an array or object, grab elements from the DOM, an alias to jquery.find if given a context, and more.

You don't really need to go OOP on this one. A simple recursive function is all you need for this to work. Going the OOP route means you're creating instances of an object, in this case, Menu - an unnecessary overhead. If you want structure, the data is already your structure.

Try to batch the render, preferably all at once to the very end of the process. This is because DOM manipulation is slow. In your case, you already appended the list to the container before processing the descendants nodes. This means every time you append a descendant, the browser has to render that in the DOM.

Lastly, that <div> is unnecessary.

Here's a rewritten version using a simple recursive function. It runs 3~6ms depending on the browser's mood.

function createMenu(nodes, container){
  var list = document.createElement('ul');

  // Use native array.forEach
  nodes.forEach(function(node){
    var listItem = document.createElement('li');
    listItem.textContent = node.Name;
    list.appendChild(listItem);

    // If no children, return early to skip code below.
    if(!node.Children) return;

    // Process descendants next.
    var childList = document.createElement('li');
    createMenu(node.Children, childList);
    list.appendChild(childList);
  });

  // Only when the list is fully formed do we append it to the parent
  container.appendChild(list);
}

createMenu(children, document.getElementById('container'));


Function that divides money with regard to the smallest denomination

I can make infinite money (well, as much as will fit in a javascript number) with your code!

var money = 10;
while(true){
    money = divideMoney(money, [3, 0], 1)[0];//muhahahahah infinite money
}

Which divides the money like so: 1 for me, 1 for myself, 1 for I, none for you. 1 for me...

I'd recommend in this case to fall back on relative percentages: that is, sum the percentages and then set the cut to be the percentage of the summed percentage. So 10, 5, 5 = 20 total, 10/20 = 0.5, 5/20 = 0.25, so it's 0.50, 0.25, 0.25.


Do you see any flaws in my code and anything that could be improved?

Segregate code

Splitting into bin_add.c, bin_add.h, main.c would help delineate what is the code, its user interface and test code.

No compilation errors

As posted now, I did not notice any warnings either- good.

Some comments would help

gpp() would benefit with at least a line comment about its goal, expected input, output, etc.  Same for bin_add() - which should alert that the return pointer needs to be free'd.  This becomes even more important when the user only has access to the declaration in a .h file.

Commenting some of the block of code would help too.

When to shift

When there is not a final carry, code shifts Ol[].  As a final carry with this FP-like code is more rare, I'd shift when there is a carry.

Collapsing

With floating point strings, I expect code to drop trailing zero digits to the right of the '.'.

Leading zero digits are possible based on input.  Perhaps eat those too with an early while (*a == '0') a++; and with b. - depends on coding goals though.

Inconsistent bracket style

//                                v ??
pp[i] = pp[i] ? ll[i] - pp[i] : 0;}

Hopefully code is auto-formatted.

Inconsistent indentation

if((Ol[0] = '0' + xc) == '1') return Ol;
//  v   Why indented here?
    for (size_t i = 0; i <= ML - lO + 1; ++i)
        Ol[i] = Ol[lO + i];

This implies code is not auto formatted.  Save time, and use auto-formatting.

Terse digit like object names lose clarity

The short object names OO, lO, O, Ol, ll look too much like 00, 10, 0, 01, 11.  Consider more clear alternatives.

Other examples:
int xc as the carry bit looks more clear as int carry.
size_t ML more meaningful as MaxLength.

Input error detection

I'd suggest a separate bool bin_valid(const char *s) and let bin_add() assume  valid strings a,b.  This would help simplify - a NULL return would only indicate out-of-memory.

Good use of cast to ward off warnings

return n  ? (size_t)(n - s + 1) : 0;
//          ^------^

Misc.

ops[2], cc[2] could be local to for (size_t i = ML; i; --i) {

Good use of const.

Good use of size_t.

Personal preference: Consider char *Ol = calloc(ML + 2, sizeof *Ol);

Main

Do not assume EOF is -1

Simply test if the scanf() result is 2.

// while (scanf(" %80[0.1] %80[0.1]", a, b) & 1 << 1) {
while (scanf(" %80[0.1] %80[0.1]", a, b) == 2) {

ENOMEM

ENOMEM is not part of the standard C.

Test cases

Some specific example test cases would be useful.

  maybe even C90/C89

Not quite.

Lots of error: 'for' loop initial declarations are only allowed in C99 or C11 mode problems

warning: control reaches end of non-void function [-Wreturn-type]

error: redefinition of 'i'


Code separation

What you have there is everything mixed together - just by moving the php logic to the top of the file, makes it easier to read. With some minor reformatting it becomes easier to read/maintain:

<?php
$states = getStates();
$statusList = getCxStatusList();
?>

    Name:<input type="text" id="cxByNameInput" name="cxByNameInput"/>

    State:
    <select id="cxState">
        <option></option>
    <?php while($state = $states->fetch_assoc()): ?>
        <option value="<?= $state['st'] ?>"><?= $state['state'] ?></option>
    <?php endwhile; ?>
    </select>

    Status
    <select id="cxStatus">
        <option></option>
    <?php while($status = $statusList->fetch_assoc()): ?>
        <option value="<?= $status['cxType'] ?>"><?= $status['cxTypeDescription'] ?></option>
    <?php endwhile; ?>
    </select>

Format for readability

If you're jumping in and out of php - having lines like this: {?> make things hard to read, especially if there is some nesting in the code. Whether you choose to use curly braces or the alternate (colon) syntax is up to you, but in html code using a style which aides readability (putting the curly brace/colon on the same line as the statement it relates to) helps.

No PHP Short tags

Shorttags are often considered a bad practice, and as such should be avoided unless the code is your own, and you control where it's going to be used. Note that you can use <?= with PHP 5.4 irrespective of the shorttags setting.

Consistent whitespace

The following:

<? foo(); ?>

Is easier to read than

<?foo();?>

Especially where it appears inline somewhere - use whitespace for readability.

Sprintf

If you find that your code gets to be like this:

<foo x="<?= $x ?>" y="<?= $y ?>"  z="<?= $z ?>"> ...

Then it's probably easier to read and maintain using:

<?php echo sprintf('<foo x="%s" y="%s" z="%s">...', $x, $y, $z); ?>


Instead of magic numbers, extract them to either explaining variables or constants.
For example, in neighbor_counts, what are -1, 0, and 1?
People who are familiar with the GoL might know what you're trying to do, but assume you're passing this off to someone who is new to the GoL and doesn't know what these constants represent.


StreamReader is IDisposable and therefor the use of it should be wrapped in a using block like this:

using (TextReader tr = new StreamReader(csvFileName))
{
    ...
}

You are reading all files into memory and then writing it out. While this probably has a fairly good performance as it's first performing a bunch of (probably) sequential reads of all the files and then one big block write you could consider writing it out as you read it:

using (var writer = new StreamWriter(outputPath))
{
    foreach (var csvFileName in csvFileNames)
    {
        using (var reader = new StreamReader(csvFileName))
        {
            string headers = tr.ReadLine();

            if (!hasHeader)
            {
                writer.WriteLine(headers);
                hasHeader = true;
            }

            writer.Write(reader.ReadToEnd());
        }
    }
}

If the files are very big you even might want to consider reading the input line by line and writing it to the output line by line. This will be less performant but also use much less memory. In the end it's a trade off between speed and memory consumption (as it often is in software development).

The other advantage with the write as you go method is that you open the output file first - so if there is a problem with writing to the target you will know before you do any work at all.


The indentation within update() is misleading.  Most of all, everything inside of the function should be indented.  Otherwise, it'll be hard to tell what exactly is inside of the function.

I do, however, like that you've indented the (lengthy) parameter list by eight spaces instead of the standard four.  It should be easier to tell them apart from the code inside of the function.
More whitespace within statements can be added for more readability.

This line, for instance, is hard to read:

Ap[i]=cX*(p[i-sX]+p[i+sX]-2.0f*p[i])

You can add more whitespace as such:

Ap[i] = cX * (p[i-sX] + p[i+sX] - 2.0f * p[i])

Now you can really tell what everything is at a glance.

You can also add a space before the opening curly braces for functions.  It may not be a big deal with functions with smaller signatures, but yours are pretty lengthy, and it's harder to see the opening curly brace with them.

You also have inconsistent whitespace, such as in here:

for(int offset = blockDim.x/2;offset>0;offset>>=1){

There is spacing between the =, but nowhere else.  This should look clearer:

for (int offset = blockDim.x / 2; offset > 0; offset >>= 1) {

Considering that CUDA's blockIdx and blockDim are primarily signed, you should make your thread ID variables of the same type.  If they won't be too large, make them int.  If they can be larger than an int, make them either long or long long and cast blockIdx to the same.


Interpreting database values as times and integers

I was wondering if there was anything else that can be done

Well, morally, no. You can either return a nullable value (Maybe UTCTime) or lie (read "1970-01-01 00:00:00 UTC" :: UTCTime) but you can't turn a DbNumber 1 :: DatabaseItem into a UTCTime both unconditionally and truthfully.

The good news is, if you hit on the right set of higher-order functions you don't need to. Maybe values are very easy to work with when you know the extra tools available in Data.Maybe.

Taking as a whole this set of functions related to dates—

filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate [] = []
filterDbDate dataBase = [extractUTCTime item | item <- dataBase, isDbDate item]

isDbDate :: DatabaseItem -> Bool
isDbDate (DbDate _) = True
isDbDate _          = False

extractUTCTime :: DatabaseItem -> UTCTime
extractUTCTime (DbDate utcData) = utcData

mostRecent :: [DatabaseItem] -> UTCTime
mostRecent dataBase = foldr max y ys
                where dates = filterDbDate dataBase
                      y     = head dates
                      ys    = tail dates

We'll begin by throwing out isDbDate and extractUTCTime and writing the DatabaseItem -> Maybe UTCTime function you avoided.

dbDate :: DatabaseItem -> Maybe UTCTime
dbDate (DbDate utc) = Just utc
dbDate _            = Nothing

Now pulling from Data.Maybe, we'll replace filterDbDate with an equivalent code fragment that utilizes mapMaybe.

-- filterDbDate :: [DatabaseItem] -> [UTCTime]
-- filterDbDate db =
     mapMaybe dbDate db

We can use that definition in mostRecent, a function from the standard Prelude, and point free style to achieve a one liner that more than just being clever, emphasizes the power of abstraction in producing concise code that will be instantly comprehensible to other Haskell programmers.

mostRecent :: [DatabaseItem] -> UTCTime
mostRecent = maximum . mapMaybe dbDate

mostRecent still commits the sin of using a partial function though, maximum throws an exception (much like your use of head and tail did before) when the filtered list is empty. Until such time as partial functions are excised from base (and O, do we all lust for and fear such a tumultuous day) you should familiarize yourself with the safe package, which has no dependencies besides base, and provides many alternatives to the partial functions we all know and love.

import Safe.Foldable (maximumMay)

mostRecent :: [DatabaseItem] -> Maybe UTCTime
mostRecent = maximumMay . mapMaybe dbDate


Stable-sorting all even numbers before odd numbers in a linked list

The best way to accelerate your code is to defenestrate it (9.82 m/s2) and use the correct algorithm.

You don't need to do anything fancy. Just go through the list once, print all the even numbers, go through once more and print the odd ones.


Checking if characters in a string can be rearranged to make a palindrome

Strange output

What is a user to think when seeing such output of a program?

The output is a palindrome.
The output is not a palindrome.

I wouldn't know what this program is trying to tell me.

Consider this alternative:

void print_result(char * s)
{
    printf("The characters of \"%s\" %s be rearranged into a palindrome.\n", s, pal_perm(s) ? "can" : "cannot");
}

int main()
{
    print_result("abbas");
    print_result("deeds");
    print_result("dead");
}

Output:

The characters of "abbas" can be rearranged into a palindrome.
The characters of "deeds" can be rearranged into a palindrome.
The characters of "dead" cannot be rearranged into a palindrome.

Though actually I would prefer something much simpler than that:

printf("\"%s\" -> %s\n", s, pal_perm(s) ? "true" : "false");

Producing output:

"abbas" -> true
"deeds" -> true
"dead" -> false

Usability

It would be more interesting if the program took the strings from the command line, instead of using hardcoded values, for example:

int main(int argc, char ** argv) {
    for (int i = 1; i < argc; i++) {
        print_result(argv[i]);
    }
}

For the record, @Law29 suggested another alternative in a comment:

  You can also read from standard input. This lets you either type in words as they come to mind, or use a whole file (there are files of dictionary words, for example). Example:

#define MAX_WORD_SIZE 50
int main(int argc, char ** argv) {
    char buf[MAX_WORD_SIZE]
    while (fgets (buf, MAX_WORD_SIZE, stdin)) {
        print_result(buf);
    }
}

Testing

Getting the implementation right can be tricky.
You revised your post 3-4 times to fix bugs pointed out in comments.
It's good to automate your tests so that they can be repeated easily,
for example by adding methods like these:

void check(char * s, bool expected)
{
    if (pal_perm(s) != expected) {
        printf("expected \"%s\" -> %s but got %s\n", s, expected ? "true" : "false", expected ? "false" : "true");
        exit(1);
    }
}

void run_tests()
{
    check("a", true);
    check("aa", true);
    check("aba", true);
    check("abba", true);
    check("aabb", true);
    check("aabbs", true);
    check("deeds", true);

    check("ab", false);
    check("abc", false);
    check("dead", false);
}

Use boolean expressions directly

Instead of this:

if(oddCount <= 1)
    return true;
else
    return false;

You can simply return the boolean expression itself:

return oddCount <= 1;

Excessive looping

As @DarthGizka explained, instead of this:

for(char ch = 'a'; ch <= 'z'; ch++)
{
    for(int i=0; i < size; i++)
    {
        if(str[i] == ch)
            alpha[str[i]]++;
    }
}

This is identical, but without unnecessary looping:

for(int i=0; i < size; i++)
{
    alpha[str[i]]++;
}

Unnecessary conditions

The first condition is unnecessary:

    if(alpha[j] == 1 || (alpha[j]%2==1))

This is exactly the same:

    if(alpha[j]%2==1)

Too compact writing style

Instead of this:

    if(alpha[j]%2==1)

I suggest to put spaces around operators, and before ( in if statements:

    if (alpha[j] % 2 == 1)

Stop iterating when you already know the result

Once you find two characters with odd number of occurrences,
you can stop iterating and return false.
As such, you don't even need an int oddCount, but a bool seenOdd.
So instead of this:

int oddCount = 0;

//count the number of times a letter only appears once
for (int j = 0; j < 256; j++)
{
    if (alpha[j] % 2 == 1) oddCount++;
}
//if there is more than one letter that only occurs, then it
//cannot be a palindrome.
return oddCount <= 1;

You could write:

bool seenOdd = false;

// scan for odd number of occurrences, stop after seeing two
for (int j = 0; j < 256; j++)
{
    if (alpha[j] % 2 == 1) {
        if (seenOdd) return false;
        seenOdd = true;
    }
}

// less then 2 letters with odd number of occurrences, must be true
return true;


Using % for string formatting is deprecated, you should be using str.format instead. The str.format methods also allows you to do some cool things as well. Here's an example of it in action:

# No positional or named arguments
print "{} {}".format("Hello", "world")

# Positional arguments (*args)
print "{1} {0}".format("world", "Hello")

# Named arguments (**kwargs)
print "{word1} {word2}".format(word1="Hello", word2="world")

When running the line Tk.mainloop(), you should encapsulate it in an if __name__ == "__main__": block. See this Stackoverflow question for more details.

These two lines should be moved underneath all of your imports/includes:

matplotlib.rcParams['toolbar'] = 'None'
matplotlib.use('TkAgg')

I'm also noticing your lack of comments as well. Even if this is a small utility script, I'd still recommend adding comments for clarity.

Finally, a few of your variable names confuse me. For example, f, a, and j are all good examples of names that could be better. Try seeing if you can expand on these.


how can I improve the check name file part

I have two minor comments.

First, I prefer having my variables defined in all branches, to avoid the PHP Notice:  Undefined variable:... error in logs. So, an initialization

$isMove = false;

would be nice. Btw, maybe $isMoved seems a bit more accurate/correct name. This part might also be written like this:

if (!is_uploaded_file($_FILES['file']['tmp_name'])) return false;
$safe_filename = $dateadded . preg_replace(array('/\s+/', '/[^-\.\w]+/'), array('_', ''), trim($_FILES['file']['name']));
if ($_FILES['file']['size'] > $MAXIMUM_FILESIZE) return false;
if (!preg_match($rEFileTypes, strrchr($safe_filename, '.'))) return false;
if (!move_uploaded_file($_FILES['file']['tmp_name'], $dir_base . $safe_filename)) return false;
return $safe_filename;

Depending on your taste, this might be easier to read.

My second comment is related to this:

$rEFileTypes = "/^\.($filetype){1}$/i";

What is the purpose of {1} (which means "repeat once")? I'd write that regex like this:

$rEFileTypes = "/\.($filetype)\$/i";

and I would replace

preg_match($rEFileTypes, strrchr($safe_filename, '.'))

with

preg_match($rEFileTypes, $safe_filename)

It seems to me a bit less cluttered this way, and I'd expect such regex to be faster than doing the old one + strrchr, but I have no proof that it really is. However, I don't think this is a kind of code in which speed is very important (upload of a file and moving it around will eat up much more time).

Btw, $filetypes might be a bit better name.

A bit more important comment is regarding the possibility that, given a long enough filename, your safe one will grow too long when you prepend it with a date, and you will lose the file extension (or a part of it). You might want to address that issue by checking the length and trimming the filename part if needed.

Now, for the general approach, there is a question about what you're doing with this. Usually, it is better to keep the original filenames in a database, and to store the uploaded files under a completely generic name (using, for example, an auto_increment primary key from the filenames table). Also, if you don't need filenames at all, you can then just make them generic.

Notice that your $dateadded makes it very likely that your filenames are unique, but it doesn't really guarantee it. Depending on your use and the expected number of users, this might be a potential problem (although I wouldn't expect it).


First off, a pet peeve of mine: while 1 makes no semantical sense. You want while True.

However, in your case you actually want while ct_changed:

ct_changed = True
while ct_changed:
    ct_changed = False
    for block in newtry:
        success, newcatchtype = block.isCatchExtendable(newhandler, catchtype)
        if not success:
            if catchtype == newcatchtype:
                break
            else:
                catchtype = newcatchtype
                ct_changed = True

Alternatively, you can flatten the nesting level by inverting the if not success conditional, and continuing:

        …
        if success:
            continue

        if catchtype == newcatchtype:
            break

        catchtype = newcatchtype
        ct_changed = True

(In fact, I’d probably go for this.)


This seems quite fine to me.
One thing that pops to mind is that I lose the ability to see the status code of the error as you only reject with the message text. I would wrap that in an object where the statuscode is also exposed.


Improved the output of the related posts in WordPress

The major thing for me in this code is the repetition forms a large part of it.  You can also use some of the features of PHP to stop having to move data around and comparing individual items.

Using array_column() (this requires PHP 7+ as your input is an array of objects) to fetch all of the values of cat_ID, stops you having to extract the values from the objects and then compare each one individually.  You can then use in_array() to check for each value against all of them in one call rather than the list of || conditions.

Then the code setting $args is the same in each branch of your if, so I've reduced this to each branch sets $cat (as your last branch already does) and then this is used by the same code outside the if...

$cat = get_the_category();

$categories = array_column($cat, "cat_ID");
if ( in_array(10, $categories) ){
    $cat = 10;
} elseif (in_array(12, $categories)){
    $cat = 12;
} else {
    $cat = $cat[0]->cat_ID;
}
$post = get_the_ID();
$args = array('cat'=>$cat, 'orderby' => 'date',
    'showposts' => $related,'post__not_in' => array($post));


Inline isn't
This pops up on CodeReview regularly. inline is effectively ignored by most modern compilers, and even if it weren't, it isn't a good idea to force the matter -- programmers do not know what's best for their program when compared to the compiler when full optimization is enabled. It's safe to omit this.
Redundant initial values
uint8_t* m_Buffer = nullptr;
size_t m_BufferSize = 0;

These are initialized by your constructor, so there's no point in pre-initializing them here.
Type punning
This:
*(value_t*)&m_Buffer[byte_offset]

is a little gross. There are better ways to do inline pointer casts, particularly in C++. Here, since you're punning from uint8_t* to a pointer of arbitrary type, you'll probably want reinterpret_cast.
I guess bit_size should be 64 if you pass uint64_t for value_t, but I don't see why it's passed separately. You can move bpb up in scope; then bit_size would equal bpb * sizeof(value_t). Perhaps you want to support bit_size smaller than the value type, which is fine; but you should at least assert that bit_size is less than or equal to the number of bits in value_t.
There are subtler risks in the way that you're packing bits - from what I can tell, it assumes little-endian, which will not be universally true.


kryptein cryptography package for Node.js

think I should prefix this by saying I'm not a JS or Crypto nerd, but am interested in both!  to other people seeing this question, this code/module seems to mostly reimplement the CCM demo at the bottom of the Crypto docs:  https://nodejs.org/api/crypto.html#crypto_ccm_mode

anyway on with a few issues I noticed:

why isn't _iv just returning crypto.randomBytes(iv_size)?  encoding to a string and then getting bytes seems counterproductive at best, it just seems to throw away entropy
why use PBKDF2 over just hashing the secret?  it's not being saved anywhere, and by using the secret as the salt you've just opened it wide up to rainbow table exploitation again.  further, by doing your string encoding things you've just thrown away even more entropy
your use of regexes in _matrix looks suspect.  why not just match against a few common patterns (e.g. /^\w+-\w+-\w+/) and handle the groups explicitly.  allowing modes like ECB at all here looks like a mistake
catching exceptions just to immediately rethrow doesn't seem very useful
can you think of a better name for the member variable flag?  maybe something like is_aead_mode

update:

another big issue just occurred to me; that you're not including any cryptographic details in the structure.  this allows the suite used to be upgraded (e.g. NIST update their recommendations) while maintaining backwards compatibility.  i.e. you should be saying that you're hashing the secret with SHA512, which algorithm was used for encryption, what you've used as a HMAC (if you've used it, CCM already includes its own MAC so HMAC isn't needed).


Generating all combinations and permutations of a set of symbols

Just use the standard modules :)

import itertools
for e in itertools.permutations('abc'):
    print(e)


1. Bugs

All the bugs in this section are to do with handling of bad input; see §2.1 below for more about this issue.

If there are no sequences in the input, your function wrongly yields an output sequence:

>>> from StringIO import StringIO
>>> list(read_fastq(StringIO('')))
[(None, None, None)]

If the input is wrongly formatted, your program can go into an infinite loop waiting for a line starting with a plus sign:

>>> list(read_fastq(StringIO('@ID\nSEQUENCE\n')))
^C
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr32897.py", line 155, in read_fastq
    sequence += line.rstrip().replace(' ', '')
KeyboardInterrupt

If the input is wrongly formatted, your program can go into an infinite loop waiting for the end of the quality data:

>>> list(read_fastq(StringIO('@ID\nSEQUENCE\n+ID\nSCORE')))
^C
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr32897.py", line 162, in read_fastq
    if len(score) >= len(sequence):
KeyboardInterrupt

2. Other comments on your code

You don't detect or report problems in the input. You just ignore or suppress them. This leads to outright bugs, as noted in §1 above, but it also means that you don't detect other problems with the input, like these:

missing sequence id;
junk lines before the first sequence or between sequences;
sequence id on + line fails to match sequence id on @ line;
length of quality data fails to match length of sequence data;
quality data contains characters outside the correct range.

You shouldn't ignore or suppress errors in the input, because you need to know about these errors in order to discover problems with your processing pipeline. What if you are being fed the wrong input? What if the input is in the wrong format (for example, FASTA instead of FASTQ)? What if there is a bug in the code that generated the input? If you don't detect errors then you will end up generating bogus output and causing trouble for whatever process is next in your processing pipeline.

When writing code that parses input data, the code for detecting and reporting errors typically constitutes the majority of the code. See §3 below for how I would go about writing this kind of parser.
The first item of each output tuple (the sequence id) starts with the @ sign, but the @ sign is not part of the id.
Your claim, "Deciding what is a quality score and what is an id is a tricky endeavor with many pitfalls" is a bit exaggerated. As far as I can see there is just one pitfall, namely that you might incorrectly stop reading the quality data when you encounter a line starting with @. If there are other pitfalls, you should probably mention them in a comment in the code so that we can check that they are all avoided.
It's not clear to me what the H means in the variable name fileH. Does it stand for "handle"? If that's what you mean, you should write it out for clarity: file_handle. But really there's no reason not just to use the name file here.
Your code contains two docstrings, but only the first is actually available to a user via the help function. The second docstring should be a comment instead — or better still, break it up into small comments that appear next to the relevant bits of code.
The actual comments could be better. There is really no need to write comments like this:

line = fileH.readline()

#break if we hit the end of the file
if not line:
    break

You can expect Python programmers to know that file.readline returns an empty string to indicate end-of-file; or if not, they can find out by running help(file.readline).

Some of the comments are wrong, for example here:

#get our first idSeq
idSeq = line.rstrip()

This only gets the "first" idSeq if there was no previous line starting with an @.
For an infinite loop, you write:

while 1:

but it's conventional to write:

while True:

In Python, a file object is also an iterator that yields the lines in the file, so instead of

line = fileH.readline()

#break if we hit the end of the file
if not line:
    break

you can write:

line = next(fileH)

This raises StopIteration when there are no more lines.
You build up the sequence string by repeated addition:

sequence = ""
while not line.startswith('+'):
    sequence += line.rstrip().replace(' ', '')
    line = fileH.readline()

In Python this is an anti-pattern that results in quadratic space and time consumption. The efficient way to build up a string from components is to put the components in a list and then call str.join:

sequence_lines = []
while not line.startswith('+'):
    sequence_lines.append(line.rstrip().replace(' ', ''))
    line = fileH.readline()
sequence = ''.join(sequence_lines)

You build up the score in the form of a list rather than a string:

score = []
while 1:
    score += line.rstrip().replace(' ', '')
    ...

which means that your results come out like this:

('@ID', 'GATTTGGG', ['!', "'", "'", '*', '(', '(', '(', '('])

Is that really what you want? I would have expected score to come out as a string, like this:

('ID', 'GATTTGGG', "!''*((((")

3. Revised code

Here's some revised code that fixes the problems above, and is much more robust in its detection and reporting of errors in the input.

class Error(Exception):
    pass

class Line(str):
    """A line of text with associated filename and line number."""
    def error(self, message):
        """Return an error relating to this line."""
        return Error("{0}({1}): {2}\n{3}"
                     .format(self.filename, self.lineno, message, self))

class Lines(object):
    """Lines(filename, iterator) wraps 'iterator' so that it yields Line
    objects, with line numbers starting from 1. 'filename' is used in
    error messages.

    """
    def __init__(self, filename, iterator):
        self.filename = filename
        self.lines = enumerate(iterator, start=1)

    def __iter__(self):
        return self

    def __next__(self):
        lineno, s = next(self.lines)
        line = Line(s)
        line.filename = self.filename
        line.lineno = lineno
        return line

    # For compatibility with Python 2.
    next = __next__

def read_fastq(filename, iterator):
    """Read FASTQ data from 'iterator' (which may be a file object or any
    other iterator that yields strings) and generate tuples (sequence
    name, sequence data, quality data). 'filename' is used in error
    messages.

    """
    # This implementation follows the FASTQ specification given here:
    # <http://nar.oxfordjournals.org/content/38/6/1767.full>
    import re
    at_seqname_re = re.compile(r'@(.+)$')
    sequence_re = re.compile(r'[!-*,-~]*$')
    plus_seqname_re = re.compile(r'\+(.*)$')
    quality_re = re.compile(r'[!-~]*$')

    lines = Lines(filename, iterator)
    for line in lines:
        # First line of block is @<seqname>.
        m = at_seqname_re.match(line)
        if not m:
            raise line.error("Expected @<seqname> but found:")
        seqname = m.group(1)
        try:
            # One or more lines of sequence data.
            sequence = []
            for line in lines:
                m = sequence_re.match(line)
                if not m:
                    break
                sequence.append(m.group(0))
            if not sequence:
                raise line.error("Expected <sequence> but found:")

            # The line following the sequence data consists of a plus
            # sign and an optional sequence name (if supplied, it must
            # match the sequence name from the start of the block).
            m = plus_seqname_re.match(line)
            if not m:
                raise line.error("Expected +[<seqname>] but found:")
            if m.group(1) not in ['', seqname]:
                raise line.error("Expected +{} but found:".format(seqname))

            # One or more lines of quality data, containing the same
            # number of characters as the sequence data.
            quality = []
            n = sum(map(len, sequence))
            while n > 0:
                line = next(lines)
                m = quality_re.match(line)
                if not m:
                    raise line.error("Expected <quality> but found:")
                n -= len(m.group(0))
                if n < 0:
                    raise line.error("<quality> is longer than <sequence>:")
                quality.append(m.group(0))

            yield seqname, ''.join(sequence), ''.join(quality)

        except StopIteration:
            raise line.error("End of input before sequence was complete:")


When the server does not exists it seems node throws an EIO error.

Now you need to make a decision, you can either reject the promise or resolve with false. From an usage point of view I would say I would prefer to resolve it false unless I need to know why the server is unavailable.

I am assuming that you just want to know if it is available or not, thus it doesn't make sense to reject the promise ever.

Your module also doesn't support Urls, in the form of

  scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]

In order to support that you must parse the parameter with the existing URL module.

In order to support both the URL and the URN you can check if the protocol was specified

var http = require('http');
var url = require("url");
var Promise = require('promise');

module.exports = function (uri) {
  var address = url.parse(uri);
  var parts = uri.split('/');
  var options = {
    host: address.protocol != null ? address.host : parts[0],
    method: 'HEAD',
    path: address.protocol != null ? address.pathname : parts.slice(1).join('/')
  };
  var req = http.request(options);
  req.end();
  var promise = new Promise(function (resolve, reject) {
    var connected = false;
    req.on('response', function (res) {
      connected = res.statusCode < 500;
      resolve(connected);
    });

    req.on('error', function (err) {
      resolve(false);
    });
  });
  return promise;
};

module.exports("http://httpstat.us/200").then(function(isAvailable){
    console.log(isAvailable);
});


Bubble Sort has an inefficient worst case.  In general, you could speed things up by switching from this \$O(n^2)\$ sort to one of the \$O(n \log n)\$ sorts, e.g. Quicksort.  Simplest would be to just use Arrays.sort but perhaps this is a programming exercise (tagging as reinventing-the-wheel would let reviewers know that).

        for(int i = 0; i < array.length - 1; i++){
            for(int j = 0; j < array.length - i - 1; j++){

                if(array[j] < array[j + 1]){
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }

The one thing that Bubble Sort can do well is handle sorted input efficiently in \$O(n)\$ time.  But you don't do that.

        for (int i = 0; i < array.length - 1; i++) {
            boolean bubbled = false;
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] < array[j + 1]){
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                    bubbled = true;
                }
            }

            if (!bubbled) {
                return;
            }
        }

Now it will return after a single pass if the input is sorted.  If the input is almost sorted, it may return on the second or third pass.

You can save a calculation an outer loop iteration if you're really trying to optimize.

        for (int i = array.length - 1; i > 0; i--) {
            boolean bubbled = false;
            for (int j = 0; j < i; j++) {
                if (array[j] < array[j + 1]){
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                    bubbled = true;
                }
            }

            if (!bubbled) {
                return;
            }
        }

Now you don't have to calculate array.length - 1 - i on every outer iteration.

Note that a naive compiler might actually calculate that on each inner iteration in the original code.


Can I make a regex array to iterate through in C++?

Probably like this:

C++11:

vector< pair<regex, string> > regex_pairs = { {regex(".."), "($1/$2)"}, {regex(".."), "($1)"}, {regex(".."), "($2)"} };
for(auto pa:regex_pairs){
    cout << regex_replace(string, pa.first, pa.second);
}

C++03:

vector< pair<regex, string> > regex_pairs;
regex_pairs.push_back(make_pair(regex(".."), "($1/$2)"));
regex_pairs.push_back(make_pair(regex(".."), "($1)"));
regex_pairs.push_back(make_pair(regex(".."), "($2)"));
for(vector< pair<regex, string> >::iterator it = regex_pairs.begin();it!=regex_pairs.end(); it++){
    cout << regex_replace(string, it->first, it->second);
}


Sieve of eratosthenes: My optimized version

Built-in functions
As mentioned by Marc, Since Python 3.8 you can use math.isqrt.  This is faster.  It is also guaranteed to be accurate when the size of the argument exceeds the number of bits of mantissa in a float.
Type coercion
sieve_arr = array('i', [True for _ in range(n+1)])

Your array is declared to hold 'i' values: integers.  But you are trying to storing boolean values in the array.  This necessitates an unnecessary conversion from True and False to 1 and 0.
Underused variable
The value sieve_arr_length is used once.  It effectively holds n + 1.
In fact, sieve_arr_length = n + 1 might be a more efficient way to initialize it, rather than asking the array for its length.  Then instead of recomputing n+1 each time the j loop starts, you could simply use sieve_arr_length.
Special case even numbers
Every even number greater than 2 is not prime.  There is no need to check for these.  You could simply start your i loop at 3, instead of 2, and go up by twos to check only the odd numbers greater than 1.
Starting the j loop at i+i, or i*2 is an optimization, but not enough of one.  By the time you're checking 13, you've already eliminated 3*13, 5*13, 7*13, and 11*13 because you've eliminated multiples of smaller primes.  You can simply start at i*i.
Plus, if you're only checking the odd prime candidates (because you've special-cased the even), you don't need to eliminate 14*13, 16*13, 18*13 and so on, because those are guaranteed to be even. Your step size can be 2*i, and eliminate half of the redundant assignments.
    # Odd prime candidate sieve ...
    for i in range(3, isqrt(sieve_arr_length) + 1, 2):
        if sieve_arr[i]:
            for j in range(i * i, sieve_arr_length, 2 * i):
                sieve_arr[j] = 0;

Memory
The array('i', ...) uses 4 or 8 (depending on architecture) bytes per element in the array.  RootTwo's solution uses a list structure, instead of the array.  This will increase the amount of storage required for the sieve, since a list must store a pointer in each list element.
Using a bytearray instead of an array('i', ...) would reduce your memory usage, down to 1 byte per sieve element, allowing you to maintain a larger sieve.
def ajneufeld_bytearray(n=80):
    """Sieve of Erathosthenes"""

    prime = bytearray((0, 1)) * ((n + 1) // 2)
    prime[1] = 0
    prime[2] = 1
    for i in range(3, isqrt(n) + 1, 2):
        if prime[i]:
            prime[i*i::2*i] = bytes(len(range(i*i, n, 2*i)))

    return prime

You can further pack 8 flags into each byte, dramatically decreasing the size of your sieve even further, but this bit packing would be complex to implement yourself.  Fortunately it has already been done as a nice package: bitarray.
bitarray implementation
The bitarray package has nice bitslice assignment operators.  RootTwo's slice assignment:
sieve_arr[i*i::i] = [False]*len(range(i*i, len(sieve_arr), i))

is much easier with bitarray.  The equivalent statement would be:
sieve_arr[i*i::i] = False

assigning False to each bit in the slice.
from bitarray import bitarray
from math import isqrt

def ajneufeld(n=80):
    """Sieve of Erathosthenes"""

    prime = bitarray(n)
    prime.setall(False)
    prime[3::2] = True

    prime[2] = True
    for candidate in range(3, isqrt(n) + 1, 2):
        if prime[candidate]:
            prime[candidate*candidate::2*candidate] = False

    return prime

Test code:
import matplotlib.pyplot as plt
from timeit import timeit
from sys import getsizeof

if __name__ == '__main__':

    candidates = (theprogrammer, roottwo, ajneufeld_bytearray, ajneufeld_bitarray)
    limits = [10, 30, 100, 300, 1000, 3000, 10_000, 30_000, 100_000, 300_000]

    print("Memory usage:")
    for candidate in candidates:
        result = candidate(100_000)
        print(f"  {candidate.__name__:19} {getsizeof(result):6}")

    fig, ax = plt.subplots()

    for candidate in candidates:
        times = [ timeit(lambda: candidate(limit), number=1) for limit in limits ]
        ax.plot(limits, times, '-+', label=candidate.__name__)

    ax.legend()
    plt.xscale('log')
    plt.yscale('log')
    plt.show()

Output:

Memory usage:
  theprogrammer       400068
  roottwo             800056
  ajneufeld_bytearray 100057
  ajneufeld_bitarray   12564


You can easily find the next death-index with the modulus operation: next = (current + space) % totalStillAlive . No need for fancy loops (see end of answer).
Instead of making an array of arrays (btw, don't create js arrays with new Array, use the array literal []), simply store an array of original indexes, and splice from that on each around until there are no more people left.
The way you're extracting the data is awkward, specifically the spacer definition - why not define it right off the bat as parseInt(...) - 1 ?
It's probably not very important with this input size, but the synchronous line reading is frowned upon; you should use the asynchronous versions unless there's a reason not to.
if (line != "") can just be if (line)
With #1 you don't need regroup, but your forEach loop is an implementation filter (docs)

(as a continuation of #2:

var person = [];
person = new Array(i.toString(), 1);

I don't get what went through your mind at the time, but why not just people[i] = [i, 1] ?)

So, your main algorithm can be simplified to 1 nice loop instead of 3 (discounting the instantiation loop):

function josephus (n, interval) {
    var people = [],
        deaths = [];
    for (var i = 0; i < n; i += 1) {
        people[i] = i;
    }

    var idx = 0,
        len = people.length;
    while (len = people.length) {
        idx = (idx + interval) % len;
        deaths.push(people[idx]);
        people.splice(idx, 1);
    }

    return deaths;
}


Deleting everything between two quotes in a string

C++ is very picky about types.
You should always try and use the correct ones:

unsigned int firstQuotePos = logFileName.find_first_of(L"\"");
unsigned int secondQuotePos = logFileName.find_first_of(L"\"", firstQuotePos + 1);

should be:

std::string::size_type firstQuotePos  = logFileName.find_first_of(L"\"");
std::string::size_type secondQuotePos = logFileName.find_first_of(L"\"", firstQuotePos + 1);

Next there is already an erase that does this:

if (firstQuotePos != std::string::npos)
{
    logFileName.erase(firstQuotePos, (secondQuotePos - firstQuotePos));
}


In terms of making more robust, a fairly obvious improvement would be to ensure that argv[1] exists before using it (that's what argc is for).  If there's no argument, or the file can't be read, emit a useful error message to std::cerr and return EXIT_FAILURE - negative return values from main() can vary by platform.

Why do we declare CannyThreshold with two arguments, but never use them?  Just declare it taking no arguments.

Your description mentions saving the result, but I don't see any code for that - did you perhaps show us the wrong version of the program?


Metalsmith plugin for stripping UTF8 BOM from files

As @konijn said in the comments, it looks pretty OK, though I do have some comments. I don't know anything about Metalsmith specifically, so it'll just be more general JS/Node comments.

Firstly, it looks like you're doing two different things here:

Stripping the BOM, of course, which is indeed what the function claims to do
Parsing some the file, and extracting some attributes.

I don't know the exact structure of the input for this function, but each "file" object seems to contain a contents buffer. Question is whether it also contains other attributes already, or if they only get added by this function.

If it's the latter, then the plugin is really two things, which doesn't smell quite right. I'd probably break it into two plugins: Strip the BOM somewhere, then parse the attributes somewhere else. I imagine you need to strip the BOM before anything else, but beyond that, those two operations sound independent to me.

I can see the appeal of keeping it in the same place though, since splitting it up requires and extra toString and buffer replacement per file. But the overhead is, I'd wager, completely negligible.

The alternative would be to call the plugin something like utf8SafeParsing (or something like that), just to indicate that its main function is to parse - compared to that, the BOM-stripping seems like a minor thing.

Besides that I can only think minor improvements.

Firstly, there are konijn's two observations: A comment about why this plugin is used (why the BOM is a problem, and/or where it comes from), and the call to setImmediate(done) before actually being done. The latter probably works just fine as there's nothing asynchronous going on in the function, but nevertheless seems odd to call it before doing anything.
I always lobby for using brace-on-same-line style in JavaScript, only because putting the brace after a linebreak can in some (uncommon) circumstances cause JS auto-insert a semicolon at the linebreak, causing all sorts of confusion. In other words, while whitespace shouldn't matter, it kinda sorta does, and the interpreter kinda sorta assumes that you're using brace-on-same-line, and will attempt to "fix" your code otherwise.
You can move your require calls into the function itself, to keep things neat and tidy (requires are cached, so there's no performance hit).
If you keep it as one function, you could add a little helper function or two for yourself. No difference in logic, just structure.
Super trivial thing; I'd name the function stripBOM rather than mix-case the acronym. If the named started with "BOM", then it should be lowercase, but acronyms in JS names are typically kept uppercase (e.g. innerHTML in browsers). But again, this nit-picking in extenso.

Again, though, the code seems quite fine as-is. It's readable, and if you say it works, then great.

Here are some refactoring attempts with really, really minor changes.

2 plugin solution:

// **snip**

.use(function stripUTF8BOM(files, metalsmith, done) {
    var stripBOM = require('strip-bom');

    Object.keys(files).forEach(function (file) {
        var data = files[file],
            parsed = stripBOM(data.contents.toString());

        files[file].contents = new Buffer(parsed.body);
    });

    setImmediate(done);  // or, presumably, just call `done();` directly
})
.use(function parseAttributes(files, metalsmith, done) {
    var front = require('front-matter'),
        extend = require('extend');

    Object.keys(files).forEach(function (file) {
        var data = files[file],
            parsed = front(data.contents.toString());

        files[file] = extend({}, parsed.attributes, {
          contents = new Buffer(parsed.body);
        });
    });

    setImmediate(done); // or, presumably, just call `done();` directly
})

Single plugin solution:

// **snip**

.use(function utf8SafeParsing(files, metalsmith, done) {
    var stripBOM = require('strip-bom'),
        front = require('front-matter'),
        extend = require('extend');

    function parse(buffer) {
      var sanitized = stripBOM(buffer.toString());
      return front(sanitized);
    }

    Object.keys(files).forEach(function (file) {
        var parsed = parse(files[file].contents);

        files[file] = extend({}, parsed.attributes, {
          contents = new Buffer(parsed.body);
        });
    });

    setImmediate(done);  // (see above)
})


Finding common Integers between two lists

I personally would shorten this greatly:

public static int numInCommon(List<Integer> list1, List<Integer> list2){
    if(list1.isEmpty() || list2.isEmpty()){
        return 0;
    }

    Set<Integer> setCommon = new HashSet<>(list1);
    setCommon.retainAll(list2);
    return setCommon.size();
}

Returning 0 at the start is good, but no need for the else block on the If code.
Next task is to calculate the common elements - putting list1 into the set removes duplicates and then retainAll removes anything that isn't in list2. This leaves everythin in list1 and list2 without duplicates. Returning the size() counts the elements.

For performance - I'm taking the major assumption that HashSet is one of the quickest ways to check if an item exists and handle removal.


Django functions to sanitize URL, return welcome message, redirect, compute HMAC, and manage profile picture

Some comments, with security issues highlighted:

Why would you remove whitespace from URLs? It is perfectly valid for URLs to contain whitespace, unencoded or encoded as + or %20. If your backend code can't handle whitespace there are much bigger fish to fry. In general:

Blacklisting is more dangerous than whitelisting, because it's easy to omit some values.
Whitelisting parts of values (such as characters in a URL) is more dangerous than whitelisting entire values, because clever hackers often find a way to escape the sandboxing attempt by combining parts. For example, depending on how you pass values to your backend, %20 in a URL may or may not be replaced with a space character.
Blanket removal of parts of the input limits your application severely while providing very little security (because of the above). A better solution is to escape the input and test the escaping using previously insecure values. This escaping should be provided by the official libraries (such as SQL or shell escaping).
An even better solution is to let the library do the escaping for you, for example with parametric SQL queries, because now you don't need to remember to escape every value yourself, only to use parameters rather than string concatenation.

Why would you lowercase the URL? There's no security issue with uppercase characters that I've ever heard of. And again, limiting the URL space like this is a bad trade-off.
Redirecting to a URL without checking it against a strict whitelist first is a well-known security issue.
Similarly, not validating the username parameter is a massive issue - what if I specify something like u=../../etc/passwd?
Why would you implement your own HMAC generator? It's built right into the standard library, even in Python 2.
What is the purpose of the message_rendered_at cookie?
Guessing the MIME type indicates that someone could send a JavaScript, PDF or other potentially harmful file as their avatar. If this is shown to other people that could lead to remote code injection. This has already happened on many sites with Bitcoin mining scripts. At best you should instead convert all avatars to a single format (PNG is ideal for this) and serve that. If you really need some flexibility then allow a small set of well-known formats and change the file extension when saving it. Then use a dict to map file extension to MIME type.
ordenary is not an English word as far as I know. ordinary would not be a good function name either, because it gives the programmer no idea what it actually does. One thing I've found useful to determine better names for things is to use type hints and validate them using mypy with strict settings (not allowing Any type). It takes some getting used to, but doing this properly should tell you exactly what goes into and comes out of any function. A function which takes a Request to /foo and returns a Response, for example, could be a respond_to_foo_request.
Some of the imports are unused.


General Observations
There is a real lack of communications with the user of the program. There is no error checking performed on the possible input. While the code really doesn't do that much it is too complex and very hard to maintain.
Communications With the User
Unless the user knows exactly how to call the program, the program will crash with no indication of what went wrong. This is because the code uses argv[1] for input and doesn't check that argv[1] actually exists. The following code would be better for the user of the program because it check that an argv[1] actually exists first before using it and reports an error if there is no argv[1]:
    if (argc > 1)
    {
        loops = atoll(argv[1]);
    }
    else
    {
        fprintf(stderr, "USAGE MESSAGE");
        return EXIT_FAILURE;
    }

It is also unclear what is being printed in the following statement:
    printf ("%llu" "%s" "%llu"   "%s" "%0.9f" "%s" "%0.3f\n",
        i, " ", cpoints, " ", approx, " ", cpu_time_used);

It might be better if the the previous statement was something like this:
    printf ("i = %llu cpoints = %llu approx = %0.9f cpu_time_used = %0.3f\n",
        i, cpoints, approx, cpu_time_used);

Note: Use the formatting capabilities of the printf statement rather than using "%s" to print spaces. Rather than using the variable i in the statement it would be more understandable to use the variable loops, i and loops should be the same at this point.
Declare and Initialize the Variables as Needed
C is not the nicest language to program in because there is no default value assigned to local variables so it is always best to initialize the variable when it is declared, each variable should be declared and initialized on its own line to make the code easier to read, write, maintain and debug.
    unsigned long long loops = 0;
    unsigned long long cpoints = 0;
    unsigned long long i = 0;

If the variable loops is used for the calculations and printing then the variable i can actually be declared in the for loop.
    for (unsigned long long i = 0; i < loops; ++i)
    {
        double x = (rand() + 1.0) / (RAND_MAX+2.0);
        double y = (rand() + 1.0) / (RAND_MAX+2.0);
        if ( incircle(x,y) !=FALSE )
            cpoints+=1;
    }

Unnecessary Code
Since stdbool.h is included the #defines for TRUE and FALSE are unnecessary because stdbool.h defines true and false. In the if statement where FALSE is used you have a double negative, which is as bad in programming as it is in English. The if statement can be simplified to
        if (incircle(x,y))
            cpoints += 1;

Code Complexity
##Complexity
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

The main() function can be broken up into the following functions

Get the user input from the command line and report any errors
Set up the random number generator.
The loop that is currently doing the calculations should be in its own function.

Compiler Warnings
Make sure you enable the compiler warnings when you compile some of the casts in the code are questionable and my compiler is reporting warnings. It might be best to compile with the -wall switch (enable all warnings).


When you call gettimeofday it gives you the number of seconds since EPOCH too, so you don't need to call time again. And when you use output of localtime as input of strftime, you may omit the intermediate variable (not a very useful point though). So your code could be written like:

timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;

char buffer [80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));

char currentTime[84] = "";
sprintf(currentTime, "%s:%03d", buffer, milli);
printf("current time: %s \n", currentTime);

an important note to be considered is that functions like localtime are not thread-safe, and you'd better use localtime_r instead.


Are there any suggestions regarding readability and variable names?

You should follow PEP8, the official Python coding style guide.
For example:

Put spaces around operators. Instead of var%3==0, write as var % 3 == 0
Put spaces after commas separating parameters. Instead of Board(fBoard,99,None), write as Board(fBoard, 99, None)
Use snake_case for naming variables and methods instead of camelCase
Use PascalCase for naming classes

What is an fBoard? It's not easy to guess, so that's not a good name.

Don't execute code in global scope

These lines are executed immediately when the script is imported,
which is not good:

n=3
fBoard = [1,2,3,
          4,5,6,
          7,8,0]

board = [i for i in range(9)]
shuffle(board)

print(board)
aStar()

It would be better to move them into a main function,
and call that function from a if __name__ == '__main__' guard, like this:

def main():
    n=3
    fBoard = [1,2,3,
              4,5,6,
              7,8,0]

    board = [i for i in range(9)]
    shuffle(board)

    print(board)
    aStar()

if __name__ == '__main__':
    main()

This will make your script more reusable, and it will help you avoid some obscure bugs that can happen by variable shadowing.

Get ready for Python 3

It's not too difficult to make this script work with Python 3 too.
All it takes is adapting your print statements a little bit.
In some cases it's as trivial as adding (...), for example:

print "\n"

Rewrite as:

print("\n")

When you don't want the automatic newline, for example here:

print "\n",self._array[var],",",

You can add the end='' parameter:

print("\n",self._array[var],",", end='')


Reading a certain number of lines from a file

That implementation is very procedural.  getLines() returns an Iterator, which supports a take(n) method.

def getLinesFromFile(file:File, linesToGet:Int): List[String] = {
  val bufferedSource = Source.fromFile(file)
  try {
    bufferedSource.getLines.take(linesToGet).toList
  } finally {
    bufferedSource.close
  }
}


Reducing allocations in arbitrary precision calculations with Julia

The following is a workaround for your speed and memory issue rather than a general review of your code.
Profiling is useful for investigating the source of performance issues, and Julia's standard library includes a profiling module (guide, doc).
Here's a basic use of it: (I'm using @eval just to interpolate in the construction of M)
using Profile
@eval @profile Hmn(12, 2, $(construct_M(192, 192)), 64)

julia> Profile.print()
Overhead ╎ [+additional indent] Count File:Line; Function
=========================================================
    ╎963  @Base/task.jl:356; (::IJulia.var"#15#18")()
...
    ╎    ╎   963  In[1]:61; Hmn(::Int64, ::Int64, ::Arr...
    ╎    ╎    1    In[1]:4; gamma_mpnq(::Int64, ::Int6...
...
  18╎    ╎    962  In[1]:46; maclaurin_exp(::Int64, ::I...
   1╎    ╎     1    In[1]:0; general_binomial(::Float6...
    ╎    ╎     14   In[1]:11; general_binomial(::Float6...
...
    ╎    ╎     786  In[1]:13; general_binomial(::Float6...
...
    ╎    ╎     97   In[1]:15; general_binomial(::Float6...
...

I've removed all the lines that point to code in external files. Of the 963 samples collected in Hmn, more than 800 were spent within calculations of general_binomial.
Looking at how general_binomial(alpha, k) is used, I noticed that it is called repeated with only a small number of different alpha and k values. Since it is a pure function (i.e., it does not interact with external state), basic memoization can be applied to speed it up.
We can use a Dict to cache the results (make sure it is defined with concrete key and value types). To allow for easy benchmarking, we'll define it as a global constant; for performance, it is important that global variables are constant (or otherwise type-constrained in code using it) so that type inference works (also, the compiled code can avoid an extra lookup).
Here's a simple way to do this. Rename general_binomial to _general_binomial, then create the Dict and redefine general_binomial to cache the results. Like so:
@isdefined(general_binomial) && Base.delete_method.(methods(general_binomial))

const GENERAL_BINOMIAL_CACHE = Dict{Tuple{Float64, Int}, BigFloat}()

function general_binomial(alpha, k)
    return get!(GENERAL_BINOMIAL_CACHE, (alpha, k)) do
        _general_binomial(alpha, k)
    end
end

Benchmarking shows a substantial improvement in speed and memory use using the parameters you provided.
Before:
julia> @benchmark Hmn(12, 2, $(construct_M(192, 192)), 64)
BenchmarkTools.Trial:
  memory estimate:  435.29 MiB
  allocs estimate:  8543119
  --------------
  minimum time:     787.497 ms (5.88% GC)
  median time:      791.734 ms (5.83% GC)
  mean time:        792.690 ms (5.76% GC)
  maximum time:     802.070 ms (5.17% GC)
  --------------
  samples:          7
  evals/sample:     1

After: (the cache is cleared before each sample by empty!(GENERAL_BINOMIAL_CACHE))
julia> @benchmark Hmn(12, 2, $(construct_M(192, 192)), 64) evals=1 setup=empty!(GENERAL_BINOMIAL_CACHE)
BenchmarkTools.Trial:
  memory estimate:  12.74 MiB
  allocs estimate:  239309
  --------------
  minimum time:     10.684 ms (0.00% GC)
  median time:      12.844 ms (0.00% GC)
  mean time:        14.181 ms (7.58% GC)
  maximum time:     32.631 ms (14.03% GC)
  --------------
  samples:          353
  evals/sample:     1


data = json.load(open("vocabulary.json"))

Unless Python 3 has changed this, I think you're leaking the open file handle here. What you want is more like

with open("vocabulary.json") as f:
    data = json.load(f)

which IMHO is even a bit easier to read because it breaks up the mass of nested parentheses.

vocab = random.choice(list(data.keys())).lower()

Same deal with the nested parentheses here. We can save one pair by eliminating the unnecessary materialization into a list. [EDIT: Graipher points out that my suggestion works only in Python 2. Oops!]

Also, vocab (short for vocabulary, a set of words) isn't really what this variable represents. data.keys() is our vocabulary; what we're computing on this particular line is a single vocabulary word. So:

word = random.choice(data.keys()).lower()
print(word)
print(hangman_game(word))

I can tell you're using Python 3 because of the ugly parentheses on these prints. ;) But what's this? Function hangman_game doesn't contain any return statements! So it basically returns None. Why would we want to print None to the screen? We shouldn't be printing the result of hangman_game; we should just call it and discard the None result.

word = random.choice(data.keys()).lower()
print(word)
hangman_game(word)

def hangman_game(vocab):

Same comment about vocab versus word here.

'Preliminary Conditions'

This looks like you maybe forgot a print? Or maybe you're trying to make a docstring? But single quotes don't make a docstring AFAIK, and even if they did, "Preliminary Conditions" is not a useful comment. I'd just delete this useless line.

print(introductory(vocab=vocab))

In all of these function calls, you don't need to write the argument's name twice. It's a very common convention that if you're calling a function with only one argument, the argument you pass it is precisely the argument it needs. ;) Also, even if the function takes multiple parameters, the reader will generally expect that you pass it the right number of arguments in the right order. You don't have to keyword-argument-ize each one of them unless you're doing something tricky that needs calling out. So:

print(introductory(word))

And then you can inline introductory since it's only ever used in this one place and it's a one-liner already:

print(
    "HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. "
    "WORD COUNT : " + str(len(vocab))
)

Personally, I would avoid stringifying and string-concatenation in Python, and write simply

print(
    "HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. "
    "WORD COUNT : %d" % len(vocab)
)

I know plenty of working programmers who would write

print(
    "HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. "
    "WORD COUNT : {}".format(len(vocab))
)

instead. (I find that version needlessly verbose, but it's definitely a popular alternative.)

tries = num_of_tries(vocab=vocab)
blank_line = produce_blank_lines(vocab=vocab)
print(blank_line)
print(guessing(tries=tries,vocab=vocab,blank_line=blank_line))

It's odd that you abbreviated number_of_tries to num_..., but then left in the word of. I would expect either number_of_tries or num_tries (or ntries for the C programmers in the audience); num_of_tries is in a weird no-man's-land.

It's weird that you have a function named produce_blank_lines that produces actually a single blank_line. It's even weirder that the value of blank_line is not a constant "\n"! This suggests that everything here is misnamed. You probably meant underscores = produce_underscores(word) or even blanks = shape_of(word).

Finally, it is weird that blank_line is not even a string, but rather a list of characters.

I would replace this entire dance with something like

blanks = ''.join('_' if c.isalpha() else ch for ch in word)

or

blanks = re.sub('[A-Za-z]', '_', word)

This would lose your addition of a blank space after each non-space-non-alpha character, but IMHO that's actually an improvement over your version. (Your sample JSON doesn't show any examples of words containing non-space-non-alpha characters. My version certainly performs better for words like non-space or Route 66.)

if not(user_input in blank_line):

This would be idiomatically expressed (both in Python and in English) as

if user_input not in blank_line:

index = find_letter(user_input=user_input,vocab=vocab)
i = 0
while i < len(index):
    blank_line[index[i]] = user_input
    i += 1

You have another singular/plural problem here (just like with blank_line[s]). It doesn't make sense to get the len of a singular index. Since the variable actually represents a list of indices, we should name it [list_of_]indices.

Also, this style of for-loop is very un-Pythonic. In Python we can say simply

for i in find_letter(user_input, word):
    blank_line[i] = user_input

And then we can inline the single-use find_letter:

for m in re.finditer(user_input, word):
    blank_line[m.start()] = user_input

(Using m as the conventional name for a match object.)
And then we can eliminate the regex and just loop over the word directly:

for i, ch in enumerate(word):
    if ch == user_input:
        blank_line[i] = user_input

or

for i in range(len(word)):
    if word[i] == user_input:
        blank_line[i] = user_input

In fact, by not using regexes, we fix a bug in your code: if the chosen vocabulary word contains . as one of its non-space-non-alpha characters, a user who enters . as their guess will win the game immediately! :D

Anyway, that's enough for one answer, I think.