The small things

    s <- get
    let candidates = fst s
    let visited = snd s

could be simplified to

    (candidates, visited) <- get

(It is technically a little bit stricter but it's not a problem because you don't rely on laziness here.)

    let ret = blah in
    ret

is equivalent to

    blah

At the end of dfsGetNext you return either 0 or 1, which is strange because the return type is Vertex, and although it is a synonym for Int (so this type checks), 0 and 1 don't look like vertices.

My guess is that you intended either:

to return a boolean to indicate whether the DFS ended, so Bool would be a more appropriate type;
to return the visited vertex, so, rather than returning dummy sentinel values, Maybe Vertex would be a more appropriate type.

Assuming that 0 and 1 are meant to be booleans, and with the other changes above, we get:

-- Also isolating the monad, and applying it to the result type in the function instead
type DFS = ReaderT Env (StateT DFSState Identity)

dfsGetNext :: DFS Bool
dfsGetNext = do
    graph <- ask
    (candidates, visited) <- get
    case candidates of
       []     -> return False
       (x:xs) -> if elem x visited
                 then put (xs, visited) >> return True
                 else put ((getNeighbors x graph) ++ xs, visited ++ [x]) >> return True

Getting fancy

There's a more direct implementation of DFS. To do a DFS starting from a vertex v:

If v has already been visited, stop; otherwise...
Visit v
Recursively run a DFS from each neighbor of v

In particular, this description doesn't require you to explicitly keep track of "pending candidate vertices", nor to iterate a "single step" function like dfsGetNext; the DFS is directly defined.

-- The state now only contains the visited vertices, not the candidates (which is implicit in the recursive structure of dfsFrom)
type DFS = ReaderT Graph (State Visited)

dfsFrom :: Vertex -> DFS ()
dfsFrom v = do
  visited <- get
  if v `elem` visited then                     -- 1
    pure ()
  else do
    put (visited ++ [v])                       -- 2
    graph <- ask
    let neighbors = getNeighbors v graph
    for_ neighbors dfsFrom                     -- 3

Now you can "run" that DFS, interpreting it as a function as follows:

-- dfs from 0
dfs :: Graph -> [Vertex]
dfs graph = dfsFrom 0 `runReaderT` graph `execState` []

Your "single step" version does have one distinguishing feature, which is that you can easily interrupt the DFS at any time to inspect the state for example. But you can also do that with the recursive version, by passing a function (visit below) that will be called when visiting a node. Clients of the DFS are free to define it however they wish.

It's also useful to generalize the DFS monad to support additional effects relevant to users rather than to the DFS itself. This is straightforward since you're already using monad transformers, by changing the base monad from Identity to something else. Here I chose IO for simplicity and concreteness, but it might as well be a type parameter m.

type DFSIO = ReaderT Graph (StateT Visited IO)

dfsFromIO :: (Vertex -> DFSIO ()) -> Vertex -> DFSIO ()
dfsFromIO visit v = do
  visited <- get
  if v `elem` visited then
    pure ()
  else do
    visit v
    put (visited ++ [v])
    graph <- ask
    let neighbors = getNeighbors v graph
    for_ neighbors (dfsFromIO visit)

Another possibility is to call visit at the very start of the function, before checking whether the vertex was visited, or at the very end, on the neighboring vertices, where the function could also have access to the cost of the edges being crossed.

Running this new version dfsFromIO is as straightforward as running dfsFrom (only replacing execState with execStateT since the base monad is no longer Identity):

-- dfs from 0
dfsIO :: (Vertex -> DFSIO ()) -> Graph -> IO [Vertex]
dfsIO visit graph = dfsFromIO visit 0 `runReaderT` graph `execStateT` []

For example you can print every visited vertex as follows:

main :: IO ()
main = void (dfsIO (\v -> liftIO (print v)))

Full gist: https://gist.github.com/Lysxia/4733f8d670c84e5b886f74d2d106d1f5


Constructing objects for external libraries using a model in Laravel

I would implement this as a service in Laravel, and use IOC to resolve my dependencies.

I would make a service, called AdWordsCampaign. This would resolve its dependencies in constructor, namely OAuth2TokenBuilder and AdWordsSessionBuilder, although these two classes are good candidates for services themselves (a factory pattern is most of times is a sign you should abstract creation of class into a service provider).

Then I would implement a method in this service, adWordsSession which takes two parameters: a User instance and $customer_id. Then it has everything it needs to to its job.

I would also implement the reverse case using a service. Semantics are the same.

As for static method, I would avoid them. If you like them, use a Facade. They enable you to use a service anywhere you want.

I strongly suggest to read Laravel docs about services and providers and IOC and Facades. It will give you enough insight about how they work, and where to use them.

As a rule of thumb, whenever you see yourself using new * in your codes, it seems your could use a service/provider and inject it.


Some remarks:

You have repetitive code eg:

if (empty($_POST["username"])) {

You might as well define an array of fields to check and run validation in a loop.
Although you have only 3 items here...

There is a major flaw: you are not sanitizing the input fields:

$stmt->bind_param("s", $_POST['username']);

At a minimum you should trim the text because it may contains whitespace (before and after). So if user 'admin' is already taken, I can register as 'admin ' for example (one space). That is not necessarily a direct vulnerability, it depends on the rest of the code, but you have inconsistent data and this will likely cause problems later. Usernames should not contain whitespace leading or trailing whitespace. Because you can have two different accounts the all look the same in print and on screen. That makes impersonation easy.

What you should do is assign the POST fields to variables, and then use variables in the rest of the code, after checking them and sanitizing them. Do not reuse $_POST['whatever'] all across your code.

You should also test what happens if the HTTP request is tainted, for example if
$_POST['username'] is included twice in the POST request. Or if the field contains multiline input (or null characters). How will your code react ? Do you have error handling and logging ?

I note that you are not checking the length of input fields, including the password. What happens if the text is very large, larger than the corresponding table field ?

You should have a sensible password policy and not accept any password like 1234 or same as the username...

What you are showing is the registration form, but what would be interesting to see is the login page. That's the thing that should not be easy to trick or bypass.

If you use a modern development framework you can simplify your life, and your code will very probably be more secure.

In my opinion a page that does not have error handling is not secure, because you are not seeing what's going on and the code could also behave unpredictably.

Conclusion:

  If I launched this on the web would you feel safe signing up with
  personal info ?

No. There are simply not enough checks. The code is not robust. You should test it in adverse conditions. Try automated tools like SQLmap, Nikto and simulate an attack against yourself.

It is good that you are using parameterized queries, that's the least you could do in 2020. But that does not mean user input does not have to be checked and sanitized. You may be opening your site to other vulnerabilities. What is pretty much guaranteed is that users will use very weak passwords since you are accepting anything. Therefore many accounts will be susceptible to brute force attacks. And you will be blamed for facilitating a breach of personal data.


Check out how Django apps work:

Plugins are genuine Python packages, so the standard tools can be used to install them
Plugins that are actually used must be in the PYTHONPATH and listed (only the package name) in the configuration.
There are scripts to help create, test, ... plugins
The plugin structure is extensible in all possible ways.
Plugins are reloaded when they change in development mode.

I'm not saying that you should use Django if you're not doing web development, but you can inspire your plugin system on it.


The simplest way to avoid the recursive traversal is to have two lists: nodes you want to visit and nodes you have visited. Your loop then goes like this:

take a node from the 'to visit' list, or end if empty
check the node
add any connected nodes that aren't in the 'visited' list to the 'to visit' list


Small bash script to enhance virtual environments on directory navigation

No shebang
It doesn't make sense to execute this as a program - it's intended to be sourced into an interactive shell.  So we shouldn't have the #! line.
Quote expansions
$1 could expand into multiple words here:
    if [ -d ~/projects/$1 ]; then
        cd ~/projects/$1;

and here:
    if [ $1 == "-"] || [ -d $1 ]; then

Send errors to stderr
    echo "Directory $1 does not exist!" >&2
    #                                   ^^^ IMPORTANT

Don't ask questions when used non-interactively
funcCheckVirtualEnvironment can misbehave when standard input is not a terminal.  We should test that case and return early:
test -r "venv/bin/activate" || return 0;
if ! test -t 0
then echo "Warning: not activating virtual environment" >&2
     return 0   # or 1 if this should be a failure
fi
read -p "Execute this project's activation script? [y/N]" -n 1 -r; echo
[[ REPLY =~ [Yy] ]] || return 0;

I've transformed some of the other if and else above into early returns, to reduce the nesting depth - I find that easier to read.  Also, I've capitalised N in the prompt, to provide the usual indication of the default.  And we know that $REPLY is a single character, so we can lose the anchors.
Let cd do its own checking instead
There's a possible race between checking for the existence of a directory and actually changing into it, so it's easier and safer to simply check whether cd succeeded:
command cd "$@" && test -d 'venv' && funcCheckVirtualEnvironment

This also allows cd to produce the error message (in the user's preferred $LANGuage).
Consider the exit status of the command
If we cd but there's no venv directory at the destination, that should be considered a success:
command cd "$@" || return $?
if test -d "venv"
then funcCheckVirtualEnvironment
else true
fi

Actually, there's no need to check for the existence of venv/, given that funcCheckVirtualEnvironment does that itself, and should succeed if it's not present:
command cd "$@" && funcCheckVirtualEnvironment

Similarly, in cdp -r, instead of return 0, a plain return is better, as that will result in the return value of the last executed command (funcCheckVirtualEnvironment in this case).
Use standard directory completion
It's bad practice to parse the output of ls.  Instead, we can ask compgen to give us directory names; we can eliminate absolute paths and subdirectories by excluding anything containing /:
_cdp()
{
        COMPREPLY=( $(cd ~/projects && compgen -X '*/*' -d $2) )
}

My version
funcCheckVirtualEnvironment()
{
    test -r 'venv/bin/activate' || return 0;
    if ! test -t 0
    then
        # Not a terminal - don't ask questions
        echo "Warning: not activating virtual environment" >&2
        return 0   # or 1 if this should be a failure
    fi

    read -p "Execute this project's activation script? [y/N]" -n 1 -r; echo
    [[ REPLY =~ [Yy] ]] || return 0;
    source venv/bin/activate || return $?

    test -e 'requirements.txt' || return 0;
    read -p "Install any missing PyPi packages? [y/N]" -n 1 -r; echo
    [[ REPLY =~ [Yy] ]] || return 0;
    pip install -r requirements.txt
}

funcCDP()
{
    # Add more flags in future, maybe
    case "$1" in
    "-r" )
        funcCheckVirtualEnvironment
        return
        ;;
    esac

    cd ~/projects/"$1" && funcCheckVirtualEnvironment
}

funcCD()
{
    command cd "$@" && funcCheckVirtualEnvironment
}

_cdp()
{
    COMPREPLY=( $(cd ~/projects && compgen -X '*/*' -d $2) )
}
complete -F _cdp cdp
alias cdp=funcCDP
alias cd=funcCD


def computeGCD(x, y):

Just call it gcd. It's part of a computer program: you don't need to say that it computes.

    graph = {i+1:[] for i in range(n)}
    for i in originCities:
        for j in range(n):
            if i != j+1 and computeGCD(i, j+1) > g:
                graph[i].append(j+1)

This is buggy: it doesn't build the whole graph. Consider test case connectedCities(16, 1, [14], [15]): there is a path 14 -- 6 -- 15 with GCDs respectively 2 and 3.

As a matter of style, I would find the code more readable if it iterated over range(1, n+1) and didn't have to continually increment the variable.

    for i in range(len(originCities)):
        paths = find_all_paths(graph, originCities[i], destinationCities[i])
        if len(paths) > 0:
            res.append(1)
        else:
            res.append(0)

Spot the big performance problem: to determine whether any foo exists, it suffices to find one foo. You don't need to find every foo in the universe and then count them.

But just fixing that still leaves a smaller performance problem: if there are a lot of queries (i.e. if originCities and destinationCities are long) then it's quicker to do an expensive preprocessing to get an object which answers queries fast than it is to evaluate each query separately. As a big hint, in graph-theoretic terms the queries are "Are these two vertices in the same connected component?".

Note that if you really want to squeeze the asymptotic complexity (and it's not too bad for practical performance either), \$O(n \lg \lg n + q)\$ is achievable1 where \$q\$ is the number of queries.

1 Technically there's also a factor of \$\alpha(n)\$ where \$\alpha\$ is the inverse Ackermann function, but for practical purposes it's constant.


Efficiency

Nothing to worry about. It's only a linear script, there are no loops anywhere. You don't need to worry about efficiency.

Security and best-practices horrible practices

I should really have you write down this sentence 100 times on a piece of paper:

DO NOT USE THE MYSQL_* FUNCTIONS, THEY ARE DEPRECATED
DO NOT USE THE MYSQL_* FUNCTIONS, THEY ARE DEPRECATED
DO NOT USE THE MYSQL_* FUNCTIONS, THEY ARE DEPRECATED
DO NOT USE THE MYSQL_* FUNCTIONS, THEY ARE DEPRECATED
(...)

Although your SQL is technically safe, I think you can write down this sentence 2 times, and read up on what it is about:

GIVE ME PARAMETRIZED SQL OR GIVE ME DEATH
GIVE ME PARAMETRIZED SQL OR GIVE ME DEATH

There are other positive things with prepared queries / parametrized SQL than just security issues. I strongly recommend switching to prepared queries and not looking back. It's easy to miss using the mysql_real_escape_string function (and in my opinion it has an overly long function name). Switching to prepared queries helps with all these things, plus a couple of others.

There is also the fact that the mysql_* methods will be entirely removed in future versions of PHP. You are not the only one still using mysql_* methods unfortunately, and it is not the first time I'm saying this.

Start converting your code to use mysqli or PDO NOW. Nothing Else Matters! (Feel free to listen to that song while you convert your code).


Conversion functions between binary, hexadecimal and ASCII

Step 1: minor cleanup

You've defined a to_list() function, but aren't really taking advantage of it.  Instead, you're still writing things like … for i in range(0, len(chain), 8)) in functions like bin2str.  You should change to_list() into a generator.  (Then, since it is no longer returning a list, you should also rename it.  You'll end up with the same thing as the chunks() function in this Stack Overflow answer.)

chain is an odd parameter name.  It strikes me as a botched English translation from a Romance language ("chaîne", "catena", etc.).  If we want to help programmers who aren't English speakers, I suggest replacing your …2… names with _to_.

Instead of slicing off the 0b and 0x prefixes generated by the bin() and hex() functions, and zero-padding using zfill(), use str.format() to take care of both problems.

# http://stackoverflow.com/a/312464/1157100
def _chunks(str, chunk_size):
    for i in xrange(0, len(str), chunk_size):
        yield str[i:i+chunk_size]

def hex_to_bin(hex):
    return ''.join('{:08b}'.format(int(x, 16)) for x in _chunks(hex, 2))

def str_to_bin(str):
    return ''.join('{:08b}'.format(ord(c)) for c in str)

def bin_to_hex(bin):
    return ''.join('{:02x}'.format(int(b, 2)) for b in _chunks(bin, 8))

def str_to_hex(str):
    return ''.join('{:02x}'.format(ord(c)) for c in str)

def bin_to_str(bin):
    return ''.join(chr(int(b, 2)) for b in _chunks(bin, 8))

def hex_to_str(hex):
    return ''.join(chr(int(x, 16)) for x in _chunks(hex, 2))

I've rearranged the order of appearance, grouping by the target type rather than the source type, as a segue to the next step…

Step 2: decluttering the interface

Looking at the code above, you'll notice a pattern: each function just mixes-and-matches code.  There is always a decoding portion (either … for something in _chunks(input, base) or … for c in str) and an encoding portion (either ''.join('{:format}'.format(something) …) or ''.join(chr(int(something, base)) …)).

A more disturbing observation is that the complexity is exponential.  If you wanted to add octal support, for example, you would need to add str_to_oct(), oct_to_str(), bin_to_oct(), oct_to_bin(), hex_to_oct(), and oct_to_hex() — doubling the number of functions.

A better design would be to convert everything to/from a common interface.  I've chosen an iterable of ASCII values as that hub.

def _chunks(str, chunk_size):
    for i in xrange(0, len(str), chunk_size):
        yield str[i:i+chunk_size]

def from_str(str):
    for c in str:
        yield ord(c)

def to_str(ascii):
    return ''.join(chr(a) for a in ascii)

def from_bin(bin):
    for chunk in _chunks(bin, 8):
        yield int(chunk, 2)

def to_bin(ascii):
    return ''.join('{:08b}'.format(a) for a in ascii)

def from_hex(hex):
    for chunk in _chunks(hex, 2):
        yield int(chunk, 16)

def to_hex(ascii):
    return ''.join('{:02x}'.format(a) for a in ascii)

Then, instead of writing str2bin(word), you would write to_bin(from_str(word)).

You happen to be at the break-even point: either way, there are six functions.  The architecture proposed in Step 2 simplifies your library (at a slight burden to the caller).  You would see a payoff, though, if you were to add octal support — you would be adding two functions instead of six.


Confirming whether a user is registered, using Optional class in Java 8

Concerning your question about the usage of Optional: yes, this usage is correct and it roughly respects the principles of functional programming.

However, I would recommend a few changes to increase the readability of this piece of code:

1) jsonService.prepareErrorResponse("INCORRECT_DATA") appears three times: it needs to be extracted into a dedicated method.

2) The main valid return case starting with return Optional.ofNullable should also be extracted into a dedicated method.

3) The condition should also be extracted.

After this refactoring, the code will resemble something like

public Response confirmRegister2(Request request) {
  return mailTokenRepository.findByToken(request.getToken())
                            .map(mailToken -> {
    if (isTokenValid(mailToken, request)) {
      return responseForUser(mailToken).orElseGet(this::errorResponse);
    } else {
      return this.errorResponse();
    }
  }).orElseGet(this::errorResponse);
}

private boolean isTokenValid(MailToken mailToken, Request request) {
  return mailToken.getTypeToken().equals(TypeToken.REGISTER)
         && mailToken.getToken().equals(request.getToken());
}

private Response errorResponse() {
  return jsonService.prepareErrorResponse("INCORRECT_DATA");
}

private Optional<Response> responseForUser(MailToken mailToken) {
  return Optional.ofNullable(userRepository.findOne(mailToken.getUser().getId()))
                .map(user -> {
                      user.setBlock(false);
                      userRepository.save(user);
                      mailTokenRepository.delete(mailToken);
                      return jsonService.prepareResponseForUser(StatusMessage.SUCCESS,
                                                              "SUCCESS_REGISTERED", null, null, true);
                    });
}

... which is definitely more readable and easier to understand. :)


Representing a combatant's equipment using the decorator pattern

Implementation is OK, note: I will add method which adds new behaviour dynamically, for example:

public class ShieldDecorator extends EnemyDecorator {

    ...
    private String addShield() {
        return "I have a shield! ";
    }

    @Override
    public String shoutIdentity() {
        return super.shoutIdentity() + addShield();
    }
}


Ruby script on-all-nodes-run not only for teaching

First of all, take a look at the Net::SSH library. I don't have much experience with it, so I don't know whether it supports all the options you need. But if it does, using it might be more robust than using the command line utility (you wouldn't have to worry about whether ssh is installed in the place you expect (or at all) and you wouldn't have to worry about escaping the arguments).

Assuming you can't (or won't) use Net::SSH, you should at least replace /usr/bin/ssh with just ssh, so at least it still works if ssh is installed in another location in the PATH.

nodes = []
Kernel.open('|qnodes | grep -v "^ " | grep -v "^$"') do |f|
  while line = f.gets
    i = line.split(' ').first
    nodes.push(i) if EXCLUDE.select{|x| i =~ x}.empty?
  end
end

When you initialize an empty array and then append to it in a loop, that is often a good sign you want to use map and/or select instead.
line = f.gets is a bit of an anti-pattern in ruby. The IO class already has methods to iterate a file line-wise.
To find out whether none of the elements in an array meet a condition, negating any? seems more idiomatic than building an array with select and check whether it's empty.

nodes = Kernel.open('|qnodes | grep -v "^ " | grep -v "^$"') do |f|
  f.lines.map do |line|
    line.split(' ').first
  end.reject do |i|
    EXCLUDE.any? {|x| i =~ x}
  end
end

nodes.sort.each {|n| block.call(n)}

I would recommend that instead of taking a block and yielding each element, you just return nodes.sort and rename the function to all_nodes. This way you can use all_nodes.each to execute code on all nodes, but you could also use all_nodes.map or all_nodes.select when it makes sense.

Open3.popen3("#{SSH} #{node} \"#{COMMAND}\"")

Note that this will break if COMMAND contains double quotes itself. Generally trying to escape command line arguments by surrounding them with quotes is a bad idea. system and open3 accept multiple arguments exactly to avoid this.

If you make SSH an array (with one element per argument) instead of a string, you can use the multiple-arguments version of popen3 and can thus avoid the fickle solution of adding quote around COMMAND to escape spaces, i.e.:

Open3.popen3(*(SSH + [node, COMMAND]))

IO_CONNECTIONS_TO_REMOTE_PROCESSES = {}
# ...
on_all_nodes do |node|
  stdin, stdout, stderr = Open3.popen3("#{SSH} #{node} \"#{COMMAND}\"")
  IO_CONNECTIONS_TO_REMOTE_PROCESSES[node] = [stdin, stdout, stderr]
end

If you heeded my above advice about all_nodes you can simplify this using map. I also would suggest not using a Hash here. If you use an array instead, the nodes will stay in the order in which you inserted them, which will mean that you can iterate over that array instead of invoking all_nodes again.

has_remote_errors = false

all_nodes.map do |node|
  [node, Open3.popen3(*(SSH + [node, COMMAND]))]
end.each do |node, (stdin, stdout, stderr)|
  stdin.close

  ethread = # ...
  # ...
end

This way you removed the complexity of first putting everything into a hash and then getting it out again.

while line = stderr.gets

Again, this can be written more idiomatically as stderr.each_line do |line|. Same with stdout.

first = true

This is never used. I can only assume that it's a left over of previous iterations of the code, which is no longer necessary. Obviously it should be removed.

# Let the threads finish
t1 = nil
t2 = nil
while [t1, t2].include? nil
  if t1.nil?
    t1 = e_thread.join(0.1) # Gives 1/10 of a second to STDERR
  end
  if t2.nil?
    t2 = o_thread.join(0.1) # Give 1/10 of a second to STDOUT
  end
end

I don't see any benefit of doing it this way. Just do:

e_thread.join
o_thread.join

Note that joining on one thread does not mean that the other threads stop running - only the main thread does, but that's perfectly okay as you want that anyway.


Nowhere. Events have nothing to do with MVC.
Patterns are best practices for a specific solution
First of, read my rant on MVC: http://www.sitepoint.com/mvc-problem-solution/
MVC is a pattern that helps us in seperating our display, domain logic and data representation. Thats it. Nothing more.
It doesn't say anything about events or observers. Neither does it help us save the world.
MVC comunication
MVC states that a Controler updates a model, The Model updates the view and the view triggers the Controller.
It does however not say how this should happen. Should the Model be passed a view that it then updates. Maybe, maybe not. MVC doesn't care.
Because we are using JavaScript, we have however a very strong tool to solve this communication between the Model, view and controller; The event system.
Our Model-View communication could look like this:
model.on('update', function(updatedData) {
    view.update(updatedData);
});

This is called the Observer pattern. The anonymous function is the observer that observers the model. Here, the model notifies all registered observers of a change.
Or you could go for an event notifier. where you add notifiers and listeners:
controler.prototype.changeModelName = function() {
    myEventService.notify('model.update', {'data':{'name':'myNewName'}});
};
myEventService.listenTo('model.update', function(event){
    model.update(event.data);
});
myEventService.listenTo('model.update', function(event){
    view.update(event.data);
});

Or some other approach. MVC doesn't care.


Java program to add two numbers represented by linked lists

Advice 1

Fix your code indentation. Instead of

public class LLAdd {
...
public static void printList(Node head){
...
}
...
}

you should have

public class LLAd {
    ...
    public static void printList(Node head){
        ...
    }
    ...
}

Advice 2

In method definitions, one, according to common Java coding conventions, must have a single space between parameter-closing ) and a block-opening {. Instead of

public static void printList(Node head){
    ...
}

you should write

public static void printList(Node head) {
    ...                                ^-- Space!
}

Advice 3

The class name LLAdd is really poor. Taking a look of what it does, you could come up with the name, say, BigInteger.

Advice 4

static Node head, head1, head2;

This is an anti-pattern since there is only one "instance" of the class. Make these non-static and private instead.

Advice 5

Node new_node ...

Once again, Java coding conventions dictate that the fields/variables are named in CamelCase:

Node newNode ...

Advice 6

static class Node {
    Node link;
    int data;

    Node(int data){
        this.data = data;
        this.link = null;
    }
}

Make this private and final since most likely you don't want to shine into the entire package, and you hardly need to derive from that class. Also, I would rename link to next. Finally for this advice, you don't need this.link = null;. Java sets all the object fields to null by default.

Advice 7 In principle, I think you should make your BigInteger/LLAdd immutable.

Advice 8

public static Node push(int data, Node head)...

That's is a poor name too. Looking from what it does, I suggest you rename it to prependDigit. Also, I believe you would want to check that data is within the range 0-9 unless you want to allow dealing with arbitrary radices.

Advice 9

Instead of implementing printList, I would override toString.

Alternative implementation

import java.util.Scanner;

public final class BigInteger {

    private static final class Digit {
        Digit next;
        int digit;

        Digit(char ch) {
            this.digit = ch - '0';
        }

        Digit(int digit) {
            this.digit = digit;
        }
    }

    private Digit leastSignificantDigit;

    public BigInteger(String integerText) {
        checkCharacters(integerText);
        leastSignificantDigit =
                new Digit(integerText.charAt(integerText.length() - 1));
        Digit head = leastSignificantDigit;

        for (int i = integerText.length() - 2; i >= 0; i--) {
            Digit digit = new Digit(integerText.charAt(i));
            head.next = digit;
            head = digit;
        }
    }

    private BigInteger() {

    }

    public BigInteger add(BigInteger other) {
        Digit digit1 = leastSignificantDigit;
        Digit digit2 = other.leastSignificantDigit;
        BigInteger result = new BigInteger();
        Digit headDigit = null;
        boolean carry = false;

        while (digit1 != null || digit2 != null) {
            int intDigit1 = digit1 == null ? 0 : digit1.digit;
            int intDigit2 = digit2 == null ? 0 : digit2.digit;
            int sum = intDigit1 + intDigit2 + (carry ? 1 : 0);
            carry = sum > 9;
            int currentDigit = carry ? (sum - 10) : sum;
            Digit digit = new Digit(currentDigit);

            if (result.leastSignificantDigit == null) {
                result.leastSignificantDigit = digit;
                headDigit = digit;
            } else {
                headDigit.next = digit;
                headDigit = digit;
            }

            if (digit1 != null) {
                digit1 = digit1.next;
            }

            if (digit2 != null) {
                digit2 = digit2.next;
            }
        }

        if (carry) {
            headDigit.next = new Digit(1);
        }

        return result;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();

        for (Digit digit = leastSignificantDigit;
                digit != null;
                digit = digit.next) {
            stringBuilder.append((char)('0' + digit.digit));
        }

        return stringBuilder.reverse().toString();
    }

    private void checkCharacters(String integerText) {
        for (char ch : integerText.toCharArray()) {
            if (!Character.isDigit(ch)) {
                throw new IllegalArgumentException(
                        "Character '" + ch + "' is not a valid digit.");
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        BigInteger bi1 = new BigInteger(scanner.nextLine());
        BigInteger bi2 = new BigInteger(scanner.nextLine());
        System.out.println(bi1 + " + " + bi2 + " = " + bi1.add(bi2));
    }
}


Generating lists populated with random objects

Requirements may vary so I find it hard to use with the "hardcoded" constructors. Instead I would define a function that accept such constructors as an argument.

I would also define the function returning the list-comprehension as an inner function so the off parameter is hidden from the public interface (the end-user does not need to know such implementation details). Besides, off is a terrible name for such variable when all it does it to track the recursion depth, better call it depth, then.

An other thing that could be worth taking as parameter (even though a sensible default would make sense most of the time) is the maximum length of the inner lists (and thus the maximum allowed recursion level):

import random
from string import digits

def fake_list(items, max_size=10):
    """Create a list populated with random objects constructed from `items`"""

    choices = (
            lambda _: random.choice(items)(),
            lambda depth: random_list(depth),
            lambda depth: tuple(random_list(depth)),
    )

    def random_list(depth):
        return [
                random.choice(choices)(depth + 1)
                for _ in range(max(random.randint(1, max_size) - depth, 0))
        ]

    if max_size < 1:
        raise ValueError('minimal size of output should be at least 1')

    return random_list(0)

def test():
    constructors = [
        object,
        dict,
        lambda: bool(random.randint(0, 1)),
        lambda: random.randint(1, 1000),
        lambda: ''.join(
            random.choice(digits)
            for _ in range(random.randint(1, 10))),
    ]

    print(fake_list(constructors))

if __name__ == '__main__':
    test()

That way I can call:

fake_list([lambda: float('-inf'), lambda: range(random.randint(-100, -10), random.randint(10, 100)), set])

if I need to.


Entity Framework - Add or Update Parent Entity with Children

The line ...

 dbContext.Set<DomainEntityRecord>().AddOrUpdate(domainEntityRecord);

... will always try to find an existing record in the database in order to determine whether domainEntityRecord should be marked as Added or as Modified.

But you already fetch the existing record by the statement:

var existingDomainEntity = dbContext.Set<DomainEntityRecord>()
   .Where(x => x.DomainEntityId == domainEntityRecord.DomainEntityId)
   .Include(x => x.DomainEntityDetailRecords)
   .SingleOrDefault();

So there is a redundant database roundtrip in your code. After this statement var existingDomainEntity = ... you know everything that AddOrUpdate is going to find out again. So you may as well do it yourself: if the record exist: modify it and its details, if it doesn't: add it. To modify the existing records, use CurrentValues.SetValues:

  var domainEntityRecord = mapper.Map<DomainEntityRecord>(message);

  var existingDomainEntity = dbContext.Set<DomainEntityRecord>()
    .Where(x => x.DomainEntityId == domainEntityRecord.DomainEntityId)
    .Include(x => x.DomainEntityDetailRecords)
    .SingleOrDefault();

  if (existingDomainEntity != null)
  {
    // Delete detail records that no longer exist.
    foreach (var existingDetail in existingDomainEntity.DomainEntityDetailRecords.ToList())
    {
      if (domainEntityRecord.DomainEntityDetailRecords.All(
        x => x.DomainEntityDetailId != existingDetail.DomainEntityDetailId))
      {
        dbContext.Set<DomainEntityDetailRecord>().Remove(existingDetail);
      }
    }
    // Copy current (incoming) values to db entry:
    dbContext.Entry(existingDomainEntity).CurrentValues.SetValues(domainEntityRecord);
    var detailPairs = from curr in domainEntityRecord.DomainEntityDetailRecords
                      join db in existingDomainEntity.DomainEntityDetailRecords
                        on curr.DomainEntityDetailId equals db.DomainEntityDetailId into grp
                      from db in grp.DefaultIfEmpty()
                      select new { curr, db };
    foreach(var pair in detailPairs)
    {
      if (pair.db != null)
        dbContext.Entry(pair.db).CurrentValues.SetValues(pair.curr);
      else
        dbContext.Set<DomainEntityDetailRecord>().Add(pair.curr);
    }
  }
  else
  {
    dbContext.Set<DomainEntityRecord>().Add(domainEntityRecord);
    // This also adds its DomainEntityDetailRecords
  }

  dbContext.SaveChanges();

As you see, for the details I use a GroupJoin (join - into which serves as an outer join) to determine the existing and the new details. The existing ones are modified, the new ones are added.


Reporting progress to main form's controls from within a threaded heavy task

What you've provided is a lambda expression.

The Invoke method takes a delegate as an argument. Before I explain what a delegate is, the simple answer to your question is provide one of the predefined delegate types Action or Func. These may seem like magic, but trust me, they are super simple concepts once you wrap your head around them.

Invoke(new Action(() => {...})) Action takes no parameters and returns void

Invoke(new Func<bool>(() => { return false; })); Func<T> returns T and has no parameters.

Action and Func<T,...> are simply predefined delegates. Action is defined like so:

public delegate void Action();

What is a delegate?

A delegate plain and simple is a way to describe a method signature - that is, what does the method return (if anything) and what arguments (if any) does it take.

Another way to think about this is when I'm done doing my work I always notify someone to let them know the status of goals achieved. To make this process flexible I allow you to specify that unit of work. I will invoke the custom method and send it the status of my work. For this to happen obviously I need to set some general ground rules, the rules being that the method I invoke needs to take a string (the status I send you) and return a response to me (maybe that response is "ok go home" or etc).

The beauty of specifying only the method signature is that you can make your own custom method to be invoked (as you want to above) or you could specify any method that matches the signature. In our case string in, string out would match String.Reverse (just the name). Obviously in our scenario I may be confused by the response, but this way of programming allows you to plug in different implementations. One implementation could be that I notify you via phone call, or email, or text message etc.

Depending on your use case you might return void from the method because you just want an email to be kicked off once I internally invoke the method you've given to me.

You see a lot of this programming in thing like JavaScript, it is asynchronous, it returns control back to you right away and allows you to specify a callback function, essentially a delegate that should be invoked once it's done.


A prefix notation calculator that asks about everything step by step

Use a shebang at the beginning

This is something like #!/usr/bin/env python2, and helps interpreters know how to run it.

Remove some of the unnecessary comments

Comments are good. Excessive comments are just hard to read.

e.g.

elif cmd == "+":
    x = (lorr_input("Left side addend? ", x) +
         lorr_input("Right side addend? ", x))
    print x # Implicitly output result

Turn that into:

elif cmd == "+":
    x = (lorr_input("Left side addend? ", x) +
         lorr_input("Right side addend? ", x))
    print x

And:

# Get user input
cmd = raw_input(">> ")
# Process input
if cmd == "quit":
    ....

Into:

cmd = raw_input(">> ")
# Process user input
if cmd == "quit":
    ....

Empty lines for readability

Using the previous example:

cmd = raw_input(">> ")
# Process user input
if cmd == "quit":
    ....

Into:

cmd = raw_input(">> ")

# Process user input
if cmd == "quit":
    ....

if __name__ == "__main__" check

This just checks if you are running this directly, or from a module import/something else.

Maybe put the while loop into a function called start() and use:

if __name__ == "__main__":
    start()

Don't assign unnecessary variables

The helpmsg var is pretty much useless, just print the plain string.

The lit_input function is not used

Either use it, or remove it. Maybe make a variation of the docstring for the lorr_input?

Other notes:

Nice job with the ast safe eval, but a method that doesn't involve eval would also be nice. This is a lot of work, probably unnecessary.
I would set x to 0 at the beginning, but that's personal preference.
I'm not sure, but you appear to have limited to 87 chars per line (or under). That is a PEP guideline, good job.


Timer convenience class to time code execution for user output

Your Timer class contains two timers.

The entire duration timer.
The timer for tracking pauses.

I'd move the core timer code out into a separate class.
And we can see you're starting to repeat yourself.

Initializing a timer shouldn't start the timer.
If I open my timer app should the timer start running straight away?
If I want to create some timers but I don't want the timer to be started your class gives me no options.
However just not calling start_timer in __init__ will allow everyone to use your class however is desired.
If you really really want to start the timer when building the object, you can write a class method.
class Timer:
    @classmethod
    def run(cls, *args, **kwargs):
        self = cls(*args, **kwargs)
        self.start_timer()
        return self

# option 1
timer = Timer()
timer.start_timer()

# option 2
timer = Timer.run()

start_timer restarts the timers.
You should rename the method or make the method do what is expected.

If you call pause_timer twice without calling resume_timer your code acts as if the timer was never paused the first time.

I don't really see the point of making elapsed_seconds a property.

get_timer is doing way too much and violates the SRP principle.

Rounds elapsed timings to a specified amount of decimal places.
Prints the elapsed timings.
Restarts the timer.
Returns the elapsed timings.

You should make a function to round the elapsed timings.
Then leave printing and restarting to the user.

I'd a couple more methods from functionality I'd expect from a timer.

from time import perf_counter

class CoreTimer:
    def __init__(self):
        self.stop()

    def __bool__(self):
        return bool(self.start_time)

    def start(self):
        self.start_time = perf_counter()

    def stop(self):
        self.start_time = 0

    def time_taken(self, now):
        return now - self.start_time

    def elapsed(self):
        return self.time_taken(perf_counter())

class Timer:
    def __init__(self, decimal_places=5):
        self._decimal_places = decimal_places
        self._timer = CoreTimer()
        self._pause = CoreTimer()
        self._pause_length = 0

    def __str__(self):
        state = "Paused" if self._pause else "Running"
        return f"{state} Timer at {self.elapsed_rounded()} seconds"

    @classmethod
    def run(cls, *args, **kwargs):
        self = cls(*args, **kwargs)
        self.start()
        return self

    def start(self):
        if not self._timer:
            self._timer.start()

    def stop(self):
        self._timer.stop()
        self._pause.stop()
        self._pause_length = 0

    def restart(self):
        self.stop()
        self.start()

    def pause(self):
        if not self._pause:
            self._pause.start()

    def resume(self):
        if self._pause:
            self._pause_length += self._pause.elapsed()
            self._pause.stop()

    def elapsed(self):
        if self._pause:
            duration = self._timer.time_taken(self._pause.start_time)
        else:
            duration = self._timer.elapsed()
        return duration - self._pause_length

    def elapsed_rounded(self, decimal_places=None):
        if decimal_places is None:
            decimal_places = self.decimal_places
        return round(self.elapsed(), ndigits=decimal_places)


Converting a state from hash into a JavaScript object

I think a good practice is to name what you mean, cause that makes the code more readable. So I would create a var for each state and grap a good name: stateOfViewAvailable ...


Having to pass - or even being able to pass - min and max to the method doesn't seem quite right. The arguments are only there for the method's own use when calling "itself" on its child nodes - they're not really part of the class's API. So that smells a bit.

I'd take a different approach, and add an #each method:

def each(&block)
  left.each(&block) unless left.nil?
  yield data
  right.each(&block) unless right.nil?
end

This lets you say root.each { |n| ... } like you would with an array. And it lets you include Enumerable - since all that requires is that your class implements an #each method - giving you a bunch of methods for free. For instance, you might implement #valid? like so:

def valid?
  each_cons(2).all? { |a, b| a <= b }
end

And of course, thanks to Enumerable, you can also do things like root.to_a, root.reduce, root.include? and other good stuff.

In all, you get this:

class Node
  include Enumerable

  attr_accessor :data, :left, :right

  def initialize(data = nil, left = nil, right = nil)
    @data = data
    @left = left
    @right = right
  end

  def each(&block)
    left.each(&block) unless left.nil?
    yield data
    right.each(&block) unless right.nil?
  end

  def valid?
    each_cons(2).all? { |a, b| a <= b }
  end
end

Beyond that, your current code looks good, only a few comments:

Since you have attr_accessor synthesized methods, use them. Don't access instance variables directly with @... unless you have to. The point is, that if you need to customize access, you can simply swap out the synthesized accessor with a custom one, and no other code has to change, since it'll still be calling the method.
But speaking of accessors, using attr_accessor can be a bit blunt for the left and right attributes, since it lets anyone, anywhere, set them to something nonsensical, like root.left = "foobar!". That'll break things, since you suddenly have non-Node nodes in your tree. So I'd suggest using attr_readers, but adding your own assignment methods, e.g. def left=(node); ...; end. That'll let you check things before assigning.
The method in question might be named #sorted? instead. valid? could imply any number of things. Edit: You may actually want to use (a <=> b) <= 0, as that's what used to sort objects, instead of just a <= b.
Don't bother aligning the = assignment operators like you do in the initializer. Yeah, it's pretty, and I'm often tempted to do the same, but it's a bit of busywork that - if you ever have to change the code - requires you to redo it. I've read through my own commit history on projects and wondered why seemingly unchanged lines showed up in the diff, only to realise I was messing around with the whitespace and confusing future-me.

You can also take a different tack, and use an add/insert/<< or something method to add data to the tree, rather than requiring someone else to create new Nodes. E.g root << 15 would traverse the tree, and find the right place to insert the value, creating a new node to hold it, etc. etc.. That way, you won't really need a valid? method.


I would add a sanity check on the pointer as well:

void AddTime(int seconds, tm* date) {
    if (date == NULL) return;
    date->tm_sec += seconds;
    mktime(date);
}

But other than that it looks correct.

Reading some documentation on mktime, this appears to be what it was meant for.


My Python3 Library provides a Wrapper around the Popular espeak TTS

1.PEP8

Naming

In python functions/methods/variables are using underscore as a naming separator, but not a camelCase.

Quotes

You should pick one double or single quotes and use it everywhere that is a general rule, I prefer single ones so I've changed a code as I like, but you might want to use double, just follow one way to do that.

Please read code styling guide aka PEP8

2.Class definition

Methods order

I prefer to have __init__ and __new__ as first methods defined by class, this gives you better image on class and what it does and what it got. This is not a strong rule, but most of people and libraries are following it.

Properties definition

Most of the times you want to have all your properties defined in init,
again that is not a strong rule, but in this particular case, I would define them inside __init__ instead of having a separate method to do that. If fact you I don't see much of use of your setProperties method, so I would just modify object attributes directly here if I would need it. Since there are no logics inside those methods except for changing an attribute to a value passed into it.

3.Improvements

I'm not a big fan of try:catch:pass statements you can avoid them with pre-conditions: so your say method can be modified like this:

def say(self, phrase, wait4prev=False):
    cmd = self.generate_command(phrase)
    if self.prevproc:
        if wait4prev:
            self.prevproc.wait()
        else:
            self.prevproc.terminate()
    self.prevproc = subprocess.Popen(cmd, cwd=os.path.dirname(os.path.abspath(__file__)))

Note: you don't need to pass executable explicitly since it's already a part of your cmd param.

So in the end what we have is this:

import os
import platform
import subprocess

class Speaker:
    """
    Speaker class for differentiating different speech properties.
    """
    def __init__(self, voice='en', wpm=120, pitch=80):
        self.prevproc = None
        self.voice = voice
        self.wpm = wpm
        self.pitch = pitch

        executable = 'espeak.exe' if platform.system() == 'Windows' else 'espeak'
        self.executable = os.path.join(os.path.dirname(os.path.abspath(__file__)), executable)

    def generate_command(self, phrase):
        cmd = [
            self.executable,
            '--path=.',
            '-v', self.voice,
            '-p', self.pitch,
            '-s', self.wpm,
            phrase
        ]
        cmd = [str(x) for x in cmd]
        return cmd

    def say(self, phrase, wait4prev=False):
        cmd = self.generate_command(phrase)
        if self.prevproc:
            if wait4prev:
                self.prevproc.wait()
            else:
                self.prevproc.terminate()
        self.prevproc = subprocess.Popen(cmd, cwd=os.path.dirname(os.path.abspath(__file__)))


iterative binary_search Python implementation

Be sure to check bisect the Python's standard binary search module.

This is a good implementation of Binary Search; I just have a few nitpicks:

How about a high and low overload?

Instead of declaring your lower and higher index like this:

lower_index = 0
upper_index = len(array) - 1

You could give them as argument overloads

def binary_search_iterative(array, item, low=0, high=None):
    if high is None:
        high = len(array)
    ...

Change your comments accordingly

Don't mix comments and docstrings, stick with docstrings if you want to explain arguments

"""iteratively return the index of the item with binary search or None if not found"""
# Sorted array that has to be the condition
# go through several iteration until we found this
# First, set the lower_index = 0
# upper_index as the length of array -1
lower_index = 0

That could be this:

"""Return the index of the item with binary search or None if not found

Keyword arguments:
array -- the list to search in
item -- the item to search for
high -- the highest index to search in between (default highest index of the array)
low -- the lowest index to search in between (default 0)
"""

This uses the PEP257 Docstring style, but you may use your own as long as it is clear.
Remove redundant comment

Commenting is good, but don't overdo it; your code is good enough to speak for itself. These comments feel redundant:

# calculate the middle index by sum the lower_index and upper_index and divide by 2
# check if the item is found
# Did not find


Custom function for serialization of form inputs (and selects)

You are not really implementing in plain JavaScript in that you are using jQuery inside the function. This seems to be an odd choice. Are you using jQuery or not?  You should make a decision. If you are using jQuery, then I don’t know why this function would exist at all.

The function name itself is meaningless and does not at all convey what the function does.

You are not url encoding your query string.

You are not handling case where your asynchronous fails to return 200 response.

You are using loop counters where you don’t really need to.

It makes no sense how you build a query string then split it apart and then reassemble it.

Code style is problematic:

inconsistent indentation
lines of code that are too long


Simple python code takes command line argument for file location and tokenizes text

You have a few redundant and unnecessary calls in there.

Calling open(sys.argv[1]) right before with open(sys.argv[1]) as inputfile: does not do anything.
The with statement already takes care of closing the file. So you don't need the inputfile.close
If with did not close your file, it would not be closed, because you actually need to call that method (so inputfile.close())
You should never have a bare except. This catches more than you want, including, for example, the user pressing Ctrl+C. Always use as specific an exception as possible. Here you probably want to except the file missing, so use either IOError (Python 2.x) or FileNotFoundError (Python 3.x)

You should also have a look at Python's official style-guide, PEP8. It recommends surrounding operators with spaces, so if len(sys.argv) == 2:.

If you want this script to do something more, you should start to split the responsibilities into functions. Here you could have something like this:

import sys

def parse_lines(file_name):
    """Parse the lines of file_names into comma-separated lists"""
    with open(file_name) as inputfile:
        for line in inputfile:
            yield ",".join(line.split())

if __name__ == "__main__":
    # Open file passed by terminal
    if len(sys.argv) == 2:
        try:
            for line in parse_lines(sys.argv[1]):
                print(line)
        except FileNotFoundError:
            print(f"File {sys.argv[1]} not found")
            sys.exit(-1)

Here I put the parsing into a function, which is actually a generator. It yields the parsed lines one by one. I also added a docstring describing the function.

I also made your error handling code more specific. Your code actually makes debugging your program harder, because the program returning -1 (regardless of the error encountered) is  a lot less clear than Python creating a stacktrace. If you do catch errors, you should handle them (and give the user feedback if necessary). This uses Python 3.6's new f-strings.


It looks safe from SQL Injection, your binding and preparing is fine.

This is how I would do it, using the PHP code found here in the manual.

In fact, these calls would benefit from being in their own functions; however this would work the same.

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$val = $_GET['val'];

/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO tablename (value) VALUES (?)")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $val);

    /* execute query */
    if($stmt->execute()) {
       echo 'INSERTED';
    }
    /* close statement */
    $stmt->close();
}

if ($stmt = $mysqli->prepare("SELECT * FROM tablename WHERE value = ?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $val);

    /* execute query */
    if($stmt->execute()) {
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            echo $row['id'].'<br />';
        }
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>


Python scanner for the first free port in a range

Your code has some incorrect assumptions.

an application may listen on a specific address/port combination; 127.0.0.1:port can be available while *:port is not.
an application may bind a port without listening.  Connects will fail, but so will your own bind.
a firewall or other mechanism can interfere with connections, generating false positives in your scan.

The reliable approach is to bind the port, just as your dashboard will, and then release it.

result = sock.bind(('', port))
sock.close()

You'll need to catch the exception and this is a good opportunity to move the whole thing into a function.   That will make the start_dashboard logic cleaner and get rid of boolean loop-terminator scan_ports.    Just exit the loop by returning the answer.

def next_free_port( port=1024, max_port=65535 ):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while port <= max_port:
        try:
            sock.bind(('', port))
            sock.close()
            return port
        except OSError:
            port += 1
    raise IOError('no free ports')

def start_dashboard():

    # pass optional second parameter "max_port" here, else scan until a free one is found
    port = next_free_port( os.getenv('DASHBOARD_PORT_ENV_VAR', 8008) )

    dashboard.configure(port=port)
    dashboard.launch()

You can use netcat to make ports in-use for testing: nc -l -p 9999 will listen on port 9999; press control-C to end it.


Generating CSV strings for various 3rd party utilities

I doubt you'll find a way of not listing all those properties without using reflection, but the following helps to eliminate that huge format string which is likely to become the source of bugs.

var properties = new Object[]
{
    this.BlockType,         //  1, A_NAME
    this.Tag,               //  2, A_TAG
    this.Description,       //  3, A_DESC
    this.InitialScan,       //  4, A_ISCAN
    this.AutoManual,        //  5, A_SCAN
    this.ScanTime,          //  6, A_SCANT
    this.IoDevice,          //  7, A_IODV
    this.IoAddress,         //  8, A_IOAD
    this.InitialAmStatus,   //  9, A_IAM
    this.AlarmPriority,     // 10, A_PRI
    this.AlarmEnable,       // 11, A_ENAB
    this.EnableOutput,      // 12, A_EOUT
    this.HistDescription,   // 13, A_HIST_DESC
    this.SecurityArea1      // 14, A_SECURITYAREA1
}.Select(x => String.Format("\u0022{0}\u0022", x));

return String.Join(",", properties);

A couple of things to note:

This is hardly an efficient way of doing it, but offers fairly maintainable code. If you have an extra property, just add it to the array.

This will only work in .NET 4.0. In earlier versions, you'll have to call ToArray() after that call to Select.


Updating multiple svn repositories using powershell

Reusable Commands

One of the most important ideas in PowerShell is the Get/Update/Set pattern. A clear delineation between resources (nouns) and commands (verbs) helps to write code that is useful not only for scripting, but also in the interactive shell.

We only need a couple of new commands. First we need to Find the working copies under some directory, then Update each working copy. The list of approved verbs for PowerShell is a great resource for help with naming your commands. Let's use these names.

Find-SvnWorkingCopy (Find looks for an object in a container)
Update-SvnWorkingCopy (Update brings a resource up-to-date)

Functions and Modules

Now you're convinced that we should create reusable commands with these great new names. What next? PowerShell v2 introduced the concept of a module, which is just a file that contains functions. (Of course, you could just create a new script for each command but it helps to keep things tidy by bundling all of the functions together in one file.)

What should our functions look like? Yes they will need to take some parameters. But more importantly, they should return objects to the pipeline, even if they aren't a "getter" function! This makes it easier to review what impact a function had.

Some actual code

Luckily for us, somebody else already found a way to find all the svn working copies underneath a directory. We can reuse that.

SvnTools.psm1

function Find-SvnWorkingCopy
{
    Param (
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        $BasePath
    )
    process
    {
        $prev = "^$"
        Get-ChildItem -Recurse -Force -Include ".svn" -Path $BasePath |
            Where-Object {
                $_.PSIsContainer -and $_.Fullname.StartsWith($prev)-eq $false
            } |
            ForEach-Object {
                $prev=$_.Fullname.TrimEnd(".svn")
                $prev
            }
    }
}

I took some liberties with the command Update-SvnWorkingCopy. In addition to calling "svn update" like your original script, it also calls "svn info" and parses the results to find the current revision number and include that in the object returned to the pipeline.

SvnTools.psm1 (continued)

function Update-SvnWorkingCopy
{
    Param (
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        $WorkingCopy
    )
    process {
        svn update $WorkingCopy > $null
        [String[]] $result = svn info $WorkingCopy
        [String] $revStr = $result -like "Revision:*"
        [int] $revNumber = $revStr.Replace("Revision: ", "")
        New-Object -TypeName PSObject -Prop @{
            WorkingCopy=$WorkingCopy;
            Revision=$revNumber;
        } | Write-Output
    }
}

Now we can reap the benefits from creating these commands. Here's your original script, rewritten to take advantage of our new module using just one line.

UpdateMyWorkingCopies.ps1

Import-Module C:\path\to\module\SvnTools.psm1
Find-SvnWorkingCopy -BasePath "C:\TRUNK\" | Update-SvnWorkingCopy

You could easily redirect the output to a file. If you don't, it will show up on screen looking something like this.

WorkingCopy         Revision
-----------         --------
C:\TRUNK\Alpha      31
C:\TRUNK\Bravo      42
C:\TRUNK\Charlie    16

References

The Scripting Guy! blog on TechNet has a really excellent series about building your own PowerShell cmdlet that I recommend reading.

Coding Style

https://stackoverflow.com/a/2031927/190298
https://stackoverflow.com/questions/5260125/whats-the-better-cleaner-way-to-ignore-output-in-powershell
http://www.powershellcommunity.org/Wikis/BestPractices/tabid/79/topic/Naming/Default.aspx

Bonus Points

For bonus points, install the module into one of the module path folders ($env:PSModulePath) so that you can import it from the shell more easily.

And if you want to get even more fancy, implement another command called Get-SvnWorkingCopy which parses all of the results from svn info. It should integrate nicely with the two commands we already created here.


Python Etiquette for Functions in Multiple Files

Putting all of your code into a single file is bad.  As a very VERY loose rule of thumb I try to avoid having any source file be more than a thousand lines of code, but the real rule to follow is that code should be broken up into modules that have coherent and comprehensible purposes, and those modules should live in their own files.

The origin of rules of thumb like "no file longer than a thousand lines" is that if a file is really long, it's no longer comprehensible by a normal human brain, and so you need to think about how to break your logic down into smaller and more mentally-digestible pieces.  A function (or group of interrelated functions) that is long but is self-contained and doesn't interact with anything else would make a lot of sense to have in its own file/module.

I'd probably do my argument parsing right in the main function unless the arg parsing was so complex that it felt like it needed to be its own module.


As @ChoiZ already said in a comment, I would not pass the PHPMailer object in the constructor.

It doesn't really have any benefits (it's not like you can - or would want to - just pass a different mail class), and it's additional work for the caller.

It also means that it will be hard to change the library you are using. With your Mail class, you created a nice interface for sending emails, but by passing the class that actually sends mails via constructor, you are binding yourself to that library.

Misc

The names body and plainText represent the same thing - just one with and one without HTML. It's generally best to name same things the same. So I would go with body/bodyPlain or htmlText/plainText to avoid confusion.
I would rename sendMail to mail, as the class is already named mail.
Your spacing is not consistent.
if there is not reason not to, fields should be private.


Checking whether two lists are equal is naturally an O(n) operation. So yes, your code looks efficient.

Note that you could also replace your for loop with Enumerable.SequenceEqual

public static bool EqualsAll<T>(this IList<T> a, IList<T> b)
{
    if (a == null || b == null)
        return (a == null && b == null);

    if (a.Count != b.Count)
        return false;

    return a.SequenceEqual(b);
}

If you take a look at its implementation, you'll notice that it's very similar to yours. It might be just a tiny bit less efficient - so if performance is an issue here, measure both approaches, and then weigh readability/maintainability vs performance gains.

On a different note, I would rename the method to SequenceEqual and consider it a "specialization" of Enumerable.SequenceEqual for lists.

I would also consider throwing an exception if either argument is null.
This would be consistent with the BCL's own extension methods (Select, Where, ToList, SequenceEqual, Any, All, etc).


Counting athletes whose height is in a given range

Your code and algorithm seem pretty optimal for the problem.

A minor nit-pick, the PrintWriter "out" is not being used.  (The braces immediately following are unnecessary, but wouldn't affect performance.)

There are only 2 tiny things which might help:

1) In each loop, you're allocating a new int[] array.  If you didn't do this, you would need to call Arrays.fill() to zero out the array each time.  I doubt there would be much difference as allocations of this type are pretty fast.

2) The bigger possibility is I/O performance on the output.  When fine-tuning to meet a time constraint, I/O might make the difference.  Instead of calling System.out.println, try using a StringBuilder and appending the output.  Then, after the main loop, do a single output operation on the resultant string.

Also, one final tip.  The linked problem statement indicates that none are less than 150 or greater than 250.  If you get input with 250, you will get an array bounds exception.  You need an array of size 101.


There's only so much a code analysis tool can see.

using (SqlCommand command = CreateCommand(query, parameters))

You're using a parameterized SqlCommand, and given the example you appear to have everything under your own control, strongly typed and all.

Depends who is calling this ExecuteNonQuery method, and where query is coming from.

It appears the query is coming from a QueryBuilder, out of a QueryTemplate.

The thing is, this QueryBuilder has been given the ability to perform replacement of "tokens" in the SQL command string, and it seems to be taking in a string for the replacement - if I were a code analysis tool, I'd raise a flag right there.

I don't see any apparent specific problem with the example usage you've supplied. But how the API is used is the responsibility of the programmer using it, and the API takes a SQL command string, and actually sends another to the server. The API could easily be misused to misplace these "tokens" and pass a user-supplied value as the replacement value, and bingo, you have SQL injection happening.

In other words, I think there is a potential SQL injection issue with the API, if it's misused. But if it's used everywhere the way you've shown, in my opinion you can put that warning onto the "false positives" pile.

Using an Object Relational Mapper, or any current technology for that matter (Entity Framework comes to mind), could significantly reduce all that boilerplate - and risk of misuse. But no API is shielded from carelessness.

I can't help but mention this one:

SqlCommand retVal = this.connection.CreateCommand();

retVal reads like VBA code from 1998. You're using readable identifiers everywhere else; would returnValue kill anyone? Personally I use result all the time. I can live with params, but seeing retVal in my code base would automatically trigger Ctrl+R,R and a new name.


Multi-threaded utility that logs some audit trails

DO NOT LOCK ON EMPTY STRING

In .NET every string is stored only once in the AppDomain so if you are locking on empty string everything will stop until you release the lock.

The correct syncroot can be:

private readonly object _flag = new object();

And yes you should use double check locking. The other thing is thati would use a ConcurrentQueue instead of SynchronizedCollection.


private Boolean isWild = true; // is the animal wild?
private Boolean hasSharpPointyTeeth = false; // does it have sharp, pointy teeth?!

Why are you using the wrapper class? Use the primitive boolean instead.
Also, about comments:
private static int counter = 0; // how many animals we have created (to demonstrate a static variable)
private Boolean isWild = true; // is the animal wild?
private Boolean hasSharpPointyTeeth = false; // does it have sharp, pointy teeth?!
private int age = 0; // how old

All the comments here are unnecessary with better variable names. Comments explain why, not what.
All of the variable names are fine, maybe except counter: could be numberOfAnimals...
NAMING
public Boolean getIsWild()

should be isWild(). Likewise,
public Boolean getHasSharpPointyTeeth()

should be hasSharpPointyTeeth().
But getAge(), for example, should stay getAge().
public static int getCounter()

should be getNumberOfAnimals()
speak() is poorly named. I would've expected it to print what it says, but it just returns what it says. I would either change it to do what I said, even though I would suggest against it, or rename it. I would suggest rename it to getSpeech().
Misc
    this.isWild = isWild;
    this.hasSharpPointyTeeth = hasSharpPointyTeeth;
    this.age = age;

In the default constructor is completely unnecessary: it already has those values, does it need those same values again? Same in the Dog class:
    this.name = name;
    this.owner = owner;
    this.breed = breed;
    this.sex = sex;

The begin and end getters/setters comments are unnecessary: why are those there?
The (){ after each method should be () { according to Java standard conventions.
Constructors should be public.
I think the sex property should be Animal's.
Also you should check the parameters and see if they are valid: you don't want age to be set to -1 or breed to be set to something like hello... do you? I'll leave that up to you, but the general format is this:
if (is not valid) {
    throw new IllegalArgumentException("Why is it not valid?);
}

You shouldn't be testing with main(). Instead use JUnit 4 or any similar testing library.
Final Code
public class Animal {

    private static int numberOfAnimals = 0;
    private boolean isWild = true;
    private boolean hasSharpPointyTeeth = false;
    private int age = 0;
    private String sex = "Unknown";

    public Animal() {
        numberOfAnimals++;
    }

    public Animal(String sex, boolean isWild, boolean hasSharpPointyTeeth, int age) {
        this.sex = sex;
        this.isWild = isWild;
        this.hasSharpPointyTeeth = hasSharpPointyTeeth;
        this.age = age;
        numberOfAnimals++;
    }

    public void setIsWild(Boolean isWild) {
        this.isWild = isWild;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setHasSharpPointyTeeth(Boolean hasSharpPointyTeeth) {
        this.hasSharpPointyTeeth = hasSharpPointyTeeth;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Boolean isWild() {
        return isWild;
    }

    public Boolean hasSharpPointyTeeth() {
        return hasSharpPointyTeeth;
    }

    public int getAge() {
        return age;
    }

    public String getSex() {
        return sex;
    }

    public static int getNumberOfAnimals() {
        return numberOfAnimals;
    }

    public String getSpeech() {
        return "Grrrr!";
    }

    public String toString() {
        String out = getSpeech() + "\n" + "Age: " + getAge() + "\n" + "Wild? "
                + isWild() + "\n" + "Has Sharp Pointy Teeth? "
                + hasSharpPointyTeeth() + "\n";
        return out;
    }

}

public class Dog extends Animal {

    private String name = "None";
    private String owner = "None";
    private String breed = "Unknown";

    public Dog() {
        super("Unknown", false, false, 0);
    }

    public Dog(boolean isWild, boolean hasSharpPointyTeeth, int age, String name,
            String owner, String breed, String sex) {
        super(sex, isWild, hasSharpPointyTeeth, age);
        this.name = name;
        this.owner = owner;
        this.breed = breed;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getName() {
        return name;
    }

    public String getOwner() {
        return owner;
    }

    public String getBreed() {
        return breed;
    }

    @Override
    public String getSpeech() {
        return "Woof!";
    }

    @Override
    public String toString() {
        String out = super.toString()
                + "Name: " + getName() + "\n" + "Breed: " + getBreed() + "\n"
                + "Sex: " + getSex() + "\n" + "Owner: " + getOwner() + "\n";
        return out;
    }

}


I don't know, if you can understand all my code, but I would implement the task this way:

#include <iostream>
#include <random>
#include <string>

enum class CompareAnswer { LESS, LESS_OR_EQUAL, GREATER, GREATER_OR_EQUAL };
enum class TruthAnswer { YES, NO };

CompareAnswer ask_user_compare(int compare_with) {
  static auto randfn = []() -> bool {
    static auto dist = std::uniform_int_distribution<>(0, 1);
    static auto gen = std::default_random_engine();
    return static_cast<bool>( dist(gen) );
  };

  char user_input;
  std::cout << "Is your number ";

  if (randfn()) {
    std::cout << "less than " << compare_with << "? [y|n]\n";
    std::cin >> user_input;
    if (user_input == 'y')
      return CompareAnswer::LESS;
    if (user_input == 'n')
      return CompareAnswer::GREATER_OR_EQUAL;
    throw std::runtime_error("invalid answer");
  };

  std::cout << "greater than " << compare_with << "? [y|n]\n";
  std::cin >> user_input;
  if (user_input == 'y')
    return CompareAnswer::GREATER;
  if (user_input == 'n')
    return CompareAnswer::LESS_OR_EQUAL;
  throw std::runtime_error("invalid answer");
};

TruthAnswer ask_user_is(int number) {
  std::cout << "Is your number " << number << "? [y|n]\n";
  char user_input;
  std::cin >> user_input;

  if (user_input == 'y')
    return TruthAnswer::YES;
  if (user_input == 'n')
    return TruthAnswer::NO;
  throw std::runtime_error("invalid answer");
}

int guess_number(const int min, const int max) {
  // std::cout << "\ndebug: min=" << min << " max=" << max << "\n";

  const int median = (min + max) / 2;  // (77+78)/2  =77

  if (median == min) {
    return ask_user_is(min) == TruthAnswer::YES ? min : max;
  };

  switch (ask_user_compare(median)) {
    case CompareAnswer::GREATER:
      return guess_number(median + 1, max);
    case CompareAnswer::GREATER_OR_EQUAL:
      return guess_number(median, max);
    case CompareAnswer::LESS:
      return guess_number(min, median - 1);
    case CompareAnswer::LESS_OR_EQUAL:
      return guess_number(min, median);
    default:
      throw std::logic_error("need case for some of 'enum Answer' ");
  };
};

int main() {
  constexpr int MIN = 0;
  constexpr int MAX = 10000;

  std::cout << "Choose a number from " << MIN << " to " << MAX << "\n";
  int number;
  std::cin >> number;
  if(number < MIN || number > MAX) throw std::runtime_error("Invalid number");

  int guessed = guess_number(MIN, MAX);
  std::cout << "Your number is: " << guessed << "\n";
}

Even though guess_number is recursive function, probability of stack overflow extremely low (cause log(N) complexity). Asking user again instead of throwing exception may be good idea too.

Also:
Generally forget about srand, use <random> instead (srand is only for homework)


Finding pairs of Amicable Numbers, up to 10000

printf("|---------- PROGRAM FOR AMICABLE NUMBERS.----------|");

This kind of banner message makes it harder to use the output of your program in a pipeline.  I'd suggest removing it (the user has chosen to run it; trust them to know what they're doing!).

    int num1,num2,sum=0;

What's sum for?  It doesn't seem to be used.

    for(num1=1; num1<=10000; num1++)

Where does the magic value 10000 come from?  It should be a named constant (or, better, specifiable as a command-line argument).

        for(num2=1; num2<=10000; num2++)

Do we really need to consider every pair in both directions?  We could simply iterate while num2 < num1 (which also saves ourselves a comparison later).  But see below why this loop isn't needed at all.

                if ((num1==sum_of_divisors(num2))

There's no prototype visible for sum_of_divisors() - enable the relevant compiler warnings and provide the prototype (e.g. by moving the definition ahead of main()).

        for(num2=1; num2<=10000; num2++)
            {
                if ((num1==sum_of_divisors(num2))
                    && (num2==sum_of_divisors(num1))
                    && num1!=num2)

In the inner loop, sum_of_divisors(num1) is a constant, so we could save it in the outer loop, and make that the first comparison (so that short-circuit && will then evaluate sum_of_divisors(num2) just once).  Then observe that we have a loop which tests whether its index is equal to a particular value - that means that we replace the inner loop with a single test:
    for (num1 = 1;  num1 <= 10000;  num1++) {
         num2 = sum_of_divisors(num1);
         if (num1 < num2 && sum_of_divisors(num2) == num1) {
             /* we found a pair */
         }
    }

The num2 < num1 test there saves us re-finding pairs we've already seen.  num2 > num1 would also work, of course - I chose this version so that we print each pair lowest-first, as that seems to be the convention.

                    printf("\n%d\t\t%d", num1,num2);

It's better to consistently end your output with newline, rather than beginning with newline.  This works better in programs that might emit errors or other diagnostics, and plays nicely with line-buffered output such as interactive terminals (where the newline causes a flush).

    for(i=1; i<n; i++) if(n%i==0) sum += i;

This is a really inefficient way to accumulate factors.  You can reduce it to the range (1, √n) with sum += i + n/i (adjusted a little to avoid double-counting √n when n is square); it may be better instead to generate all the prime factors and use those to generate the composite factors.

After making the above improvements, I found the runtime was below my measurement threshold.  Increasing the limit to 1 million gives a runtime of about 2 seconds - that might be acceptable; if not, the problem parallelizes well (other than outputting the results).

Modified version
#include <stdio.h>

#if USE_LONG_TYPE
typedef unsigned long Number;
#define FMT "%lu"
#else
typedef unsigned int Number;
#define FMT "%u"
#endif

static const Number MAX_VALUE = 1000000;

Number sum_of_factors(Number n)
{
    Number sum = 1;
    Number i = 2;
    for (;  i < n/i;  ++i) {
        if (n/i*i == n) {
            sum += i + n/i;
        }
    }
    if (i*i == n)
        sum += i; /* add square root only once */
    return sum;
}

int main()
{
    //#pragma omp parallel for
    for (Number num1 = 1;  num1 <= MAX_VALUE;  ++num1) {
        Number num2 = sum_of_factors(num1);
        if (num2 > num1 && num1 == sum_of_factors(num2)) {
            printf(FMT "\t\t" FMT "\n", num1, num2);
        }
    }
}


Fetching Python news headlines for Alexa

You probably want to move the session to a global variable(or simply use requests.get) else at function level it is not helping in re-using any connections right now and is adding an extra level of indentation to your code.
This is mostly opinionated but grouping from x import y based imports below import z makes the imports bit easier to read. Plus keep the items within each group sorted as well.  Google's style guide also contains a related example.

import requests
from bs4 import BeautifulSoup
from dateutil.parser import parse
from flask import Flask, jsonify
from lxml import etree
from nltk import sent_tokenize


Just get rid of the link function entirely. You can set the background-image in the template with ng-style, and then you have one less function to worry about:

.my-card(ng-style='{"background-image": "url(" + card.item.image_url + ")"}', ng-class='card.cardClass')
  button(ng-click='card.toggle()')
  .my-card-content(ng-show='card.item.showMore')
    h1 {{::card.item.name}}
  .my-card-more(ng-show='!card.item.showMore')
  .my-card-bg

If you want to build up the url(card.item.image_url) string in the controller for easier testing, you can still use ng-style to apply the resulting variable. For example:

function MyCardCtrl() {
  var vm = this;

  vm.backgroundUrl = 'url("' + vm.item.image_url + '")';

  vm.cardClass = 'my-card-' + vm.item.type;

  vm.toggle = function() {
    vm.item.showMore = !vm.item.showMore;
  };
}

Also, if you're on Angular 1.5+, this directive can be written even more simply as a component:

angular
  .module('components')
  .component('myCard', {
    bindings: {
      item: '<'
    },
    templateUrl: 'my-card.html',
    controller: 'MyCardCtrl',
    controllerAs: 'card'
  })
  .controller('MyCardCtrl', [MyCardCtrl]);


Most elegant image to image frame comparison algorithm

If we move past rewriting the boolean expressions and instead rework the formulas, I think we can get something a little easier to manage.

If I understand correctly, your goal is to have the image cover the frame. That is to say, for the frame to be filled and the image cropped.

In that case, All we need to do is scale the image to the frame.

var imageHeight = 150, imageWidth = 310, height = 240, width = 300;

//Find the larget discrepancy between frame size and corresponding image size
var scaleRatio = Math.max( height/imageHeight, width/imageWidth );

//Apply the scale to the whole image.
imageHeight *= scaleRatio;
imageWidth *= scaleRatio;

If instead your desire it to have the image fit in the frame, then all we need to do is replace Math.max with Math.min.


Calculating amount of diet soda a dieter can drink without dying

Each of the three methods runs correctly, and does so in constant time.  That's good.

Comments

You wrote one comment.  Either

remove the comment (because it could become inconsistent if the constants change and is therefore a maintenance headache), or
hard-code the answer and discard everything else (System.out.println("2600.0 litres.");), or
write the comment as asssertion instead (assert maxAmountOfDietSodaDieterCanDrinkInLitre() == 2600.0;)

Constants

The names of the constants and methods are extremely clear, which is good.  You might want to shorten them, though.  If so, I suggest:

private static final double DIETER_TARGET_KG = 65,
                            MOUSE_KG = 0.025,
                            MOUSE_SWEETENER_LD50_L = 0.001,
                            SWEETENER_CONCENTRATION_IN_SODA = 0.001;

That puts the members in an order where each constant is related to its neighbour.  As a bonus, they are in alphabetical order.  I've chosen to use SI units throughout.  "LD50" is standard notation in toxicology for the median lethal dose.

Methods

I think you could have decomposed the problem more logically.  For example, what quantity is being expressed by the parenthesized expression

(maxAmountOfDietSodaAMouseCanDrinkInLitre() * DESIRED_WEIGHT_OF_DIETER_IN_GRAMS)

… whose units are L ∙ g?

I would therefore write the solution as follows:

/**
 * Median lethal dose of artificial sweetener, in litres per kilogram of
 * the subject's body weight.
 */
public static double sweetenerLD50() {
    return MOUSE_SWEETENER_LD50_L / MOUSE_KG;
}

/**
 * Median lethal dose of diet soda, in litres per kilogram of the subject's
 * body weight.
 */
public static double sodaLD50() {
    return sweetenerLD50() / SWEETENER_CONCENTRATION_IN_SODA;
}

/**
 * Median lethal dose of diet soda, in litres.
 *
 * @param subjectKG subject's body weight, in kilograms
 */
public static double sodaLD50(double subjectKG) {
    return subjectKG * sodaLD50();
}

public static void main(String[] args) {
    System.out.println(sodaLD50(DIETER_TARGET_KG) + " litres.");
}

Note that unlike the // 2600.0 litres comment, JavaDoc serves as useful documentation, and is unlikely to become out of sync if the numbers change.


You could use composition instead of inheritance:

class OperationDevice(Device):
    def __init__(self):
        super(OperationDevice, self).__init__()

    def start(self):
        # Do operation specific code

    def stop(self):
        # Do operation specific code

class SimulationDevice(Device):
    def __init__(self):
        super(SimulationDevice, self).__init__()

    def start(self):
        # Do simulation specific code
        self.fsm.start()

    def stop(self):
        # Do simulation specific code
        self.fsm.stop()

class DualModeDevice(Device):
    def __init__(self, mode='simulation'):
        super(DualModeDevice, self).__init__()
        self._mode = mode
        self._mode_map = {
            'simulation': SimulationDevice(),
            'operation': OperationDevice()
        }

    def start(self):
        self._mode_map[self._mode].start()

    def stop(self):
        self._mode_map[self._mode].stop()


First some minor issues with naming, then a rewrite:

prev could be previous, there is no need to skimp on characters. node_j and node_i are completely different things, yet their names suggest they are both "moving pointers". That is only true for node_j. May I suggest using current and insert instead?

The use of while..else is pretty cool, but confused me at first. Take that with a grain of salt, though, I'm not usually writing a lot of python.

Now for the meat of the problem:

This can be simplified by inverting the logic on your traversal. Consider the following code:

def sorted_insert(head, data):
    if head is None:
        return Node(data)
    if data < head.data:
        new_head = Node(data)
        new_head.next = head
        return new_head
    # at this point we will always return head
    current_node = head
    # advance if next node is smaller than node to be inserted
    while current_node.next is not None and current_node.next.data < data:
        current_node = current_node.next

    insert = Node(data)
    insert.next = current_node.next
    current_node.next = insert
    return head

This is an improvement over the code you presented because it separates special cases from traversal.

We first handle the special case of an empty list (head is None).
Then we handle the case where we create a new head (data < head.data)

With these special cases out of the way we now search for the insertion position, namely what you store in prev. The way this works is by advancing current_node only if the next node also has a smaller data than the insertion.

This simplification allows us to eliminate a variable at the cost of a somewhat more difficult to understand loop condition. Overall this tradeoff is worth it, because we reduce the complexity of the loop body.

After we found the insertion position, the insertion itself becomes a matter of setting the properties in the correct order to avoid dropping the tail of the list.


Javascript reducing an array of arrays to a single array with concat or push

The first one is more efficient in a sense that you're just reusing the array, and not recreating one on each iteration like the other one. However, neither of them are "efficient" in a sense that you're still looping... and there's actually a better way.

array.concat accepts multiple args. You can just use the spread operator to spread the arrays in the array as its args.

const arr = Array.prototype.concat.call([], ...arrayOfArrays)

Or the older way to do it is using function.apply

const arr = Array.prototype.concat.apply([], arrayOfArrays)

I'm being too formal and all. A shorter version of the spread looks like:

const arr = [].concat(...arrayOfArrays)

Choose your weapon:

const arrayOfArrays = [[1,2], [3, 4], [5, 6]]
const arr1 = Array.prototype.concat.call([], ...arrayOfArrays)
const arr2 = Array.prototype.concat.apply([], arrayOfArrays)
const arr3 = [].concat(...arrayOfArrays)

console.log(arr1)
console.log(arr2)
console.log(arr3)


When you need to loop a fixed number of time, but don't actually need the loop index, it is customary to use _ as the loop index.  So, in fibonacci(n), you would write for _ in range(n):.

Your fibonacci() generator is generating too many values.  Your last code value is 26, so any fibonacci value greater than 26 is unnecessary.  Instead of asking for a fixed number of values, ask for values up to a specific limit.

def fibonacci_up_to(last):
    a, b = 1, 1
    out = []
    while a <= last:
        out.append(a)
        a, b = a+b, a
    return out

And use F = fibonacci_up_to(26)

The following is an incorrect comment:

# Lagged fibonacci numbers the sequence starts: 1,2,3,5,8,11

The fibonacci sequence doesn't contain an 11; the number, following after 5 and 8 would be 5+8=13!

In makeCodebook():

It is usually clearer to write x = x-f as x -= f

Instead of always appending "1" to the end of code after reversing it, you could simply initialize code = ["1"] at the start.

The while x != 0: loop is unnecessary.  After the for f in F: loop, x will have become zero, or there is a logic error in constructions of the code for x.  Remove while x != 0:, and optionally add an assert if you are unsure x actually reaches zero.

Construction your code dictionary D:

D = {}
for a,b in zip(alpha, codes):
    D[a] = b

can be re-written with list-comprehension as:

D = { a: b for a, b in zip(alpha, codes) }

Or, as pointed out by @Graipher in the comments, simply:

D = dict(zip(alpha, codes))

Using if decode == False: followed by if decode == True: is unnecessary verbose.  if decode == False: can simply be if not decode:, and the reverse condition should simply be else:.  Or better, eliminate the negated logic, by swapping the statement order:

if decode:
    D = { code: letter for letter, code in zip(alpha, codes) }
else:
    D = { letter: code for letter, code in zip(alpha, codes) }

Or, leveraging @Graipher's simplification from the comments and Python's x if cond else y expression, the above can be written in one line.  Whether this is clearer or more obfuscated is a matter of taste:

D = dict(zip(codes, alpha)) if decode else dict(zip(alpha, codes))

In prefixCode():

Constructing the out array can be done with list comprehension:

out = [ D[letter] for letter in text ]

but this out array is just a temporary used as an argument in the next statement, so you should combined them:

return "".join( D[letter] for letter in text )

Your function has (or will have) two entirely different execution paths with almost no common functionality, one for encoding, and (eventually) one for decoding.  Write this as two functions, not as one function with a decode parameter to choose between the paths:

def encode(text):
    # ...

def decode(text):
    # ...

Use pylint or similar to check your code for PEP-8 compatibility.  Including things such as:

use spaces after commas: zip(alpha, codes) not zip(alpha,codes)
use spaces around operators: x - f not x-f
use lower_case_function_names(), not mixedCaseFunctionNames()
use lower_case_variables not uppercase identifiers like D and F

Generating your codebook:

This can be simplified by (for the moment, ignore the final terminating 1) noting that the code for a Fibonacci number is simply a number of placeholder 0's followed by a 1, and the code for a number like 17 (=13+4) will be the code for 4 (101), followed by a number of placeholder 0's, and then a 1 for the largest Fibonacci value smaller than the number (13).  After building all of the codes, add the final 1 terminator to each.

def codebook(key):
    codes = [""]
    a, b = 1, 1
    digits = 0

    for x in range(1, len(key)+1):
        if x >= a:
            a, b = a+b, a
            digits += 1

        prefix = codes[x-b]
        codes.append(prefix + "0"*(digits - len(prefix) - 1) + "1")

    return { letter: code+'1' for letter, code in zip(key, codes[1:]) }

letter_to_code = codebook("ETAOINSRHLDCUMFPGWYBVKXJQZ")

code_to_letter = { code: letter for letter, code in letter_to_code.items() }


Reorganizing app.js to put related initialization steps together

You can always move the require() call for middlewares up. You're not doing anything with the returned value from calling it on app.

var middlewares = require('./middlewares/config');

app.set(.....)

app.use(.....)

middlewares(app)

I'm assuming prototypes does some hacks with the global namespace. If so, then there's not much you can do about it. That's not really good practice though.


Search for string in many WBs and post results into another WB

Variables

Good job is making sure to declare all variables with a type:

 Dim wb1 As Workbook, Wb2 As Workbook

However, there's no real reason to group your variables like that; as you see with your strings it would get too long.

More on variables - give them some meaningful names. And avoid that hungarian naming:

Dim sourceWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet
Dim searchValue As String
Dim foundAddress As String
Dim foundRow As Long
Dim searchArray As Variant

Oh no, you didn't declare these variables:

  cellA = ws2.Cells(fRow, 1).Value
  cellB = ws2.Cells(fRow, 2).Value
  cellC = ws2.Cells(fRow, 3).Value
  cellD = ws2.Cells(fRow, 4).Value
  cellE = ws2.Cells(fRow, 5).Value
  cellF = ws2.Cells(fRow, 6).Value
  cellG = ws2.Cells(fRow, 7).Value

Why not use a range or an array? Seems like it will always be columns 1:7. Something like

For Each f In searchRange 'or your specific range
    Set f = searchRange.Find(searchValue, LookIn:=xlValues)
    If Not f Is Nothing And f.Address <> fAddress Then
        ws1.Range(Cells(pasterowindex, 1), (Cells(pasterowindex, 7))) = ws2.Range(Cells(fRow, 1), (Cells(fRow, 7)))
    End If
Next

But with better variables. I also dislike Do loops and stick to For Each loops, but that's my preference. It also can avoid the With block - you're nesting too many things, I think.

You also missed declaring these: dmr, pasteRowIndex

But I don't see you ever actually using dmr?

When you don't define your variable, VBA will declare it as a Variant, which are objects:

  Performance. A variable you declare with the Object type is flexible
  enough to contain a reference to any object. However, when you invoke
  a method or property on such a variable, you always incur late binding
  (at run time). To force early binding (at compile time) and better
  performance, declare the variable with a specific class name, or cast
  it to the specific data type.

By not declaring variables, you could possibly be paying a penalty.

Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.

Additionally, I have no way of telling what dmr is. Plus first it's a workbook and then it's a range - the only reason it's working is because you didn't declare it and it's inherently a variant. Get two variables with good names in there!

Plus, what's this?

dim ws2 as worksheet
Set ws2 = wb1.Sheets("MAIN SCREEN").Range("A5:G2000")

Setting a worksheet variable to a range? Also why does ws2 reference wb1 and vice-versa? I got really confused on what the source and target actually are.

Praise

Great job using vbNullString instead of " ".
Good job using a Long instead of Integer. Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.
Good job following Standard VBA naming conventions

Misc

When you do this

 ws1.Range("A5:G2000").ClearContents

You already gave the book and sheet a variable, just give this a range variable - it will make the code look cleaner. Additionally if you're using 2000 because you don't know how big the range is,
there is a standard way to find lastRow and lastColumn. That post explains why.

What is this spacing about -

 Set Wb2 = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\OfficerA.xlsx")
  Set wb1 = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\Mainwb.xlsm")
   Set ws2 = wb1.Sheets("MAIN SCREEN").Range("A5:G2000")
   Set ws1 = Wb2.Worksheets("DATA")

Be sure you align your levels:

Set Wb2 = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\OfficerA.xlsx")
Set wb1 = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\Mainwb.xlsm")
Set ws2 = wb1.Sheets("MAIN SCREEN").Range("A5:G2000")
Set ws1 = Wb2.Worksheets("DATA")

Also, what happens if the book isn't found or the sheet doesn't exist? Handle those errors!

Same goes for a space in the inputbox - " " <> vbNullString

Also why are you doing this -

strSearch = TextBox1.Value
...
strSearch = InputBox("Please enter T24 ID:", "Search Value")

I don't see that TextBox1 ever being used.

My version

Would look something like this -

Option Explicit

Sub CommandButton1_Click()

Dim sourceWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet
Dim sourceRange As Range
Dim targetRange As Range
Dim searchCell As Range
Dim searchValue As String
Dim targetRow As Long
targetRow = 5
Dim lastRow As Long

On Error GoTo ErrHandler

Set sourceWorkbook = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\OfficerA.xlsx")
Set sourceSheet = sourceWorkbook.Worksheets("DATA")
lastRow = sourceSheet.Cells(Rows.Count, 1).End(xlUp).Row
Set sourceRange = sourceSheet.Range("A5:G" & lastRow)

Set targetWorkbook = Workbooks.Open("C:\Users\elhayani\Desktop\development\AML db\Mainwb.xlsm")
Set targetSheet = targetWorkbook.Sheets("MAIN SCREEN")
Set targetRange = targetSheet.Range("A5:G" & lastRow)
targetRange.ClearContents

searchValue = InputBox("Please enter T24 ID:", "Search Value")
If searchValue = vbNullString Or searchValue = " " Then Exit Sub

For Each searchCell In sourceRange 'or your specific range
    Set searchCell = sourceRange.Find(searchValue, LookIn:=xlValues)
    If Not searchCell Is Nothing Then
        targetSheet.Range(Cells(targetRow, 1), (Cells(targetRow, 7))) = sourceSheet.Range(Cells(searchCell.Row, 1), (Cells(searchCell.Row, 7)))
        targetRow = targetRow + 1
    End If
Next
Exit Sub

ErrHandler:
    MsgBox "WHOOPS"

End Sub

Advanced

Your way of doing the loop to .Find the search value is pretty complicated considering you can just .FindNext and avoid the loop altogether, but I know that's a lot to take in right now.