Find Start/Stop Indices Where Array Is True

Enumerate

for i in range(len(y)): is an antipattern.  If you want indices (i) and the values at those indices (y[i]) the Pythonic way is using enumerate:

for i, yi in enumerate(y):

Start indices

Let's take a moment and split this task into two parts: the start indices and the stop indices.  First, the start indices:

start = []
if y[0]:
    start.append(0)
for i in range(len(y)):
    if y[i] and not y[i-1]:
        start.append(i)

That almost looks like it could be replaced by list comprehension ...

start = [i for i, yi in enumerate(y) if yi and not y[i-1]]

... except for that y[i-1] part, which may wrap around and grab a value from the end of the array.  What you really want to do is zip the y[i] and y[i-1] sequences together.  We just need to start the y[i-1] sequence off with a leading False value:

start = [i for i, (y1, y2) in enumerate(zip([False] + y[:-1], y)) if y2 > y1]

Stop indices

The stop indices are similar, zipping y[i] with y[i+1] with a trailing False:

stop = [i for i, (y1, y2) in enumerate(zip(y, y[1:] + [False])) if y2 < y1]

Groupby

And now for something completely different.

itertools.groupby() takes sequential items with matching keys, groups them together, and emits them together with their key.  We just need the True and False values to be the key, and attach the index numbers to the True/False values.

>>> [list(group) for key, group in groupby(enumerate(x), key=lambda ix: ix[1])]
[[(0, True)],
 [(1, False), (2, False)],
 [(3, True), (4, True), (5, True)],
 [(6, False)],
 [(7, True)],
 [(8, False), (9, False), (10, False)],
 [(11, True), (12, True)],
 [(13, False)],
 [(14, True)]]

(output reformatted to show one inner list per line, for clarity)

But we only want the groups where the key is True:

>>> [list(group)
...  for key, group in groupby(enumerate(x), key=lambda ix: ix[1])
...  if key]
[[(0, True)],
 [(3, True), (4, True), (5, True)],
 [(7, True)],
 [(11, True), (12, True)],
 [(14, True)]]

For each group, we want the first and the last items in the group:

>>> [[group[0], group[-1]]
...  for group in (list(group)
...                for key, group in groupby(enumerate(x),
...                                          key=lambda ix: ix[1])
...                if key)]
[[(0, True), (0, True)],
 [(3, True), (5, True)],
 [(7, True), (7, True)],
 [(11, True), (12, True)],
 [(14, True), (14, True)]]

Actually, we only want the indices stored in those items:

start_stop = [[group[0][0], group[-1][0]]
              for group in (list(group)
                            for key, group in groupby(enumerate(x),
                                                      key=lambda ix: ix[1])
                            if key)]

Which gives:

>>> start_stop
[[0, 0], [3, 5], [7, 7], [11, 12], [14, 14]]

In the comments, Graipher suggests:

  Personally, I would make getting the groups a generator expression assigned to a variable and then iterator over that in a list comprehension ...

from itertools import groupby
from operator import itemgetter

groups = (list(group) for key, group in groupby(enumerate(x), key=itemgetter(1))
                      if key)
start_stop = [[group[0][0], group[-1][0]] for group in groups]

  ... using operator.itemgetter (instead of the lambda ix: ix[1]) for some more readability.

In the comments, RootTwo suggests:

  This could be simplified by grouping the indices directly instead of using enumerate:

[(group[0], group[-1]) for group in (
 list(group) for key, group in groupby(range(len(x)), key=x.__getitem__) if key)]

Timings, for a list of 15,000,000 entries (the original x list, replicated one million times):

Original:   7.3 seconds
AJNeufeld:  6.4 seconds
Graipher:   5.5 seconds
RootTwo:    3.1 seconds


I think your code is very nice, succinct, and ruby-like.

Two minor issues -

Your bonus code is a bit over-sophisticated, which makes it not very readable, and quite brittle. Although it won't fit in one line - a case solution will be more suitable here:

def bonus(num)
  case num
  when 1 then 100;
  when 5 then 50;
  else 0;
  end
end

Also, in score I personally think that separating the score calculation from its aggregation is more easy on the eyes:

(1..6).map { |n| points(dice, n) }.inject(:+)

although, I admit, it is more a matter of taste than anything else...

As for your suspicion about not having to pass dice to points, I don't see a straight-forward way of doing that, or a proper motivation for doing it.

Perhaps you want to be able to simplify your block into a straight forward method call (using a syntax like .map(&some_method)) - for that you can use proc's curry method, but it actually results in a very awkward code, which does not seem to be worth it:

def score(dice)
  (1..6).map(&lambda(&method(:points)).curry[dice]).inject(:+)
end

Perhaps you want to decouple the point calculation methods from the dice array altogether. This can be done easily enough by passing dice.count(n) instead of dice, as that is all the points actually cares about, although this solution will break as soon as point calculation will need more information...

def score(dice)
  (1..6).reduce(0) { |sum, n| sum + points(n, dice.count(n)) }
end

def points(num, count)
  ((count / 3) * triple(num)) + ((count % 3) * bonus(num))
end


CRC without knowing the data type or size

Its always informative to comment the specific crc polynomial. An 8 bit crcs is only marginally better than 8 bit checksum.

First, remove the malloc() and memcpy(). A crc is a calculation that does not affect the input data. There is no need to allocate and copy the input data. Also, your code has a memory leak because its not releasing the allocated memory.

Second, just read each byte and update the crc calculation. There is nothing to gain with an arbitrary restriction on the input data size.

Third, replace the bit by bit calculation loop with a byte wide calculation.


Python program to get the longest substring of the same character

I really like @Justin's answer, but I'm new here so I unfortunately cannot comment or upvote yet. So instead I'll take this opportunity to detail his answer in relation to your question.

The first thing to note, the methodologies of your (@enoy) solution and @Justin's is entirely different. Your solution is recreating the longest substring of the given string, then returning the length of the recreation. @Justin's solution is using simple math. To lay out the steps:

Create a beginning index, start at 0.
Traverse from the beginning index until the current letter and the previous letter are no longer the same. Record the index of the last letter that was repeating as an end index.
Subtract the two indexes
store the length in a variable, maybe called longest_length.
replace the beginning index with the end index + 1 (plus one because you want the rest of the input string and none of the previous substring)
repeat steps 2 and 3.
store the max of the longest_length and the length that was just found.
keep repeating 5 - 7 until the end of the input string
return longest_length

So with the steps lain out and clear, to answer your question:

  What could be improved?

If all you care about is the length of the longest substring, there shouldn't be a reason for you to recreate the substring in order to find its length. In terms of complexity, your space complexity is broken down like this:

substrings = [] - Since you're simply splitting the input string into substrings and storing them all into an array, this will always have a space complexity of \$n\$, where \$n\$ is the length of the input string.
current_substring = "" - If the entire input string is repeating, this can potentially be as large as \$n\$, where \$n\$ is the length of the input string.
lengths = [] - If the entire input string does not have a single repeating substring, this can potentially be as large as \$n\$, where \$n\$ is the length of the input string.

So all in all, you have a big O space complexity of \$O(3n)\$ or \$O(n)\$ (for something small like this I prefer not to simplify constants).

Where as @Justin's solution breaks down as so:

begin_index - Only stores a single value at any given time.
end_index - Only stores a single value at any given time.
longest_length - Only stores a single value at any given time.

So you can see how much smaller this is already, and in terms of big O space complexity, it's \$O(3)\$ or simplifies to \$O(1)\$.

All that was space complexity though, as for time complexity:

Let's start with your code breakdown again:

You traverse the input string once, to split each substring and record their lengths, so that time complexity is \$n\$, where \$n\$ is the length of the input string.
You then have to traverse your array lengths, and find the max using the max function, and if there's no repeating substring, that can potentially be \$n\$, where \$n\$ is the length of the input string.

So all in all, the time complexity is \$O(2n)\$

For @Justin's:

Traverse the list once, checking the max length of each substring as they're built so that's \$n\$, where \$n\$ is the length of the input string.

It's unavoidable, traversing the list at least once when doing anything involving comparisons, but you can see how work could have been combined into one loop, rather than two separate ones here.

And on closing notes, @Justin's solution can be easily adapted to store the substring simply with a variable named longest_substring = input_string[begin_index:end_index] if the longest_length variable changes. This is much smaller space than having an array of all substrings.

Here is @Justin's answer I was talking about (which got deleted) -

# Function to return the ending index for the
# largest valid subsring starting from index i
def end_of_uniform_substring(string, n, i):
    i += 1
    while (i < n):
        current = string[i]
        previous = string[i - 1]
        #if the current character in the string
        #is equal to the previous character
        if (current == previous):
            i += 1
        else:
            break
    return i - 1

# Function to return the length of the
# longest substring of consecutive
# repeating letters in string
def largest_substring(string, n):
    length = 0
    i = 0
    while (i < n):
        # Valid substring exists from
        # index i to end
        end = end_of_uniform_substring(string, n, i)
        # Update the length
        length = max(end - i + 1, length)
        i = end + 1
    return length

Hope this helps!


JavaScript - prototype, getters, setters, functions

Though dynamic, you should not force JavaScript it to use complicated patterns that aren't worth the hassle. In your case, the code you want can be simplified into:

var people = [];

people.push({
  id: 1,
  name: "John",
  surname: "Smith"
});

people.push({
  id: 2,
  name: "Bob",
  surname: "Doe"
});

Another thing is that JavaScript has no natural concept of privacy (save closures of course). So when doing some prototypal OOP, almost everything is public. Getters and setters might not hold much purpose.

The key to a big JavaScript app is to never make it big in the first place. Keep components small, simple and easy to debug in case they go wild. Additional baggage will drag you down eventually.

Also, I suggest you don't modify native methods. Though it's common that developers do override some of them, like toString(). But some other code might use it in a way that it expects the native functionality. A general rule in JS is don't modify objects you don't own.


Setters dependent on other instance variables in Java

Allowed?
Yes. There seems to be nothing technically wrong with your code.
Good practice?
No.
Specifically, in your example code setPddocument is not actually a setter.
It is a load / initialize function, that does not set a value in the object, but instead performs an operation under the assumption a certain value (bytearray) has already been set.
It would be better off named init or load, and you probably should set up some code to check if there is a valid array, throwing a different exception in that case. (Like InvalidStateException).
setLastPage is also more of an initializer then a setter.
There, you have no error checking at all, so if it is called before setPddocument your program will crash.
While it is possible to have non-trivial setters that modify several instance variables, the general rule of thumb is: if it does not receive a value from outside to do its job, it is not a setter.


Reimplementing Python's enum.auto() for compatibility

The easiest solution would be to use the aenum1 library, which is drop-in compatible with the stdlib and also has some advanced features not found in the stdlib.  It also works in Python versions 2.7 and 3.3+.

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.


Combining contents of files by reading them in a human ordering

NewLine

The newline at the end is correct... at least according to your code.

Files.lines(...) ignores the last line of input files if it has no characters. This is a standard system to have for most operating systems (the last character in a text file is a newline).

Your code is perpetuating this process, and it always adds a newline after each line printed.

Thus, your file always ends up with a newline at the end. This is a good thing.

Exceptions

Java Lambdas cannot contain expressions that throw caught exceptions. This is a weakness. The weakness is so sever that as part of Java8, there is the new Exception UncheckedIOException so that IO-based operations can throw an unchecked exception.

The easiest way to use it is to change your catch blocks to:

private Stream<String> wrappedLines(final Path path) {
    try {
        return Files.lines(path);
    } catch (IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
}

The alternative is to wrap the exception inside the lambda with:

    try (BufferedWriter writer = Files.newBufferedWriter(directory.resolve("masterjob.script"))) {
        Files.list(directory)
                .filter(path -> Files.isRegularFile(path))
                .filter(path -> path.getFileName().toString().matches("job\\d+.script"))
                .sorted(Comparator.comparingInt(this::pathToInt))
                .flatMap(try { this::wrappedLines } catch(IOException ioe) {throw new UncheckedIOException(ioe)})
                .forEach(string -> try {wrappedWrite(writer, string)} catch(IOException ioe) {throw new UncheckedIOException(ioe)});
    }

General

The Java8 side of this otherwise looks OK, and works fine for me too.


Rotate a given number of variables in-place

Issues (for me)
I get a couple of errors when I try and compile.
This error I have a feeling is caused because you are using a more up to date compiler (I presume this is a C++17 feature).
if constexpr (sizeof...(Tail) > 0) {
   ^^^^^^^^^

This problem causes my second error (because I remove constexpr to make it compile):
rt.cpp:12:6: note: candidate function template not viable: requires at least 2 arguments, but 1 was provided
auto rotate_left_inner(T& first, T& second, Args&... args)

Assuming that constexpr forces that expression to be evaluated at compile time and thus removes that whole block of code. Then it should compile.
Review
You and I differ on how we like to express the return value. I believe we have already had the discussion. So I just want to point it out for other readers.
// You
auto rotate_left(Head& first, Tail&... args)
    -> void

// Me
void rotate_left(Head& first, Tail&... args)

But I don't see anything wrong with yours either, its a simple stylistic thing.
Personally I don't like recursive template meta programming. Two reasons:

This was because when templates were first introduced there was a recursive limit on most compilers. I think this is purely historical now as most compilers have really huge recursive limits now.

Recursive template functions needed a terminating version of the function. But this new constexpr if statement seems to be in response to that. So you no longer need a special case and it can be handled by the compiler.

So it looks like both my reasons for disliking recursive template functions have been addressed by the new version of the language.
But I still prefer the style of the unrolling the argument loop in a function. So I present my version of the same function to show readers how it is done without using recursion (template iterative style).
#include <type_traits>
#include <utility>
#include <tuple>

template<typename T, std::size_t... index>
void rotate_left_inner(T&& tuple, std::index_sequence<index...> const&)
{
    auto tmp = std::move(std::get<0>(tuple));
    auto mover = {0, (std::get<index>(tuple) = std::move(std::get<index + 1>(tuple)), 0)...};
    std::get<sizeof...(index)>(tuple) = std::move(tmp);
}

template<typename... List>
void rotate_left(List&... args)
{
    rotate_left_inner(std::tie(args...), std::make_index_sequence<sizeof...(args) - 1>());
}

#include <iostream>

int main()
{
    int t1 = 5;
    int t2 = 6;
    int t3 = 7;

    rotate_left(t1, t2, t3);
    std::cout << t1 << " " << t2 << " " << t3 << "\n";

    rotate_left(t1);
    std::cout << t1 << " " << t2 << " " << t3 << "\n";
}


Structure

Your IniParser should be the only part of your code that is aware of how the ini file looks internally. That's the whole point of the interface: With it, you can parse different kinds of files (or even retrieve the data from something else). If the file structure changes at some point, you should only ever have to change your IniParser class, nothing else.

But right now, that isn't the case. Your Connection also needs to know how your file looks. To fix this, I would add explicit getters instead of the generic getter you have right now. So you should add getEngine, getHost, etc to your class. This has the added benefit that you can validate them (see that they exist, etc) as soon as you parse the file, instead of when you are using the credentials.

Then of course your naming doesn't make that much sense anymore. So I would rename Parser to ICredentialsParser and IniParser to IniCredentialsParser.

You might also think about passing the names of keys to it as well instead of hardcoding them inside the parser.

If you do all this, your Connection class is decoupled from the ini file itself, and also, your IniParser gets more meaning (before, it was more or less only a wrapper for parse_ini_file).

parse and continue

If possible, I would avoid continue. In some cases it makes sense, but most of the time, it makes code harder to read. Your code could look like this:

        if (!$this->isValidated('values', $credentials, $section)) {
            throw new Exception("Values or section doesn't exist");
        } elseif ($key == $section) {
            $this->data = $values;
        }

Misc

your isValidated('values', $credentials, $section) call is inside a loop, but doesn't use the loop variables, so you should move it out of the loop.
I would create separate isValidated functions, as they don't share any common code (the way you do it just complicates things). You can name them isValidFile and hasSection.
naming: most of the time, I see open and close for the operations you are naming initialize and terminate. Your names are not bad, just unconventional. I would go with the general convention.
naming: isValidated would sound a bit better as isValid.
isValidated should probably be private.
in PHPDocs, it's always good to write why an exception is thrown.


Pointer to vector?

You have two members: a pointer to a vector (which you new, but never delete, which leads to several other problems) and its size. But you're already using a vector, so just do it twice:

std::vector<std::vector<int>> adjacency_vector;

Graph(int num_vertices)
: adjacency_vector(num_vertices)
{ }

Pointer to pair?

Similarly, for addEdge, take a vector of pairs - not a vector of pointers to pairs - and by reference to const:

void addEdge(std::vector<std::pair<int, int>> const& edge_list)

And then just use a range-based for expression to add them all:

for (auto const& edge : edge_list) {
    adjacency_vector[edge.first].push_back(edge.second);
}

Pointer to bool?

You see a trend here, hopefully. In your BFS, you start with:

bool* visited = new bool[this->num_of_vertices]();

But you never delete it, so you're leaking that memory. Prefer:

std::vector<bool> visited(adjacency_vector.size());

Also, this already sets everything to false, so you don't have to manually. Though your original implementation did as well.

What does BFS do?

This is a void function, that does something with local variables queue and visited - and then what? What as the outside observer do I get? This function needs to return... something of value to the caller. Otherwise, it's just spending time doing nothing.

Also, again, prefer range-based-for for the push:

for (auto child : adjacency_vector[start]) {
    if (!visited[child]) {
        queue.push(child);
    }
}

It's just much shorter.


Felice, can you expand on what you are looking for?  Are you trying to infer constraints to be applied dynamically?  I looked at your link to the whole code base at bitbucket.

First of all, nice work.  Looks like you spent a good deal of time whipping that up.

On the surface, given your demo and not knowing what exactly your intended use case is, it appears 1) that you are trying to make constraints more visually fluent (which I appreciate) and 2) it seems "possibly" unneeded.

Once you further expand on your use case, I'm sure it will make more sense and I can revise my statements.  However, for now let me explain item #2.  1) You can add the fluency you require by refactoring your code base into helper methods.  2) I would not really recommend throwing exceptions from what I can see.  Given the code sample below (from your Contracts.cs) you are throwing an exception on something that should merely be a boolean check.  As such you are altering the behavior of what you normally come to expect out of a programming language.

public IContract<T> IsEqual<TT>(TT of) where TT : T,IEquatable<TT>
{
    TT actual = (TT)accessor();
    if (!actual.Equals(of))
    {
        throw new ArgumentOutOfRangeException(Name, "Must be equal to" + of.ToString());
    }
    return this;
}

3) I would recommend watching out for "re-inventing the language".  Sometimes it is hard to identify, but the general smell is that you try to recreate basic functionality in the toolset you already use, instead of just using what you have.  This can result in double/triple programming.  Let's use the demo example from above (focusing on the snippet I grabbed).  You have built several methods to provided the ".IsNotNull()" method for the Contract and are then encapsulating that (to make it more readable and fluent) into a method that just takes the parameter.

/// <summary>
/// Classical not null verification
/// </summary>
/// <param name="arg1"></param>
public void DoSomething(string arg1)
{
    Contract.Expect(() => arg1).IsNotNull();
}

instead of just:

if (arg1.IsNullOrEmpty())

or

if (arg1.IsNullOrWhiteSpace())

Which are already built into the .net framework.

I hope some/all of this helps.  If you would, please further explain your use case.  As for now, my recommendation would be to refactor your utility into static helper methods and not throw exceptions.  For the error message part, just create helper method(s) to get the error message needed.  So 1 method does the needed check and if it fails...and as a programmer you want to get the error message, you can choose to do that in a separate call.


Inputs equality check using jQuery without plugins

Switch to the native DOM methods like getElementById, which is orders of magnitude faster and you can keep input:

$('[data-equal-to]').on('input', function() {
  var target = document.getElementById(this.dataset.equalTo);
  var isEqual = !target || target.value == this.value;
  this.setCustomValidity(isEqual ? '' : this.dataset.msgError);
});

You can also debounce the verification by 200ms, for example:

;(function() {
  var timeout;

  function validateEquality(element) {
    var target = document.getElementById(element.dataset.equalTo);
    var isEqual = !target || target.value == element.value;
    element.setCustomValidity(isEqual ? '' : element.dataset.msgError);
  }

  $('[data-equal-to]').on({
    input: function() {
      clearTimeout(timeout);
      timeout = setTimeout(validateEquality, 200, this);
    }),
    blur: function() {
      clearTimeout(timeout);
      validateEquality(this);
    }),
  });
})();

You can also make this a jQuery plugin.

As for mirroring the check for the target element, the preferable approach is to explicitly declare data-equal-to attribute on both input elements that points to the other one. But you can also do it implicitly by adding equalOf expando property pointing to the linked element so you can re-triggering input event on it:

$('[data-equal-to]')
  .on('input', function() {
    var target = document.getElementById(this.dataset.equalTo);
    var isEqual = !target || target.value == this.value;
    this.setCustomValidity(isEqual ? '' : this.dataset.msgError);
  })
  .map(function() {
    var target = document.getElementById(this.dataset.equalTo);
    target.equalOf = this;
    return target;
  })
  .on('input', function() {
    $(target.equalOf).trigger('input');
  });


Ten thousand and first prime checker takes a very long time

The square root calculation could just be done before the loop.  Since this value does not change within the function, it doesn't need to be recalculated each time through the loop.

public static boolean isPrime(int num) {
    if (num % 2 == 0) return false;

    int squareRoot = Math.floor(Math.sqrt(num));
    for (int i = 3; i < squareRoot; i += 2) {
        if (num % i == 0) return false;
    }

    return true;
}


Naming the parameters prev and prevPrev is weird.  Why not current and prev?

You shouldn't need the curly braces here for a function that consists of a single expression:

def fibonaccis(max: Int): List[Int] = fibonaccis(max, 2, 1)

Conventionally, the Fibonacci sequence is said to start like

$$1, 1, 2, 3, 5, 8, \ldots$$

or

$$0, 1, 1, 2, 3, 5, \ldots$$

Your fibonaccis(13) would produce List(1, 2, 3, 5, 8), which I would consider to be missing the first element.

The Fibonacci sequence is an infinite sequence.  It would be a shame to limit it to a max value.  The most idiomatic way to model it in Scala would be using an infinite lazy stream, just as suggested in the documentation:

def fibFrom(a: Int, b: Int): Stream[Int] = a #:: fibFrom(b, a + b)
val fibonaccis = fibFrom(0, 1)

Alternative implementation:

val fibonaccis: Stream[Int] = 0 #:: 1 #:: fibonaccis.zip(fibonaccis.tail).map(
    n => n._1 + n._2
)

Then, you could do fibonaccis.takeWhile(_ < 13).toList to obtain List(0, 1, 1, 2, 3, 5, 8).


Linked list operations for a competition

Rename Node.add to setNext, since its a setter method:

public void setNext(final Node node) {
    this.next = node;
}

Create a constructor with only the value parameter:

public Node(final int value) {
    this.value = value;
}

and call this in your main method instead of passing nulls:

final Node head_list1 = new Node(1);

Do not use public fields:

public int value;
public Node next;

Make them private and provide getters and setters.

The value field could be final:

public class Node {
    private final int value;
    ...
}

It should not change, so protect it with final.

Instead of the main method write self-checking unit tests. The posted main should be separated to two test.

The Node class shouldn't be responsible for printing. It should return a String instead of System.out.print() calls. Maybe another client wants to write it to a file or a socket, but System.out.print() made it impossible.

Declare only one variable per line.

    while (current != null) {
        System.out.print(current.value + "->");
        current = current.next;
    }
    if (current == null) {
        System.out.println("END.");
    }

The current == null condition seems always true, so it's unnecessary:

    while (current != null) {
        System.out.print(current.value + "->");
        current = current.next;
    }
    System.out.println("END.");

Check input:

public static Node twist(final Node head) {
    if (head == null) {
        throw new NullPointerException("head cannot be null");
    }
    ...
}

It's unnecessary to set default value for all variables to null:

Node newHead = null;

Furthermore, it could be final since it get its value before it will be used:

final Node newHead;

Read Effective Java, Second Edition, Item 45: Minimize the scope of local variables. (Google for "minimize the scope of local variables", it's on Google Books too.)

For example, tempNext should be declared inside the else branch:

else {
    final Node tempNext = current.next;
    current.next = prev;
    if (branchHead != null) {
        branchHead.next = current;
    }
    prev.next = tempNext;
    current = tempNext;
}

Use camelCase variable names: head_list1 -> headList1. (Effective Java, Second Edition, Item 56: Adhere to generally accepted naming conventions)


A couple of points to consider:

Calling your function shuffle instead of random would be a better name since that's really what it's doing.
The extra intermediate tables aren't really necessary to perform the shuffle. A single table is enough and you can perform the shuffle in-place right on that table.
Consider a better separation between the process of shuffling and how the input is stored. For example, if you have your shuffle function take a table instead then that function can be reused on any kind of data and not just strings.
I would do away with the Hungarian notation and just drop the type prefix on the variable names. Remember Lua variables themselves doesn't have a type. If you later change what that variable refers to then the Hungarian notation becomes misleading.

So I would refactor your original code into two functions. Here's one possibility:

function shuffle(self)
  if type(self) ~= 'table' then return nil end

  for i = #self, 2, -1 do
    local randi = math.random(i)
    self[i], self[randi] = self[randi], self[i]
  end
  return self
end

function shuffle_words(str)
  local strtable = {}
  for each in str:gmatch("%a+") do
    table.insert(strtable, each)
  end
  return table.concat(shuffle(strtable), ' ')
end


First off you if we look at the main of your code, it's mostly all the same pattern.

while True:
    text = input().upper()
    if ...:
        break
    else:
        print()

You should make that a function. And then call it.

def get_input(message, error_message, fn):
    while True:
        text = input(message).upper()
        if fn(text):
            return text
        else:
            print(error_message)

This severely reduces the amount of code needed.
The way you use this new function is:

mode = get_input(
    'Type E for enryption mode or D for decryption mode : ',
    'You must enter E or D ! ',
    lambda mode: mode in 'DE'
)

text = get_input(
    'Enter your text : ',
    'You can not leave it blank ! ',
    lambda text: text
)

If you have not come across lambda before it's a way to make small functions.
For example, the following are the same:

my_fn = lambda a: len(a) - 1

def my_fn(a):
    return len(a) - 1

You should also note that I replaced mode == 'D' or mode == 'E' to mode in 'DE'.
It's much easier to add to this if you need to.
So if you add say 'A' as a function, you can change it to mode in 'ADE'.

Also in Python you should use if text rather than if len(text) != 0.
This is as empty objects are False, and others True. E.g.

>>> bool('')
False
>>> bool('a')
True
>>> bool([])
False
>>> bool(['a'])
True

Now onto the bit that is a bit more challenging.
To make a function to check if you can change the input into a number, using int, we can't use lambda.
to do this you need to make a 'proper' function.
Alternately you can use str.isdigit. (Thanks @SuperBiasedMan)

def int_able(string):
    try:
        int(string)
        return True
    except ValueError:
        return False

key = int(get_input(
    'Enter a key : ',
    'You must enter an integer number ! ',
    int_able
))

# Or
key = int(get_input(
    'Enter a key : ',
    'You must enter an integer number ! ',
    lambda text: text.strip().isdigit()
))

When calling a function you should always pass it arguments.
caesar() is a bad design.
For a simple script like this it's alright,
however it's not a good habit to get into.
Instead, I would recommend that you call it with caesar(text, key).
I would re-write your modes to:

if mode == 'D':
    key = -key

caesar(text, key)

As I recommended you change caesar you will need to change the arguments you pass to it.

You shouldn't add to the letters_table, that should stay the same.
If you need to add more letters then you should add them in the definiton.

If you make letters_table a constant, then you can change it to a string.

You should change your loop from for letter in range(len(text)) to for letter in text.

Your algorithm can be changed to one line, and if step < 0 should never happen.

And you should probably remove the if position > 25 it's not a good idea,
just add letters to letters_table.

I would discourage print(..., end=''), instead make a string.

And so I would re-write your code to:

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def caesar(message, key):
    caesar_text = ''
    for letter in message:
        caesar_text += LETTERS[(LETTERS.index(letter) + key) % 26]

    print(caesar_text)

Note: I don't add to LETTERS if you need to add more then hard-write them in.

To note, I didn't read your comments, there were to many,
and not meaning to be rude, but I can read Python, in fact it's more straightforward than English at times.

# If step is lower than 0 then we need to add 26,
# to it to complete the decryption process.
if step < 0:
    step += 26

I know which is easier, and faster, to read by far.

But all in all you have nice code, reduce the amount of comments, and pass argument and you'll do great.


Function to get specified key from /proc/cpuinfo

Useless use of cat
Grep can open files all by itself, cat isn't necessary in most circumstances. Also, quote everything - that's save you some debugging when you need to handle spaces in them - like for the "model name" property.
target_line=$(grep -m1 ^"$1" /proc/cpuinfo)

-m1 to stop at the first match, so you won't get weird results when you run your script on a machine with more CPUs. That's not portable unfortunately (not in POSIX), so if you don't have that, the usual options are: pipe to head -n 1, use awk instead and exit early, sed and exit early. The latter two can do it all in one go too.
Use your shells string manipulations for simple things
Assuming you want everything after the :, you can simply do:
value="${target_line##*: }"

See How do I do string manipulations in bash? for more like this, or the POSIX parameter expansion reference.
function keyword not necessary
It's less portable and doesn't buy you anything, so just omit it. See difference between “function foo() {}” and “foo() {}” for more details.
Variable names don't need to be in all caps
Personal preference of course, but especially for locals, lowercase is good - keep uppercase for globals/environment variables.
So:
get_cpuinfo_prop () {
  target_line=$(grep -m1 ^"$1" /proc/cpuinfo)
  echo "${target_line##*: }"
}


Optimization of General Purpose Makefile

Instead of defining your own compiler variable, I would override the implicit CXX variable. This also goes for the implicit CXXFLAGS (instead of your ccflags).
This allows other users to easily change the compiler used when using a different environment than you.
You might also want to remove all the leading @ in favour of make -s


Concise way of "updating" element in nested collections

I think you need an id field to be sure that you're updating the correct combatant. I assume it's possible to have multiple combatants with the same hp and attack.
And in that case it makes sense to store a group as a Map of id to combatant. This makes it really simple to update a value by id and there's no need to check for existence first. See the tryUpdateCombatantById function below.
You can add small helper functions to update specific record fields with a function that is passed in.

Here's the code with all of those changes:

type Combatant = {
    id : int
    hp : int
    attack : int
}

type Battle = { combatantGroups : Map<int, Combatant> list }

let updateHp f combatant = { combatant with hp = f combatant.hp }
let removeHp attack = updateHp (fun hp -> hp - attack)

let tryUpdateCombatantById combatantId f group =
    group
    |> Map.tryFind combatantId
    |> Option.map (fun c -> group |> Map.add c.id (f c))
    |> Option.defaultValue group

let applyAttack targetId attacker battle =
    { battle with
        combatantGroups =
            battle.combatantGroups
            |> List.map (tryUpdateCombatantById targetId (removeHp attacker.attack)) }


It's probably worth accepting a second template argument for an Allocator to be passed through to the std::deque:

template<class T, class Allocator = std::allocator<T>>
class ThreadSafeDeque {
    std::deque<T, Allocator> deque;
};

Technically, we do need to include <condition_variable>; we're not allowed to assume that <mutex> always pulls it in.

I don't like the interface to pop_front_waiting() - why does the caller have to pass an lvalue reference, instead of simply being returned the value?  Return-value optimisation will ensure there's no unnecessary copy.

The locking logic all looks good to me.  We can avoid the lock.unlock() by using a simple lock-guard with smaller scope:

void push_back(const T &t)
{
    {
        std::lock_guard<std::mutex> lock{ mutex };
        deque.push_back(t);
    }
    condition.notify_one(); // wakes up pop_front_waiting
}

From C++17, we can use constructor deduction and omit the template parameter from std::lock_guard and std::unique_lock, making the code a little easier to read.

It's helpful to show that members are intentionally default-constructed, and it pacifies g++ -Weffc++:

std::deque<T> deque = {};
std::mutex mutex = {};
std::condition_variable condition = {};


Bug 1

Requirement is 'without producing any duplicates'. You have not exactly implemented this (although the chances of happening are really small)

Bug 2

You have no condition of exiting. The program will run forever, and might have inconsistent behaviour if you terminate it externally.

A: Is this an efficient way of generating the tokens?

It can be more efficient.

You can keep the File and Writers open instead of opening each time.
You can reuse the new Random() instead of creating one each time, or..
...use int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
You can use a fixed for loop instead of checking the salt.length().

Also use try-with-resources.

B: How can I call this method using threads to generate them faster

As you write to file, this process will finally be I/O bound, so there is probably no real gain from multi-threading.


There are a few problems with this; mainly that you only support the letters a, b, and c. It isn't necessarily a problem if those are the only letters you'll ever get, but what is a problem is that you're making identical variables, with identical behavior, for each letter. Then for every letter you want to add in the future, you have to repeat yourself. Anytime you see yourself with a pattern like this, it is screaming for you to use a dictionary, or situationally a list of lists.

Making that change, we'd end up with something like this

counter = {}
for letter in my_list:
    if letter not in counter:
        counter[letter] = 0
    counter[letter] += 1

largest = 0
best_letters = []
for letter, count in counter.items():
    if count > largest:
        largest = count
        best_letter = [letter]
    elif count == largest:
        best_letter.append(letter)

print()
for letter in best_letters:
    print("Letter which repeats the most is: {}".format(letter.upper()))

Now we don't need the separate logic for each possible letter; we also don't need that hacky loop where you find the largest and then loop through.

We can make this better though, as you implied with collections.Counter. A Counter already does a lot of this work. For example, to get the count we just do

counter = Counter(my_list)

Then to get the best one, we just do

best_letter, largest = counter.most_common(1)[0]

This makes your total program look like this

best_letter, _ = Counter(my_list).most_common(1)[0]
print()
print("Letter which repeats the most is: {}".format(best_letter.upper()))

In general, it is always good to write functions to encapsulate behavior, but in this case you can probably just inline the use of the Counter.

Now if we want to get all of the letters that are most frequent, we can change it pretty easily. We'll do this instead:

most_common = counter.most_common(len(counter))
largest = most_common[0][1]

for letter, count in most_common:
    if count < largest:
        break

    print("Letter which repeats the most is: {}".format(letter.upper())

That'll grab all of values in the order of most to least frequent, and then you loop through all of the ones that are most commonly seen. Note that there is no implicit sorting within the ones that share a frequency; if you want further constraints on that it'll take additional logic.


Yes, you can reduce the number of $.each(), and also simplify the whole code, in several ways.

Note that to improve readability I replaced some variable names:

. data replaced by source (to avoid confusing with data members in objects)

. d replaced by objSet inside of functions (more significant, as it is really a set of obj)

. all i and j replaced by index (more significant, and don't need to be different inside of different functions)

. tempData --> result

That's said, the first simplification come from the fact you don't need to iterate three times on the (now said) source, because there is no interaction between different objSets of source.
So instead of:

var tempData=[];
$.each(data, function (i, d) {
  // first step
});

$.each(data, function (i, d) {
  // second step
});

$.each(data, function (i, d) {
  // third step
});

it becomes:

var result=[];
$.each(source, function (index, objSet) {
  // first step
  // second step
  // third step
});

Then we can simplify each step...

Computing total can be achieved without $.each so this step:

var total = 0;
$.each(d.data, function (j, obj) {
    total += parseInt(obj.value);
});
d["total"] = total.toString();

can be achieved using reduce():

  objSet.total = objSet.data.reduce(function(total, obj) {
      return total + parseInt(obj.value);
  }, 0);

or even simpler in ES6:

objSet.total = objSet.data.reduce((total, obj) => total + parseInt(obj.value), 0);

The second step can use map() instead of $.each(), and also be slightly alleviated avoiding the temporary per variable. So rather than:

var percentage = 0;
$.each(d.data, function (j, obj) {
    obj["original"] = obj.value;
    var per = (parseInt(obj.value) * 100) / parseInt(d.total);
    percentage += per;
    obj["percentage"] = per;
    obj.value = (parseInt(d.total) * percentage) / 100;
    obj["under"] = d.under;
});

it can be:

  var percentage = 0;
  objSet.data = objSet.data.map(function (obj) {
    obj.original = obj.value;
    obj.percentage = (parseInt(obj.value) * 100) / parseInt(objSet.total);
    percentage += obj.percentage;
    obj.value = (parseInt(objSet.total) * percentage) / 100;
    obj.under = objSet.under;
    return obj;
  });

EDIT after realizing it could be yet more "compressed" using reduce() instead of map():

  objSet.data.reduce(function (percentage, obj) {
    obj.original = obj.value;
    obj.percentage = (parseInt(obj.value) * 100) / parseInt(objSet.total);
    percentage += obj.percentage;
    obj.value = (parseInt(objSet.total) * percentage) / 100;
    obj.under = objSet.under;
    return return percentage;
  }, 0);

It can be seen as a strange way using reduce(): it's usually employed to give a final result, while here it only avoids declaring a temporary variable for percentage.
Also strange, at first view, is that we keep getting a modified version of objSet.data without map(), because it is directly set.

Finally the third step can take advantage of concat to again avoid using $.each(), so this:

d.data.sort(function (a, b) { return b.value - a.value; });
$.each(d.data, function (j, obj) {
    tempData.push(obj);
});

becomes:

  objSet.data.sort(function (a, b) { return b.value - a.value; });
  result = result.concat(...objSet.data);

To summarize, the whole code can be reduced to this:

var result=[];
$.each(source, function (index, objSet) {

  objSet.total = objSet.data.reduce((total, obj) => total + parseInt(obj.value), 0);

  objSet.data.reduce(function (percentage, obj) {
    obj.original = obj.value;
    obj.percentage = (parseInt(obj.value) * 100) / parseInt(objSet.total);
    percentage += obj.percentage;
    obj.value = (parseInt(objSet.total) * percentage) / 100;
    obj.under = objSet.under;
    return return percentage;
  }, 0);

  objSet.data.sort(function (a, b) { return b.value - a.value; });
  result = result.concat(...objSet.data);
});


Using a certain query field based on state

First of all, use prepared statements.

The account id part is always the same, so extract it to the beginning.

Also, you can extract the isset and not empty part to a function to simplify the code.

$partQuery = 'account_id = '.$account->id;

if(isNotEmpty($phone) && isNotEmpty($email)) {
    $partQuery .= ' AND (phone = "'.(int)$phone.'" OR email = "'.$email.'")';
}
if(isNotEmpty($phone)) {
    $partQuery .= ' AND phone = "'.(int)$phone.'"';
}
if(isNotEmpty($email)) {
    $partQuery .= ' AND email = "'. $email.'"';
}

function isNotEmpty($var) {
    return isset($var) && !empty($var);
}

Although I would assume that that is not actually what you want, as it adds two additional ANDs in case neither phone nor email is empty.

It also seems like an odd query in general. You are fine with a wrong phone number as long as the email is correct and vise versa?

Also note that you don't actually need isset, you can just use !empty, it will not generate a warning.


I think you need to think about inverting control here or you will find limited re-use in this class.  Why would you pass a specifically-formatted POST request here to this class in order to execute validation vs. having calling code just reference methods on this class that execute the validation logic?

For example:

// somewhere outside class
$valid = sanitizer::validateEmail($_POST['email_own']);

By doing this you can make a class like this more re-usable, in that it is not built just to handle POST data validation for a single script.

There is a distinct difference between sanitization and validation. You seem to be using the concepts interchangeably. I would say this class is a validation class not a sanitization class.

From looking at the rules in your class, I actually question if there is really much value here, as really the only validation rule you have here that could not be better fulfilled by built-in PHP validation functionality is you name validation.

You could just as easily use filter_input() or filter_input_array() here.  For example:

// not shown - checking of validation results
$email = filter_input(INPUT_POST, 'email_own', FILTER_VALIDATE_EMAIL);
$voucherDuration = filter_input(INPUT_POST, 'voucher_duration', FILTER_VALIDATE_INT);

This might pretty much eliminate your need for this class altogether.

Some other code review thoughts:

You should strive to use meaningful and specific names for classes, methods/functions, variables, etc. sanitizer as a class name here is very generic, especially since this class has a VERY specific use case that it supports. sanitize() as a method name incorrectly describes what is happening in this method, which is in fact a validation method. clean_up() as a method name doesn't seem to make sense.  What are you "cleaning up"? Don't shorten variable names.  Saving typing a few extra characters is trivial in comparison to having easily understandable code. For example, reg_* properties could be called regex_* to make the meaning much clearer, not just where defined, but also where used in the rest of the code.
Speaking of the regexes. Should these be class constants?  If you don't intend to have these items be mutable (which you don't in this case), don't allow them to be mutable.
You have unnecessary code nesting/branching. In your clean_up() method you could easily combine the first two conditionals and you could invert the conditional to exit early when the condition isn't met, de-nesting the entire rest of the code in the method. In your sanitize() method you could remove the else block altogether by setting null as default value.  As a rule of thumb, the more branching/nesting you have in your code, the more bug-prone it will be, so you should actively look to code it away.
You need to be consistent in your method returns. Your clean_up() method doesn't return anything if the first two conditions aren't met.
You should be consistent in where you write to data structures.  You are breaking the logic up for where you write to $this->clean across two methods.  Perhaps the sanitize method should  not write to this array at all, but rather just perform the regex and return values.
You have some stylistic problems you may want to address:

Classes should be named with first letter in uppercase by convention.
You use inconsistent spacing around assignment operators and flow-control structures.
Don't put comments at the end of lines where they are easily missed. Comments should go on line(s) before the lines they are applicable to.  Also don't add unnecessary comments. Here your comments add no value in understanding the code.


Monte Carlo simulation of amoeba population

Performance

Limiting each trial to 20 generations is not really helpful.  Let's put it this way: the population is expected to increase exponentially with each generation.  Once the population reaches, say, 10 amoebas, it's pretty safe to declare that infection has taken hold and the population will never dwindle to 0.

If you run a trial for 20 generations, you can easily get populations in the thousands.  The problem with letting populations grow so large is that you have to decide the fate of each individual amoeba at each time step, and that ends up being a lot of work.

If you change num_generations_per_trial to 10, you'll get identical results, and finish much more quickly.  But how do you decide what an appropriately low num_generations_per_trial number is?  It would be much more intuitive to impose a cap on the population size than on the number of generations.

Expressiveness

I suggest writing a generator for the population count at each time step.  You can easily count elements using the sum() function.

from __future__ import division
from random import randint

def amoeba_generations(max_split=3, population=1):
    yield population
    while population > 0:
        population = sum(randint(0, max_split) for _ in range(population))
        yield population

def trial(generator, success_pred, failure_pred):
    for g in generator:
        if success_pred(g):
            return True
        if failure_pred(g):
            return False
    return False

def main():
    num_trials = 10000
    max_split_per_amoeba = 3
    num_dead_populations = sum(
        trial(
            amoeba_generations(max_split_per_amoeba),
            lambda n: n == 0,
            lambda n: n >= 10     # Assume a population of >= 10 will never die
        )
        for _ in range(num_trials)
    )
    print("""***starting simulation***
num trials: {num_trials}
max_split_per_amoeba: {max_split_per_amoeba}
extinct outcomes: {num_dead_populations}
extinction probability: {extinction_probability:.4f}
expected probability: {expected_probability:.4f}
delta from answer: {delta:.4f}""".format(
        extinction_probability=num_dead_populations/num_trials,
        expected_probability=2**.5 - 1,
        delta=(num_dead_populations/num_trials) - (2**.5 - 1),
        **locals()
    ))

if __name__ == '__main__':
    main()


Calculate volume of a cylinder with user input

Your implementation is quite simple,
but a bit hard to read:

It's a wall of code, with no vertical spacing to visual separate closely related groups
The ordering of statements is haphazard, with no discernible underlying logic

Consider this alternative:

#include <iostream>
#include <cmath>

long double calculateCylinderVolume(long double radius, long double height)
{
    return acos(-1) * radius * radius * height;
}

int main()
{
    std::cout << "Hello to the cylinder volume solver!\n";

    std::cout << "Please enter the cylinder's radius: ";
    long double radius;
    std::cin >> radius;

    std::cout << "\nPlease enter the cylinder's height: ";
    long double height;
    std::cin >> height;

    std::cout.precision(1000);
    std::cout << "\nThe cylinder's volume is "
        << calculateCylinderVolume(radius, height) << ".\n";
}

Notice that:

variables are not declared sooner than really needed
the std::cout.precision(1000); is delayed until it's actually needed
the blank lines visually separate the closely related statements, improving readability

Other minor improvements:

using namespace std is considered bad practice
return 0 at the end of main is unnecessary
\n is more efficient than std::endl
#include <cmath> instead of #include <math.h>, as pointed out by @FredLarson


Damage or Heal based on the buttons you press

not so much but some tiny changes:

DRY

i just would avoid all the self.healthBarView.frame.size.width

and make methods:

getWidth
setWidth(or updateWidth because you set the diff)

Constants

the magic numbers like 0.1 0.05 10 i would define as constants so it can changed only at one place. 7.63 i would calculate

Naming

rename barAmount to maxAmount

create minAmount

Float/CGFloat

the Float / CGFloat is realy needed? just put them also into getWidth and updateWidth

else if

the else if block is not needed (same condition)

7.63

this is an value depending on your setup - it should also calculated so it not changes when you init it with different width

Resulting Code

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var armorBarView: UIView!

    @IBOutlet weak var healthBarView: UIView!

    var damageAmount : Float = 0.0
    var healAmount : Float = 0.0

    // Min/Maximum Health
    var minAmount: Float = 0.00
    var maxAmount : Float = 0.0

    // how much damage was left after this number of hits
    let minAmountHits:Float = 10

    let demageFactor: Float = 0.10
    let healFactor: Float = 0.05

    override func viewDidLoad() {
        super.viewDidLoad()

        initAmount()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func initAmount(){
        damageAmount = getWidth() * demageFactor
        healAmount = getWidth() * healFactor
        maxAmount = getWidth()
        minAmount = maxAmount - minAmountHits * damageAmount
    }

    @IBAction func damageBar(_ sender: UIButton) {
        if getWidth() > minAmount {
            updateWidth(-damageAmount)
        }
    }

    @IBAction func healBar(_ sender: Any) {
        if getWidth() < maxAmount {
            updateWidth(healAmount)
        }
    }

    func getWidth() -> Float {
        return Float(self.armorBarView.frame.size.width)
    }

    func updateWidth(_ amount: Float) {
        self.healthBarView.frame.size.width += CGFloat(amount)
        print(self.armorBarView.frame.size.width)
    }
}


Broadly speaking, I'd say it looks pretty good. I'm a bit confused by the '1055'; I'm guessing that you're trying to wait until the train leaves the screen entirely? Perhaps you could write this as

(+ WIDTH (/ (image-width LOCOMOTIVE) 2))

... and also replace the 800 with WIDTH. Alternatively, you could return either 0 or

(- (/ (image-width LOCOMOTIVE) 2))

when the train goes off the right edge, so that it makes its entrance smoothly.


Both methods don't use any state of the Solution class, so they should
be static methods of that type, or global functions.

binaryOnes() can be simplified. If you replace

repeat { ... } while num > 1

by

while num > 0 { ... }

then the additional check for num == 1 becomes obsolete:

func binaryOnes(num: Int) -> Int {
    var num = num
    var count = 0
    while num > 0 {
        if num % 2 == 0 { // even numbers
            num /= 2
        } else { // all odd numbers
            num = (num-1)/2
            count += 1
        }
    }
    return count
}

Now observe that num % 2 gives the least significant bit of
the number (0 or 1), and num /= 2 is a truncating division.
Therefore the function can be simplified to

func binaryOnes(num: Int) -> Int {
    var num = num
    var count = 0
    while num > 0 {
        count += num % 2
        num /= 2
    }
    return count
}

More sophisticated bit counting methods can be found at
https://graphics.stanford.edu/~seander/bithacks.html, they can
be more effective for large numbers.

In countBits, the check for num == 0 is not necessary,
because 1...num is the empty range in that case:

func countBits(num: Int) -> [Int] {
    var nums = [Int](count: num+1, repeatedValue: 0)
    for i in 1...num {
        nums[i] = binaryOnes(i)
    }
    return nums
}

Calling the variables num and nums could be confusing,
upTo: might be a better name for the parameter.

But what the function actually does is to map the numbers
0...upTo to their bit count. That can be done directly with
a map() method:

func countBits(upTo: Int) -> [Int] {
    return (0...upTo).map(binaryOnes)
}

An alternative approach would be to use the fact that

bitCount(n) = bitCount(n/2) + (n % 2)

for all (positive) integers n. Together with bitCount(0) = 0
this is a recursive computation method. But since you store the
bit counts in an array anyway, this can be implemented as
a simple iteration:

func countBits1(upTo: Int) -> [Int] {
    var result = [ 0 ]
    for i in 1...upTo {
        result.append(result[i/2] + (i % 2))
    }
    return result
}

Now the binaryOnes() function is not needed anymore.


Creating Original Database Algorithm--Login System

It looks like passwords are stored in plain text form in the pswd.txt file. Never ever store passwords in plain text form. Store passwords salted and cryptographically hashed. That way, if an attacker gains access to the file, he still has to crack the password, which can be extremely difficult if the password is strong enough.

To verify a password, apply the same algorithm to the user input as used when creating the salted and cryptographically hashed version. The result will only match the stored password if the user entered the correct password.

@Boris left a great comment, quoting it verbatim:

  Encrypted passwords are a bad idea as the encryption key needs to be stored in the code, then then it's just a question of looking at the code to gain the key. Hashing is irreversible and using a good, random, unique, salt per password and a purpose built cryptographic hashing algorithm is the only acceptable way of storing passwords - the best idea is to use something like bcrypt which is industry standard and rolls all this together.


Code Reiview for an PHP PDO Queries? is there a better way to do it?

I don't know if I'd use ORM for something so simple, but it may be something to look into. At the very least, you should get in the practice of escaping query parameters to avoid SQL injection. I often use Aura SQL for this, because it's dead simple: https://github.com/auraphp/Aura.Sql

An example query using Aura would look like this:

$user = $db->fetchOne('SELECT chara_gold FROM chara WHERE chara_id = :id', [
    'id' => $shop->chara_id
]);

Aura will automatically escape any bound parameters, like :id, so you don't have to worry about SQL injection. If you don't use Aura, at least use PDO::quote.

Funds transfer is the textbook example of why you need transactions to meet the ACID requirements, so it's good that you're using one, but I don't see your rollback. I assume this is in your catch clause which wasn't included.


List of integer factorization into n terms

Because Divisor is quite efficient at its job, the only optimization I see, is to avoid unnecessary calls to it, by using memoization technique:

FactorIntoFixedTerms[in_Integer, terms_Integer] := Block[{f, div},
  div[n_] := (div[n] = Divisors[n]);
  f[n_, 1] := {{n}};
  f[n_, k_] :=
   Join @@ Table[{q, ##} & @@@
      Select[f[n/q,
        k - 1], #[[1]] >=
         q &], {q, #[[2 ;; \[LeftCeiling]Length@#/
             k\[RightCeiling]]] &@div@n}];
  f[in, terms]
  ]

This can lead to substantial timing reduction:

In[683]:= FactorIntoFixedTerms[1453522322112240, 6] // Length // Timing

Out[683]= {0.047, 47}

In[685]:= foriginal[1453522322112240, 6] // Length // Timing

Out[685]= {0.39, 47}


I realize now that the only time this is a problem is when the value I'm looking for is either of the starting boundaries. In all other cases, a boundary is only moved after it is checked.

So, all I had to do was check both boundaries once, before the loop starts. A fixed, slightly terser version of the original function:

/**
 * y: the target output value to find a matching input
 * minX: the smallest input value
 * maxX: the largest input value
 * ƒ:    a function that returns a value `y` given an `x`
 * ε:    the threshold to compare outputs versus the target (default:0)
 */
function binarySearch(y, minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=0;
    let m=minX, n=maxX, k, Δ;
    if (Math.abs(y-ƒ(m))<=ε) return m;
    if (Math.abs(y-ƒ(n))<=ε) return n;
    while (m<n) {
        Δ = y - ƒ( k = (n+m)/2 );
        if (Math.abs(Δ)<=ε) return k;
        if (Δ>0) m=k;
        else     n=k;
    }
}

Note that this function also fixes a ~bug in the while loop by changing the condition to m<n instead of m<=n.


Dimensions and looping

It looks like you have some off-by-one errors.  This is not a 1×7 box by any definition that I can think of:

Enter Box dimensions (LxW):1 7
********
*      *
*      *
********

In C, the idiomatic way to write a loop that does something n times is for (int i = 0; i < n; i++) { … }.    (Sometimes, the situation calls for for (int i = 1; i <= n; i++) { … } instead, but that's rarer.)  You start your counters at 0, which is good, but you used <= in your termination conditions, which is weird.

Functions

It's a good habit to make a function for any chunk of code that has an identifiable purpose.  Here, it makes sense to define a void printBox(int length, int width) function.  If you need to modify the program to take command-line parameters instead of keyboard input, then you can still call the same function.

By the way, int long is a bit unconventional.  Unless you have a specific reason to do otherwise, just use int.

Smarter library use

You're basically using printf() where the simpler putchar() function will do.  The vertical lines, though, can be better written using a smarter call to printf().  (Consult the documentation for printf().)

Error checking

Functions like scanf() can fail due to invalid user input.  You should be in the habit of checking the return value.

Suggested solution

#include <stdio.h>

void printBox(int length, int width) {
    // Top
    if (length >= 1) {
        for (int i = 0; i < width; i++) {
            putchar('*');
        }
        putchar('\n');
    }

    // Sides
    for (int i = 0; i < length - 2; i++)
    {
        printf("*%*s\n", width - 1, "*");
    }

    // Bottom
    if (length >= 2) {
        for (int i = 0; i < width; i++) {
            putchar('*');
        }
    }
    putchar('\n');
}

int main(void)
{
    int length, width;
    printf("Enter Box dimensions (LxW):");
    if (2 != scanf("%d %d", &length, &width)) {
        // Indicate input error
        return 1;
    }
    printBox(length, width);
}


Finding a substring within a string using regular expressions

You code is pretty much good but

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

may be easily replaced with

Console br = System.console();

Also your while cycle is endless. I would allow to enter some keyword for breaking the loop. E.g. exit

...
System.out.println("\nEnter your regex:");
String input = br.readLine();

if ("exit".equals(input))
    break;
else {
    Pattern pattern = Pattern.compile(input);
    ...
}


Periodically synching data from an API to database is extremely slow

Error handling

if response.status_code != 200:
    print('api response error: {}'.format(response))
    return

is better represented as a simple call to response.raise_for_status().

Also, this:

try:
    response_payload = response.json()
except ValueError:
    return

is dangerous. Silently failing should (at the least) be left up to the caller to decide whether an exception should be caught and swallowed, caught and printed, or allowed to fall through.

Tuple unpacking

for (key, value) in clients_data.items():

can be

for key, value in clients_data.items():

Undeclared variable

        if action == constants.SyncActions.CRT:
            result['new'] += 1
        if action == constants.SyncActions.UPD:
            result['update'] += 1

Where does result come from? You don't show this. Is it a defaultdict?

Incorrect default

hub_data['id'] = int(hub_data.get('client', ''))

will not work in the case that the key is missing. You can't convert '' to an int. Perhaps you meant:

hub_data['id'] = int(hub_data.get('client', '0'))

Ellipses

This is more of a meta-comment, but

# Set `is_active` based on the `archived` flag.
if client_data.get('archive', None) == '1':
    client_data['is_active'] = False
else:
    client_data['is_active'] = True
...

should show the ellipses as a comment to avoid breaking syntactical validity, and you should provide rationale as to why this code is elided. Eliding code harms the potential for you to receive a meaningful review.

Optimization

  How can I optimize it to perform better?

It's nearly impossible to say. You haven't run a profiler, which you should; you've elided too much code for us to run this thing; you haven't shown any example data; and you haven't given us an API endpoint (or if that's not possible, at least a sample of a payload the endpoint would return).


Javascript Slider that controls TinySlider - feels inefficient

A technique that would likely improve this situation is a debounced function. That way the function to be run will only run at certain intervals instead of each time the events occur.

From the Blog of JavaScript consultant David Walsh:

  For those of you who don't know what a debounce function does, it limits the rate at which a function can fire. A quick example:  you have a resize listener on the window which does some element dimension calculations and (possibly)  repositions a few elements.  That isn't a heavy task in itself but being repeatedly fired after numerous resizes will really slow your site down.  Why not limit the rate at which the function can fire?

  Here's the basic JavaScript debounce function (as taken from Underscore.js):

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

  1

That can be used to create a debounced function that only gets called at an interval - e.g. 250 milliseconds (feel free to adjust to your needs):

var debouncedFunc = debounce(sliderLoop, 250);

And use that function in the callback of the event handler:

// Fires slider loop every time the value changes, I had to use mousemove as .change() would only fire once the mouse click was relseased.
$(".slider").on("change mousemove", function() {
  debouncedFunc();
});

That could also be simplified to the following, since the extra lambda function/closure is pointless:

// Fires slider loop every time the value changes, I had to use mousemove as .change() would only fire once the mouse click was relseased.
$(".slider").on("change mousemove", debouncedFunc);

1https://davidwalsh.name/javascript-debounce-function


python: less ugly solution to the intersection of 3 lines in 3 dimensional space

Instead of having variables firstX, secondX, thirdX, replace them with a list X
Don't put input and calculations in the same function, separate them
You do:

if D == 0:
     some stuff
 if D != 0:
     other stuff

use else instead

Your three lines calculating D, DX, DY, DZ are very similar. Make it a function.
The terms being subtractd parallel the ones being added. Extract the pair into a function.

Here is my result:

DEPENDENT = 0
INCONSISTENT = 1
GOOD = 2

def determinant(X, Y, Z):
    def term(x, y, z):
        return X[x]*Y[y]*Z[z] - X[z]*Y[y]*Z[z]
    return term(0, 1, 2) + term(2, 0, 1) + term(1,2,0)

def trinomial(X, Y, Z, A):

    D  = determinant(X, Y, Z)
    DX = determinant(A, Y, Z)
    DY = determinant(X, A, Z)
    DZ = determinant(X, Y, A)
#the next two if statements evaluate the D's, or determinants, to see if it's an inconsistant or identical systerm
#if it's not, then it does the math to solve the equation
    if D == 0:
       if DX == 0 and DY == 0 and DZ == 0:
           return DEPENDENT, None
       else:
           return INCONSISTENT, None
    else:
       return GOOD, [DX/D, DY/D, DZ/D]

def main():
    print "Trinomials require 3 equations with three variables each."
    X.append( input ("Please enter the coeficcient of X in the first equation: ") )
    Y.append( input ("Please enter the coefficient of Y in the first equation: ") )
    Z.append( input ("Please enter the coefficient of Z in the first equation: ") )
    A.append( = input ("and what's after the = sign?") )

    X.append( input ("Please enter the coeficcient of X in the second equation: ") )
    Y.append( input ("Please enter the coefficient of Y in the second equation: ") )
    Z.append( input ("Please enter the coefficient of Z in the second equation: ") )
    A.append( = input ("and what's after the = sign?") )

    X.append( input ("Please enter the coeficcient of X in the third equation: ") )
    Y.append( input ("Please enter the coefficient of Y in the third equation: ") )
    Z.append( input ("Please enter the coefficient of Z in the third equation: ") )
    A.append( = input ("and what's after the = sign?") )

    result, answer = trinomial(X, Y, Z, A)
    if result == DEPENDENT:
        print "System is dependant, there are infinite solutions"
        print
    elif result == INCONSISTENT:
        print "System is inconsistant, there are no solutions"
        print
    else:
        print "the solution to the set of equations is ("+ ",".join(map(str, answer)) + ")."
        print

But if you do any amount of python programming with this stuff you'll want to learn how to use numpy, which make your code:

def trinomial(X, Y, Z, A):
    system = numpy.array([X, Y, Z]).T
    unknowns = numpy.array([A])

    return numpy.linalg.solve(system, unknowns)


Are there any improvements or suggestions to make it more "friendly" so someone would know how to use it without reading this intro?

The most obvious thing is high-quality XML docs. You've already started, but you need to fill in the param name where it's blank, and the return value for the method where it's missing.

On top of that, adding a summary tag to the class itself containing most of the verbiage above would be helpful.

Reading a little further into your implementation - is it possible to move the code of the AttachLogListener method into a constructor? That would guarantee your order of execution/initialization and make usage more sane and obvious, I think.


A directive allowing to make a whole DOM subtree readonly

Generally speaking, you should avoid looking outside the current directive for anything that would affect your internal state (bar events). The preferred method of communication is scopes. Here is how I would recommend you do this.

        <input ng-readonly="is_readonly" />

            <input ng-readonly="is_readonly" />

Simply toggling $scope.is_readonly from MyCtrl is enough to disable all child inputs that have ng-readonly="is_readonly", and it's bindable too, so you can add/remove readonly status at runtime.

Now, if there is a genuine need to have the behaviour you described, then you have 2 options.

Stick with your current implementation, but this will not be performant, since your DOM traversal will fire any time the scope changes, for any reason, anywhere up the scope tree.
Rewrite to use directive's require property.

Here is how you would do the latter.

.directive("readonly", function() {
    return {
        restrict: "C",
        link: function() {},
        controller: function() {},
    }
})
.directive("input", function()
    return {
        restrict: "E",
        // search for optional parent directive named `readonly`
        require: "^?readonly",
        // 4th parameter is `readonly` controller or null.
        link: function($scope, element, attr, has_readonly) {
            var org = attr.ngReadonly;
            if (org) {
                return; // readonly seems to be set manually, so let's not touch it
            } else if (has_readonly) {
                attr.$set("readonly", true)
            }
        },
    };
})

This tells angular that it should pass you a reference to the readonly controller if found, or null otherwise. In this way, you can tell at link time whether the parent node exists. This saves you from performing the DOM traversal yourself, and should be faster too.

Again, I highly recommend that you simply bind to a scope variable instead of checking for the presence of a class further up the tree.


Using a dictionary to group your data is arguably a better alternative to sorting, and building the actual output strings is a perfect fit for the .join() method of strings:

data = {}
for head, tail, kind in input_list:
    tails = data.setdefault(head, [None, []])
    kind = kind.lower()
    if kind == 'spouse' and tails[0] is None:
        # Duplicate spouse entries raise, should we do differently?
        tails[0] = tail
    elif kind == 'child':
        tails[1].append(tail)
    else:
        # Should wrong inputs be ignored, rather than raise?
        raise ValueError('Wrong input')
for head, (spouse, children) in data.items():
    print('|'.join((head, spouse, ','.join(children))))

This will print the families in some arbitrary order, but you could get them sorted by sorting the last for loop, i.e.

for head, (spouse, children) in sorted(data.items()):


for k in sd:
    count = []
    for x in range(1, k):
        for u in range(2, x):
            if x % u == 0:
                break
        else:
            if x != 1 and k % x == 0:
                count.append(x)
    pd.append(len(count))

This part of the code is very slow. You are finding prime numers u through trial division, which is a very naïve method.

Basically, any code that involves prime numbers is going to be extremely slow if you don’t use a “smart” algorithm. Sieves are a good place to look. If I replace your code with

from sympy.ntheory.factor_ import primefactors
for k in sd:
    pd.append(len(primefactors(k)))

it is fifty times faster for the test input

1
1 500

(0.02 sec instead of roughly a second).

A final note: profiling is a very useful technique for finding out which steps of your code take a long time. Your code is impossible to profile if you don’t split it up into smaller functions, so please do that.


Project Euler # 30 Digits fifth power in Python

Your comprehensions are hard to understand, as you have two on one line. I recomend you spread them over multiple lines to increase readability.
There is no benifit to using a dictionary comprehension, and only makes me think you're abusing comprehensions.

Just use a normal for loop and use yield.
You don't need to pass n, you can find the limit by using power * 9**power.
This causes the program to run in a quarter of the time.

def powers(power):
    for number in range(2, power * 9**power):
        total = sum(int(digit) ** power for digit in str(number))
        if total == number:
            yield number

If you change from using range to just digits and checking that the total is an anagram of the input then you can get the code to run in ~5% the time of the previous code.

def powers(power):
    for size in range(1, len(str(power * 9**power)) + 1):
        for digits in itertools.combinations_with_replacement(range(10), size):
            total = sum(int(digit) ** power for digit in digits)
            if (sorted(str(total)) == sorted(str(digit) for digit in digits)
                and total != 1
            ):
                yield total


These conditions can be simplified:

if($row==1 and $pos==1) // for first row.
{
    return 1;
}
else if($pos==0)    // for left most row element that doesn't exist.
{
    return 0;
}
else if($pos>$row)  // for right most row element that doesn't exist.
{
    return 0;
}

To this:

if ($pos == 1 or $row == $pos)
{
    return 1;
}

Coding style

The expressions are too packed.
It would be better to add more spaces:

around operators
after semicolons
after commas in parameter lists
before opening ( of if conditions and for loops

So instead of this:

for($i=1;$i<=$rows_to_generate;$i++)
{
    for($j=1;$j<=$i;$j++)
    {
        echo $storage[$i][$j]=get_elem($i,$j);  // generate
        if($i!=$j)

This is easier to read:

for ($i = 1; $i <= $rows_to_generate; $i++)
{
    for ($j = 1; $j <= $i; $j++)
    {
        echo $storage[$i][$j] = get_elem($i, $j);  // generate
        if ($i != $j)


Please never do this again:

    static ConcreteTrafficReturner* getInstance() {
      if (myself == 0)
      {
         myself = new ConcreteTrafficReturner();
      }

Problem 1:

You are not providing a concept of ownership. The user of your class has to actually read the code to understand that you are not only returning the pointer but ownership of the pointer.

Problem 2:

You are returning a pointer. So who decides when it should be deleted. What happens if the user of your class forgets to call delete!

A better way to implement this is:

    static ConcreteTrafficReturner& getInstance()
    {
       static ConcreteTrafficReturner    instance;    // created the first time
                                                      // get instance is called.
                                                      //
                                                      // automatically destroyed
                                                      // with other static storage
                                                      // duration objects.

        return instance;
    }

But really the above is a text book example (not a real world example) of a singelton. The singelton pattern is actually dangerous in that it binds your implementation to an object with mutable state. As such it should not be used in isolation it should be used in conjunction with a creator pattern (A factory is usually a good choice).

Note: Singelton is a design pattern. But in a lot of places it is also considered and anti-pattern so be very careful with its usage.

Template problem

Though technically correct. You may find problems with this design when using shared libraries. As each shared library may have its own instantiation of the templated object that is not shared. Thus you actually have multiple instances of your singelton.

Summary:

Personally I would not use a singelton (I think you can use other techniques). But if you have to use a singelton then it would look like this:

class MySingInterface
{
    public:
       virtual ~MySingInterface() {}  // Never foget the virtual destructor of
                                      // a class with virtual functions.
       // Other interfaces
};
class MySingFactory
{
    public:
        virtual ~MySingInterfaceFactory() {}
        virtual MySingInterface& createMySingInterface() = 0;
};

class MySingBuilder
{
    static std::vector<MySingFactory*>   factories;             // This could be a map
                                                                // of factories or
                                                                // anything else that
                                                                // makes sense to your
                                                                // project.

       static MySingInterface& buildInstance()
       {
             // decide what factory to use.
             // then call build (EG if you are in debug mode or unit test mode
             // you may want to build a different type of object from normal).
             //
             // I have shown an example where you can register multiple
             // factories but that may be overkill for you. Maybe you only need
             // to register one factory (which you decide in main and depends
             // on input arguments or config options or environment variables etc...)

             return factories[someIndex]->createMySingInterface();
       }
    public:
       MySingInterface&  getInstance()
       {
           static MySingInterface& instance = buildInstance();
           return instance;
       }

       static void addFactory(MySingFactory& factory)
       {
           factories.push_back(&factory);
       }
};

MySingFactoryForTest   mySingFactoryForTest;
MySingFactoryForNormal mySingFactoryForNormal;

int main()
{
    if (getenv("UNIT_TEST") != nullptr)
    {
        MySingBuilder::addFactory(mySingFactoryForTest);
    }
    else
    {
        MySingBuilder::addFactory(mySingFactoryForNormal);
    }

    MySingInterface& mSI = MySingInterfaceBuilder::getInstance();
}


Code looks good! I only have minor/pedantic comments:

for _ in range(10):  # '_' is a throw-away var

That comment is useless, the naming of the variable as _ is sufficient to indicate that we don't intend on using it. Also, in python2.7, range() returns a full list of all the values, which can get pretty inefficient as you go up, so you should prefer to use its lazier cousin, xrange():

for _ in xrange(10):

Then this:

print largestOddNumber or 'No odd number was entered.'

While I do like that or in python, rather than returning a bool returns the first argument that isn't False/None, it's a little difficult to read. Now, the code is perfectly correct for odd numbers but would actually be wrong for even numbers - if 0 ended up being the largest even number, we'd print the string. So I find it simpler to just be explicit:

if largestOddNumber is not None:
    print largestOddNumber
else:
    print 'No odd number was entered'

But really, the code is fine.


Here's one way to reverse numbers without converting to strings and/or using std::reverse.  As per the challenge, this deals with only positive integers.

int RevNum( int num )
{
    int outVal = 0;
    while ( num > 0 )
    {
        int temp = num % 10;
        outVal = ( outVal * 10 ) + temp;
        num /= 10;
    }
    return outVal;
}

Because the number starts and stays as a number, zeros are automatically handled properly.


Depth-first Search Non-Reursive Implementation in Clojure

From the top ...

The label function is a synonym for cons, as is build-stack for
concat. Drop them.
The get-edges function doesn't get edges. It gets the neighbouring
vertices. Call it neighbours, or some such.

The labeled? function:

It determines whether the first argument is a member of the
collection second argument. So call it something generic like
includes?.
Swap the arguments around, so that it reads more naturally.
Get rid of the explicit falses and trues. You usually can.

We end up with

(defn includes?
  [coll x]
  (some #(= x %) coll))

Now for the dfs function itself.

Your local S is, as its name suggests, a stack. Use the other end
of it - the front of the list. This gets rid of the slow last and
butlast. You can't use Clojure's stack lingo - peek, pop, and
conj - because there's a concat in there. So use first, next,
and cons instead.
If you use a vector instead of a list to accumulate discovered, you
don't need the final reverse.
(cons v ()) is just (list v)

The result is

(defn dfs
  [g v]
  (loop [discovered [], S (list v)]
    (cond
      (empty? S) discovered
      (includes? discovered (first S)) (recur discovered (rest S))
      :else (recur
              (conj discovered (first S))
              (concat (neighbours g (first S)) (rest S))))))

There's still a performance problem. Whenever it deals with a potentially new vertex, it uses includes? to do a linear search of discovered. For a graph of n vertices, this takes of the order of n^2 time.

The answer is to hold the discovered data twice:

as a vector, for returning the answer; and
as a set, for testing for presence.

This roughly doubles the amount of memory required, but reduces time required enormously (roughly to order of n).

I'll leave you to make the necessary changes to dfs.


First of all, these two lines:

guard completions.count > 0 else { return nil }
return completions[0]

can be simplified as just this:

return completions.first

It does exactly the logic you've implemented, except that it's far more clear what the intent is.  Moreover, if ever you need to do this in the case that completions isn't a local variable, your approach is not thread safe.

Taking a look at the bigger picture, I don't understand the purpose of loadKeywords neither as part of the protocol nor as a method itself.

It appears that the only real reason that they exist is because they are used by the suggestion() method.  Since you haven't included the code that is actually using this protocol, I can only guess, but my best guess is that it's completely not needed.  Instead, I would take an approach like this with the protocol:

protocol KeywordSuggesterProtocol {
    func canSuggestForKeyword(keyword: String) -> Bool
    func suggestionForKeyword(keyword: String) -> String
}

Notice here, no optionals.

It potentially make sense for the protocol to simply be the second method and have it return an optional, simply returning nil where the first method would have return false.  But potentially, suggestionForKeyword might be an expensive operation (although I suppose it could be optimized).  So a protocol like this:

protocol KeywordSuggesterProtocol {
    func suggestionForKeyword(keyword: String) -> String?
}

could work as well.

The code that actually makes use of the protocol would look like one of the following two snippets (based on which protocol you're using):

class Foo {
    weak var suggester: KeywordSuggesterProtocol?

    // ...

    func someFuncThatNeedsKeywords(keyword: String) {
        var suggestedWord: String?
        if suggester?.canSuggestForKeyword(keyword) {
            suggestedWord = suggester?.suggestionForKeyword(keyword)
        }
    }

    // ...
}

... or ...

class Foo {
    weak var suggester: KeywordSuggesterProtocol?

    // ...

    func someFuncThatNeedsKeywords(keyword: String) {
        let suggestedWord = suggester?.suggestionForKeyword(keyword)
    }

    // ...
}

Hmm, the latter is probably better honestly.

As for your implementation, let's take a look at your initialization...

class EmojiKeywordSuggester: KeywordSuggester {
    var keywords: Set<String> = []
    let language = "en_US"
    private let textChecker = UITextChecker()

    init() {
        self.keywords = self.loadKeywords()
    }

    // stuff
}

First of all, language and keywords should be private.  But also, the loadKeywords method really isn't useful to us at all beyond initializing the keywords, right?  So, let's take this approach...

class EmojiKeywordSuggester: KeywordSuggester {
    private let keywords: Set<String> = {
        //TODO: load CSV from file
        return ["happy", "smile", "nature", "mushroom", "eye", "poop", "icecream", "food", "grin", "face"]
    }()

    private let language = "en_US"

    private let textChecker = UITextChecker()

    // init no longer necessary
}

Now, it may come a time when you actually want to implement loading the keywords from CSV, in which case, we'd want something like this:

class EmojiKeywordSuggester: KeywordSuggester {
    private let keywords: Set<String>
    private let language = "en_US"
    private let textChecker = UITextChecker()

    init?(csvFilePath: NSURL) {
        guard let loadedKeywords = loadKeywordsFromCSV(csvFilePath) else {
            keywords = []
            return nil
        }
        keywords = loadedKeywords
    }

    private func loadKeywordsFromCSV(csvFilePath: NSURL) -> Set<String>? {
        // logic to load from the URL (which could be a local file URL)
        // this can of course fail, and return nil
    }
}

It's a failable initializer that fails when we can't load the keywords from the file path.


Ruby array search, returning either a result with a good score or the last result

You can always define your own custom method to refactor your code in the Array class:

class Array
  def find_or_last(&block)
    find(&block) || last
  end
end

And use it like this:

array.select { |i| i['title'] == 'some title' }.find_or_last { |i| i['Zscore'].to_f >= 5 }

You can also use procs or lambdas to achieve this.


Manipulating the global address book in Outlook

Your printAllReports method does almost everything that's possible to do with the Outlook API (ok maybe not), except printing anything. You basically have what we call a monolith, and that's bad because as your program changes, you are tempted to just keep adding and adding and adding, until the thing becomes an unmanageable, tangled mess. If you're going to call a method printAllReports, give it a signature like this: Sub printAllReports(allReports As Collection), so its intent is clear at first glance - and then make it do one thing; print all reports.

Performance-wise, the major hit is going to be hitting the Exchange server, so your code needs to make sure it hits the server only when it's necessary. If that's already the case, chances are you've already got it as good as it gets.

I think your multiple collections and 3-layer deep nested loop approach isn't the easiest way to make your code readable and maintainable, let alone to fine-tune its performance.

HierarchicalUser

The beautiful thing about a language that allows you to define objects, is that doing so actually adds vocabulary to that language, so no matter how lame VBA/VB6 is, with your own objects you can add new nouns, and with your own methods you can add new verbs, and with enough of them you actually end up crafting a language (ok, an API) that's beautiful in its own way.

You have the concept of an ExchangeUser, that can report to another ExchangeUser, and that can have ExchangeUser underlings. I call that a hierarchy, and I'd recommend you encapsulate that ExchangeUser into your very own HierarchicalUser class, something along those lines:

private type tHierarchicalUser
    User As ExchangeUser
    Superior As HierarchicalUser
    Underlings As New Collection
end type

private this As tHierarchicalUser
Option Explicit

Public Property Get User() As ExchangeUser
    Set User = this.User
End Property

Public Property Set User(value As ExchangeUser)
    Set this.User = value
End Property

Public Property Get Superior() As HierarchicalUser
    Set Superior = this.Superior
End Property

Public Property Set Superior(value As HierarchicalUser)
    Set this.Superior = value
End Property

Public Property Get Underlings As Collection
    'DO NOT return a reference to the encapsulated collection, you'll regret it!
    Dim result As New Collection, underling As HierarchicalUser
    For Each underling In this.Underlings
        result.Add underling
    Next
    Set Underlings = result
End Property

Public Sub AddUnderling(underling As HierarchicalUser)
    Set underling.Superior = Me
    this.Underlings.Add underling 'you can use a key here to ensure uniqueness
End Sub

'almost forgot!
Public Function FlattenHierarchy() As Collection
    Dim result As New Collection

    'traverse whole hierarchy and add all items to a collection that you return

    Set FlattenHierarchy = result
End Sub

Then you'll need a way to create instances of this class, and populate them. Enter the HierarchicalUserFactory (well, I know I would put that in its own class, but that's just me) - instead of nesting code we're going to be nesting method calls, recursively:

Public Function CreateHierarchicalUser(exUser As ExchangeUser) As HierarchicalUser
    Dim result As New HierarchicalUser
    Dim entry As AddressEntry
    Dim underling As ExchangeUser

    set result.User = exUser

    For Each entry In exUser.GetDirectReports() '<< For Each won't loop if there's nothing in the collection

        'if possible, run the isExchangeUserActualEmployee logic off this 'entry' object,
        'so you can only call the expensive GetExchangeUser method if needed:
        set underling = entry.GetExchangeUser
        result.AddUnderling CreateHierarchicalUser(underling) '<<< recursive call!

    Next

    Set CreateHierarchicalUser = result
End Function

Haven't tested any of this, but I believe an approach along those lines could possibly help you reduce the amount of GetExchangeUser calls and thus increase performance... not to mention readability++ :)

So your printAllReports method could possibly look like this now:

Public Function getHierarchy(topLevelUserName As String) As HierarchicalUser
    Dim factory As New HierarchicalUserFactory
    Dim topLevelUser As ExchangeUser

    Set topLevelUser = getExchangeUserFromString(topLevelUserName)
    Set GetHierarchy = factory.CreateHierarchicalUser(topLevelUser)
End Sub

Public Sub printAllReports(hierarchy As HierarchicalUser)

    Dim reports As Collection
    Set reports = hierarchy.FlattenHierarchy()

    'do all that cool stuff you wanted to do!

End Sub

Nitpicks

When you declare an object variable and assign it to a New instance on the next line, consider combining the two statements into one: Dim X As New Y.
When you declare a Boolean, it's automatically initialized to False so your post-declaration assignments are redundant.
When you evaluate a Boolean expression in an If statement, you don't need to specify =True or =False - rather, just say If SomeBooleanExpression Then or If Not SomeBooleanExpression Then.
When looping through objects in a collection, ALWAYS use a For Each construct. This will avoid weird stuff like For i = 1 To MyCollection.Count when .Count is 0, even someone that knows the VBA/VB6 collection base rules like the palm of their hand will go "huh?". For...Next has been around since before objects even existed, that construct is for traversing arrays. Collections deserve a For Each.


1. Comments on your code

The function is poorly specified in that it combines two tasks: (i) it gets input from the user via an editor; (ii) it replaces newlines in the input with <br>. But what I just want the input and don't want any HTML conversion (especially not a half-baked conversion like this one)?

It would be better to decompose this function into two pieces. In what follows I'm just going to discuss piece (i), launching the editor and capturing the input.
There are missing imports (os and subprocess).
The function always uses the file compose.txt in the current directory. This means that if I already had a file with that name, it would be erased and then deleted, which would be really annoying.

It would be better to create a temporary file for this purpose, using Python's tempfile.NamedTemporaryFile.
This code:

diff = subprocess.Popen(['cat',filePath], stdout=subprocess.PIPE)
pr = subprocess.Popen(..., stdin=diff.stdout)

is a classic "useless use of cat". If you read the documentation for subprocess.Popen, you'll see:

  stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None.

(my emphasis) so you can write:

pr = subprocess.Popen(..., stdin=open(filePath))

and save a process. (But actually this is unnecessary, as explained below.)
This code:

if re.search(r'ubl', editor):

doesn't seem like a very robust way to ensure that editor is Sublime Text. I mean, for all you know I could have just run:

$ ln /usr/bin/vi ubl

It's best to treat all the editors the same. After all, git commit doesn't have any special case for Sublime Text, so neither should you.

In particular, you don't need to go through all that subprocess.Popen shenanigans to open a file in Sublime. I find that

subprocess.call(['subl', filename])

works fine.
If all you are going to do with a subprocess is wait for it to exit:

pr = subprocess.Popen([editor, filePath], stdin=open('/dev/tty', 'r'))
pr.wait()
if pr.returncode == 0:

then use subprocess.call instead of subprocess.Popen:

if subprocess.call([editor, filePath]) == 0:

Specifying stdin=open('/dev/tty', 'r') is unnecessary. Let the editor decide how it wants to get input from the user.
If the editor returned with a non-zero code, your function doesn't report an error, it just continues running (but with nothing assigned to msg) until it reaches "".join(msg) which fails with a mysterious TypeError. Better to raise an exception if the editor returned an error code.

(I submitted a bug report for the mysterious TypeError: see Python issue 20507.)
Your function splits the input into lines by calling msg = fh.readlines(), and then it joins these lines back together again with "".join(msg). This is pointless: if you just want the contents of the file as a string, write msg = fh.read() instead.

2. Revised code

import subprocess
import tempfile

def input_via_editor(editor):
    """Launch editor on an empty temporary file, wait for it to exit, and
    if it exited successfully, return the contents of the file.

    """
    with tempfile.NamedTemporaryFile() as f:
        f.close()
        try:
            subprocess.check_call([editor, f.name])
        except subprocess.CalledProcessError as e:
            raise IOError("{} exited with code {}.".format(editor, e.returncode))
        with open(f.name) as g:
            return g.read()