Retrieve value from a formula in cells into different merged cells and retrieved value can be edited

I use these two methods when running macros that do intensive work of reading/writing information to several sheets:

' hide the mouse pointer, which in some PCs makes macros very slow. put this at the top
' of your module
Private Declare PtrSafe Function ShowCursor Lib "USER32" (ByVal fShow As Integer) As Integer

' disable some Excel features while the macro is running to improve performance
Sub enableMacroOptimizations()

    Dim cursorCount As Integer

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    Application.DisplayScrollBars = False
    ActiveWindow.DisplayWorkbookTabs = False
    Application.DisplayStatusBar = True
    Do
        cursorCount = ShowCursor(False)
    Loop While (cursorCount >= 0)

End Sub

' enable Excel features disabled with enableMacroOptimizations()
Sub disableMacroOptimizations()

    Dim cursorCount As Integer

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.DisplayScrollBars = True
    ActiveWindow.DisplayWorkbookTabs = True
    Application.DisplayStatusBar = True
    Do
        cursorCount = ShowCursor(True)
    Loop While (cursorCount < 0)

End Sub

This will improve the performance of your macros no matter what. We have used this code to reduce macro times from more than 10 minutes to just a few seconds.

Just call enableMacroOptimizations() at the top of you own intensive method, and then call disableMacroOptimizations() at the end (to leave the user workspace as found initially).


Given a string, find the length of the longest substring without repeating characters

The algorithmic complexity of your solution is \$O(N*C)\$ where \$N\$ is the number of characters in the string and \$C\$ is the size of the alphabet. Assuming lowercase ASCII characters, that's a linear algorithm and will probably be good enough for most things. That being said, it is possible to solve the same problem in \$O(N)\$.

Before that though, your current solution is hard to read. So let's simplify it.

If most of your code is inside an if statement, use a guard instead.
Don't use generic names like dict for variables. Especially not if the name is already taken. dict is a class in python.
You can use in and not in operators instead of has_key. e.g, if key in dictionary:
Use functions like max and min instead of conditionals. Actually, just avoid conditionals wherever possible. The more nested your code is, the harder it is to read.

Here's my take on the same program:

def lengthOfLongestSubstring(self, word):
    if not word: return 0

    currentLength = 1
    longest = 1
    lastSeen = {word[0] : 0}
    i = 1

    while i < len(word):
        letter = word[i]
        if letter in last_seen:
            i = last_seen[letter] + 1
            last_seen.clear()
            longest = max(longest, currentLength)
            currentLength = 0
        else:
            last_seen[letter] = i
            currentLength += 1
            i += 1

    longest = max(longest, currentLength)

    return longest

While it's a bit better, I still don't like it. Jumping back and forth is hard to wrap your head around, and it would be nice if the algorithm didn't do that.

Let's try brute force:

def lengthOfLongestSubstring(self, word):
    n = len(word)
    longest = 0
    for i in range(n):
        seen = set()
        for j in range(i, n):
            if word[j] in seen: break
            seen.add(word[j])
        longest = max(len(seen), longest)
    return longest

This one is pretty easy to understand and is still \$O(N * C)\$ in the worst case. Practically this will generally be slower that your solution, but not by that much.

Is there a way to get both readability and speed though? Yep. We don't need to go that far from your idea either. Just a couple minor changes.

Let's think about left most character that you can still include in a replication free substring while going right. Clearly, this character must be to the right of any character that has been seen again.
If we know the position of this character than the longest substring ending at the current index is easy to calculate. Here's an implementation:

def lengthOfLongestSubstring(self, word):
    # Initially we can go as far to the left as we want
    left_most_valid = 0
    longest = 0
    last_seen = {}

    for i, letter in enumerate(word):
        if letter in last_seen:
            # left_most_valid must be greater than any position which has been seen again
            left_most_valid = max(left_most_valid, last_seen[letter] + 1)
        last_seen[letter] = i

        # Length of substring from left_most_valid to i is i - left_most_valid + 1
        longest = max(longest, i - left_most_valid + 1)

    return longest

This is an \$O(n)\$ algorithm and about as fast as reading the string from input.


Multiple jQuery events on one element with different functions and target selectors

Try placing the comments inside the callback instead to avoid breakage. I also do this on if-else statements as well so comments remain uniform.
Event maps are better when appending multiple event handlers to the same selector.
If you want a bit readability, move the handlers away from the attaching procedure. That way, they look clean

So here it is in the end:

//handlers

function selector1handler(){
    //comment here
};

function selector2handler(){
    //comment here
};

function selector3click(){
    //comment here
};

function selector3mouseover(){
    //comment here
};

//add handlers

$(document)
    .on('mouseenter', 'selector1', selector1handler)
    .on({
        click : selector3click,
        mouseover : selector3mouseover
    },'selector3')
    .on('mouseleave', 'selector2', selector1handler)


Quoting strings passed to an output stream

In C++14, there's std::quoted. Some advantages it has over your approach:

It works with both output and input streams
You can specify the delimiter and escape character
It's a stream manipulator, allowing it to be used seamlessly with operations while yours is a one-off class with zero interoperability
It supports wide strings


I start from your code:

var search = function(nums, target) {
    for (let i=0; i<nums.length; i++) {
        if (target === nums[i]) return i
    }
    return -1
};

And your question:

  While this algo works, I am not sure if this is optimal or correct?

Your algorithm is correct but it is optimal ? The answer is nope because as from the comment by @CertainPerformance to your question your code runs in O(n).

The hint is contained in the phrase Your algorithm's runtime complexity must be in the order of O(log n) that bounds the desired solution to the binary search having O(log n) complexity. The algorithm works if there is a sorted array, but with some modification can be adapted to a rotated array.

Here my javascript code for the original binary search:

const search = function search(a, t) {
    let l = 0;
    let r = a.length - 1;

    while (l <= r) {
        let m = Math.floor((l+r) /2);
        if (a[m] == t) { return m;  }
        if (a[m]  < t) { l = m + 1; }
        if (a[m]  > t) { r = m - 1; }
   }
   return -1;
}

My solution for a rotated array is quite similar but with a two if else inside the while cycle because we can have four different cases, I added an explanation after the code below:

const search = function search(a, t) {
    let l = 0;
    let r = a.length - 1;

    while (l <= r) {
        let m = Math.floor((l+r) /2);
        if (a[m] == t) { return m; }

        if (a[m] < a[r]) {
            if (t > a[m] && t <= a[r]) {
                l = m + 1;
            } else {
                r = m - 1;
            }
        } else {
            if (t >= a[l] && t < a[m]) {
                r = m - 1;
            }
            else {
                l = m + 1;
            }
        }
    }

    return -1;
}

console.log(search([4,5,6,7,0,1,2], 0));
console.log(search([4,5,6,7,0,1,2], 5));
console.log(search([4,5,6,7,0,1,2], 3));
console.log(search([1, 3], 3));
console.log(search([4,5,6,7,8,1,2,3], 8));

Substantially if I have a [l,..m, .. r] interval I have two possible cases:

a[m] < a[r] --> consecutive ascending numbers, so if a[m] < t <=
a[r] in the next iteration I will examine the interval [m + 1, r]
otherwise I will examine the interval [l, r - 1]
a[m] >= a[r] --> there are rotated elements like for example [7, 0,
1, 2] , so I am sure the left array contains only ascending numbers.
In this case if a[l] <= a[t] < a[m] in the next iteration I will
examine the interval [l, m - 1] otherwise I will examine the
interval [m + 1, r].


Well, the first thing I'd do is put the patterns in a list, and loop through matching them. The second thing would be general cleanup; use namespaces where you can, one-liner if/else clauses don't need braces, use var where the type is obvious, etc etc. This gets rid of that if-elseif structure and makes the code much more concise.

As far as merging the patterns, you could match on a combination of two:

"xmlns:(d5p1|d2p1)=\".*?\"" (we don't care what the exact namespace definition is, just don't match greedily)
"(d5p1|d2p1):nil=\"true\""

If either of these patterns match, replace the matching text with an empty string:

    List<string> patterns = new List<string>{
       "xmlns:(d5p1|d2p1)=\".*?\"",
       "(d5p1|d2p1):nil=\"true\"",
    };

    var output = new string[sentences.Count()];
    for(int i=0; i < sentences.Count(); i++)
    {
        Console.WriteLine("{0,24}", sentences[i]); // 24 chars, left-justified.
        var formattedSentence = sentences[i];

        foreach(var pattern in patterns)
        {
           var len = formattedSentence.Length;
           formattedSentence = Regex.Replace(formattedSentence, pattern, String.Empty,
                 RegexOptions.IgnoreCase)

           if(formattedSentence.Length != len)
              Console.WriteLine(" (match for '{0}' found)", pattern);
        }

        //Finally, this may have left some unneeded whitespace which we can consolidate.
        formattedSentence = Regex.Replace(formattedSentence, "  +", " ");

        output[i] = formattedSentence;
    }

    // ok, let's look at the end result
    foreach(var sentence in output)
       Console.WriteLine(sentence);

One last thing. Hungarian notation - putting some type-specific flag at the beginning of your variable names - is EVIL in virtually any language used in an IDE, including .NET languages. IntelliSense tells you all you need to know about an object's type, if it happens to not be obvious via context; you shouldn't put it in the variable name. If you do, and the type changes, the variable name is now inconsistent and every usage of it needs to change (a task made easier by refactoring assistants like ReSharper, but if you have that you have absolutely no need for Hungarian).


What you are doing sounds reasonable overall.

It's good that you are using F-strings:

nmoPag = input(f"There are {noPag} number of pages. If you want to scrape all of them write 'Max' else write number of pages you wish to scrape: ")

But there are many other places where you don't eg:

print('Your job in '+jobL+' as a '+ jobT.text.strip()+
                    '.\nHere is a quick summary of your job here: '+
                        jobS+'\nLink for more information and application for the job - https://indeed.com'+link,

So I would upgrade the rest of the code for more consistency and better readability :)

Consistency: you are mixing lower case and upper case in some variable names eg jobName vs place. Remember that variable names are case-sensitive in Python. The practice could be dangerous and confusing. Imagine that you have jobName and jobname, it's two variables that may be assigned different values.

There is redundancy in the use of functions, for example this bit of code is repeated twice:

jobT.text.strip()

Don't repeat yourself, just assign the result of jobT.text.strip() to a variable once, and reuse it.

More repetition: www.indeed.com is hardcoded 3 times. Define a global variable for the root URL, then add the query string parameters as required.

With the urllib library you could take advantage of the URI-building functions that are available to you. See Creating URL query strings in Python. Tip: if you want to build URIs but don't fire them immediately, you can also use prepared requests.

Although in the present case, the site does not use classic query string parameters separated with a &. So you can instead use an F-string, again, with sanitized variable values:

url = f"https://www.indeed.com/q-{jobName}-l-{place}-jobs.html"

Note regarding user input: the most obvious is to check that the input is not empty. Always trim the input too, because some people might copy-paste text with extra tabs or spaces (think Excel). Maybe you could use a regex to replace multiple occurrences of whitespace with a single hyphen.

I would also add more checks to make sure that all the DOM elements you are expecting were found - because a website is subject to change at any time. When that happens, the code must alert you.

Finally, a quality script should have exception handling (10 lines of code would suffice). Catch exceptions always and log the full details to a file. This will help you a lot with debugging and troubleshooting.

As your code is on Github, some people might want to use it. If they have problems with it, it would be good if they could attach a log in their bug report, so that you get better insight into the error.

Since you are scraping a website, all sorts of errors will happen often: DNS resolution errors, timeouts, requests denied etc. Your script should handle those errors gracefully.


The bigest problem is that code while(true){} will eat up all CPU that is available for the thread. Try running your program on a single core machine (it will run fine because you are only producing 10 items but try producing infinite number - they should still be consumed properly). The minimum change should be while(condition) Thread.Yield() or Thread.Sleep(). Yielding will still eat up all CPU but sleeping will put your thread down for longer than might be needed - this is why synchronization is used - to notify the other thread instead of making it sleep and try guessing when the new data will arrive.

More important issue that requires synchronization is that Queue.Enqueue() and Queue.Dequeue() will most probably not be atomic operations - what happens if you enqueue an item while it is dequeing? This is why classes like ConcurrentQueue have been created in .NET Framework.

Next problem is a situation with multiple consumers. Assume two consumers and one item in the queue. If both of them run at the same time, they will both at the same time detect that q.Count == 1. Now the first of them dequeues the only item from the queue. Now the second one tries to dequeue but there is nothing there anymore - it will throw an exception.


Translate boolean flags to collection of numbers in scala

You could use tuples to pair your flags with an Int. Throw those into a Seq and then perform a filter and then a map on that Seq. Here is how that would look:

def f(a: Boolean, b: Boolean, c: Boolean): Seq[Int] = {

 val xs = Seq((a, 2), (b, 7), (c, 12))

 xs.filter(t => t._1).map(t => t._2)

}

Note that in Scala you don't need to use a return statement as long as the last bit of code in your function returns a new value.


Use better algorithms: Sieve_of_Eratosthenes

You used a brute force algorithm. But even this can be highly improved.

You increment by 2 each loop.

    for (int i = 5; ; i = i+2) {

So you have noticed that all even numbers are not prime. You can improve on this. By incrementing by 2 then 4 then 2 then 4. This removes all multiples of 2 and 3 automatically.

    int inc = 2;
    for (int i = 5; ; i += inc, inc = 6 - inc) {

The brute force check runs up to num/2

    for (int i = 2; i <= num/2; ++i)

Actually you can do better than that you only need to run up to the sqrt(num) anything larger than this will not divide into num exactly.

    int limit = sqrt(num);
    for (int i = 2; i <= limit; ++i)

Actually we can take this a step further. There is no need to divide by every number lower than num. Any number that is divisible by a prime is already checked by a prime smaller than it.

For example there is no need to check 4. You already checked 2 and all numbers divisible by 4 are also divisible by 2, so need to do that check. In fact you can skip all numbers that are not prime.

bool is_prime(int num)
{
    int limit = sqrt(num);
    for (auto const& prime: primes) {
    {
        if (prime > limit) {
            return true;
        }
        if (num % prime == 0) {
            return false;
        }
    }
    return true;
}


Extending Sieve of Eratosthenes beyond a billion - follow-up

There are a few things you could do to improve your code.

Use braces

Constructions like this are a bug waiting to happen:

for (unsigned long int k = i + j; k < MAX; k += j)
    if (a[k])
        //Open the following comment very carefully
        //std::cout << "removes " << 2 * k + 1 << "\n";
        a[k] = false;

If anyone ever uncomments that line, the a[k] = false will then be outside the for loop and the program will not work correctly.  Such errors are easily avoided by the use of braces:

for (unsigned long int k = i + j; k < MAX; k += j) {
    if (a[k]) {
        //no particular care is now required
        //std::cout << "removes " << 2 * k + 1 << "\n";
        a[k] = false;
    }
}

Check for allocation failure

The code doesn't currently check for an allocation failure, but it should.  Calls to malloc or calloc can fail, and your program should be robust enough not to fail if that happens.

Reduce the range of search for primes

We already know that the largest usable prime is \$<\sqrt{\text{MAX}}\$, but then there is this line:

while (((++i)<MAX) && (!a[i]));

We don't really need to search all the way to MAX.  Also, for clarity, I'd rewrite that as a for loop:

// skip over composites to next prime
for (++i; i<sqrtMAX && a[i]; ++i)
{}

Skip more composite numbers

In the actual sieve, the code skips forward and then marks all odd multiples of the most recently discovered prime.  However, the code currently doesn't skip as many as it could.

For instance, if the most recently discovered prime is 7, the code currently skips to 21, but we can do better.  We can skip to 7*7 = 49 because any other smaller multiple of 7 will already have been eliminated.  That transforms the inner loop from this:

for (unsigned long int k = i + j; k < MAX; k += j) {

To this:

for (unsigned long int k = 2*i*(i+1); k < MAX; k += j) {

Print as you go

Rather than searching the entire array at the end, only the part of the array after \$\sqrt{\text{MAX}}\$ really needs to be searched since all of the other primes were identified during sieveing.  We can print them as they are discovered and save some time searching.

Increment rather than multiply

In the various loops, the expression 2*i+1 (stored in j in the first loop) is used to convert from an index to the actual numerical value it represents.  It speeds things up a bit if the code simply increments j each loop increment.

Clean up the loop

Instead of using nested while loops, it seems to me to be cleaner if you use a for loop and inner if to determine whether the number is composite and should simply be skipped, or prime and should be sieved.

A new sieve:

Using all of these suggestions, I get this, which is about 8% faster on my machine than the original.

void sieve2()
{
    bool *a = (bool*)malloc(MAX * sizeof(bool));
    if (a == NULL) {
        return;  // bad alloc
    }
    memset(a, true, MAX);
    const unsigned long sqrtMAX = ceil(sqrt(MAX));
    unsigned long i;
    unsigned long j;
    std::cout << "done\n";
    for (i=1, j=2*i+1; i < sqrtMAX; ++i, j+=2) {
        if (a[i]) {  // it's a prime
            std::cout << j << '\n';
            for (unsigned long int k = 2*i*(i+1); k < MAX; k += j) {
                if (a[k]) {
                    a[k] = false;
                }
            }
        }
    }
    for ( ; i < MAX; ++i, j+=2) {
        if (a[i]) { // it's a prime
            std::cout << j << '\n';
        }
    }
    free(a);
}

Further improvements

There are many other things you might explore to further speed the code:

Use bits rather than bytes to store values.
Reimplement with pointers rather than array indexing.
Create a multithreaded version

Use classes

Since this is supposed to be C++, why not use a class?  Here's a very simple class template that implements something like a bitset.

template <typename T>
class Bits
{
public:
    Bits(size_t sz) :
        bitsperunit{8*sizeof(T)},
        units{sz/bitsperunit + 1},
        bits{new T[units]}
    {
        for (unsigned i=0; i < units; ++i) {
            bits[i] = ~0;
        }
    }
    void clear(unsigned index) {
        unsigned n=index/bitsperunit;
        T mask=1u<<(index%bitsperunit);
        bits[n] &= ~mask;
    }
    bool operator[](unsigned index) const {
        unsigned n=index/bitsperunit;
        T mask=1u<<(index%bitsperunit);
        return bits[n] & mask;
    }
    virtual ~Bits() {
        delete[] bits;
    }
private:
    const unsigned bitsperunit;
    const size_t units;
    T *bits;
};

Now let's reimplement using that class:

void sieve3()
{
    Bits<uint8_t> a(MAX);
    const unsigned long sqrtMAX = std::ceil(std::sqrt(MAX));
    unsigned long i;
    unsigned long j;
    for (i=1, j=2*i+1; i < sqrtMAX; ++i, j+=2) {
        if (a[i]) {  // it's a prime
            for (unsigned long int k = 2*i*(i+1); k < MAX; k += j) {
                    a.clear(k);
            }
        }
    }
    std::cout << "done\n";
    for (i=1, j=3 ; i < MAX; ++i, j+=2) {
        if (a[i]) { // it's a prime
            std::cout << j << '\n';
        }
    }
}

On my machine this is still faster than either of the other two implementations (original or the one above).


I must say, I respectively disagree with @ishyfishy's  example of the addition function. Although, I do agree with the point about splitting the arithmetic functions away from the main function.

I believe that the arithmetic functions should only handle performing the arithmetic; all the I/O should be handled by main function (I have been taught that this is a good practice, although I do not have a source right now).

So, the "1" (addition) section of the switch statement in main would look something like this:

scanf("%f", &num1);
scanf("%f", &num2);

result = addition(num1, num2);

printf("...", num1, num2, result);

And the addition function simply looks like this:

float addition(float num1, float num2) {
    return num1 + num2;
}

This doesn't make a much of a difference, but it speeds up your code a little bit.

Instead of storing the result of a calculation in result, it would be faster to just pass the return value an arithmetic functions into the statement/function that you will it next in.

For example, the end of the "1" (addition) section of the switch statement would look like this:

printf("%.2f + %.2f = %.2f\n", num1, num2, addition(num1, num2));

This is faster because it reduces memory interaction(however, not by much).

In this section:

printf("Enter a number from the list below\n\n");

printf("1. Addition\n"); //Calculator menu, user must enter a value from 1 - 4 for the program to work
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n\n");

You make 5 calls to the printf function when you could easily just put all the strings into one and split them up by newline in a single printf call:

printf("Enter a number from the list below\n\n"
       "1. Addition\n"
       "2. Subtraction\n"
       "3. Multiplication\n"
       "4. Division\n");

This is also faster as you don't have to call a function 5 times.

Only use printf when you are need to use the formatting feature. Other than that, you are over-complicating things.

If you merely need to output a string with a newline here or there, use the built-in puts function; it automatically outputs a string with a newline on the end (and you can add more if needed).

For example, this line:

printf("You entered Addition\n\n");

Becomes:

puts("You entered Addition\n");


Taking advantage of the work previously submitted by @hjpotter92 and adding an extra twist:
def anagram_check(*args ):
    return len( { tuple(sorted(x.lower().replace(' ', ''))) for x in args } ) == 1

This, potentially, gains an additional pythonicity score by avoiding repetition of the sorted(x.lower().replace( ...) construct. Instead, the construct is applied to both arguments in the set comprehension, and the test to see if the resulting set has a single element provides the answer. This implementation also generalizes the API to cover more that two strings if wanted, returning True if all strings given are anagrams of each other (thanks to Heap Overflow for pointing this out).
If you really want a function which is limited to two strings, you might prefer:
def anagram_check(string1, string2):
    return len({tuple(sorted(x.lower().replace(' ', ''))) for x in [string1,string2]}) == 1

The code can be made less terse and more legible by defining a function to act on each string:
def make_unique(x):
     return tuple( sorted( x.lower().replace(' ', '') ) )

def anagram_check(*args):
     return len( { make_unique(x) for x in args } ) == 1


doing cond?false:true is very odd to see and very much prone to mistakes in writing or reading. It's better to use negation in the condition:

bool isEvenlyDivide(int compositeNumber, int number){
  return (compositeNumber % number) == 0;
}

You can reduce the number of checks you do by using the knowledge that you only need to check prime factors up to the square root of wholeNumber, all but one prime is odd:

if(isEvenlyDivide(wholeNumber, 2)){
  return false;
}
for(int isItFactor = 3; isItFactor*isItFactor <= wholeNumber; isItFactor+=2)
    if(isEvenlyDivide(wholeNumber, isItFactor)){
      return false;
    }
}

That can also be used for findNextPrime, speaking of recursion isn't the best way to describe looping until you find something instead prefer an explicit loop:

int findNextPrime(int primeNumber){

    int number = primeNumber+1;
    if(isEvenlyDivide(primeNumber, 2)){
      number ++;
    }
    while(!isPrime(number)){
        number+=2;
    }
    return number;
}

When looping over all primes you can make use of the previous primes you have found to skip the non-primes. This can be done using the for example sieve of Eratosthenes.


Factory pattern for creating sub classes derived from interface with generic type

You have:

public static IPlayerStatsManager Create(DbContext context, int sportType)

And then:

if (sportType == (int)Utils.SportType.Basketball)

Why not just take a SportType parameter and remove that cast?

An abstract factory is a great tool, especially with Dependency Injection. The problem is that yours is a static method, which makes it available just about anywhere in the code, effectively hiding dependencies and defeating the purpose of IoC and DI: that factory becomes some sort of ambient context that's there waiting to be used by anyone, and your constructors don't need to document the fact that you're depending on an abstract factory: that smells IMO.

The factory implementation has one purpose: instantiate types. It has to know what it's creating. Your usage of reflection is nothing but a very convoluted way of saying...

return new BasketballPlayerStatsManager();

The cast to interface is also superfluous - if BasketballPlayerStatsManager does implement IPlayerStatsManager, then that's all the client code will see anyway (of course it implements that interface).

"Manager" sounds like a very general and not-so-precise way of referring to what other programmers would expect to be called a Repository; I'd rename it as such.

return default(IPlayerStatsManager);

You're returning a reference type - the default value can only be null. Your intent would be much clearer like this:

return null;


You should remove this

length = length + namelist.Count() - 1;

because length already includes the spaces.

This

length = length - namelist[i].Length;

should be

length -= namelist[i].Length - 1;

because namelist[i].Length-1 is the number of characters that are removed.

Also: why i >=1 - 1 instead of i >= 0?

You can also do it in a single loop like this:

        for (var i = namelist.Count() - 2; i >=1 && length > 20; i--)
        {
            length -= namelist[i].Length - 1;
            namelist[i] = namelist[i].Substring(0, 1);
        }

        return string.Join(" ", namelist);


User controller for a .net core WebAPI dating app

Errors

An assumption: you never ever want to return a 500 HTTP status code (Internal server error). It may leak information you do not want to expose and it's not informative enough.  Do not throw any exception: return the correct HTTP status code and eventually supplement it with the an appropriate error message. For example if SaveAll() failed because a concurrent request you may return 409 (Conflict). This leads to two more points:

In your code you should almost never catch Exception and never throw it. There are many, more informative, exceptions to use which will play well with your exception handling policy (do you have one, right?).
SaveAll() returning a boolean just to throw an exception is, TBH, sub-optimal. If it's an error condition then it should be an exception (and caller MUST handle it, if it can). A boolean return value can too easily be ignored (and you don't want this to happen if data has not been saved).

You're not catching any exception, if anything happens with the repository then API calls will fail with an internal server error.

Reuse

You parse the current user ID in many functions, move it out to a separate function. Also do not use Int32.Parse() without specifying the culture you want to use (probably CultureInfo.InvariantCulture).

Security

Do not use UserParams both in your repository and in your controller. It smells because:

You can't change them independently.
You have unused values you can specify in the query.
If you add a new field and you forget to handle it in a controller method you might end up with a vulnerability.

ALWAYS validate and translate request parameters (and the easiest way is to have two separate objects). For example userParams.Gender is directly exposed to your repository as an unvalidated string.

UpdateUser() (and LikeUser()) does not actually need the user ID as parameter. Do not require useless and redundant data from the client (which must be validated) when you already have it server-side.

Gender

Do not compare strings using == unless you exactly know what it means. In this case an even simpler and faster ordinal comparison is enough however...

Do not store the gender as a string. If your app is limited to binary genders (at birth) then you may use an enum, however...

Gender is much more complex than a simple binary identity:

Gender at birth is not necessarily binary.
Gender at birth may not be the current gender.
The assigned gender at birth may not be what a person identifies with.
Especially in a dating app it's also important the sexual orientation (which is obviously independent from gender).

In short: do not use an hard-coded list and do not assume gender equals sexual orientation.

Performance

If your app will be successful then you definitely want to avoid to search the likes table (which will grow much faster than the users table) for an entry and to retrieve it only to return Bad request. Best case scenario is to have a simpler function to determine if the entry exists instead of reading, transmitting and mapping the entry itself. See also the next section...

Design

I'm generally against the indiscriminate use of the Repository pattern. It's an invaluable tool but the price you pay in complexity to use it (properly) must be justified. I do not see the big picture here but you should seriously consider if directly using your ORM is enough. From what I see you really need a domain model, much more than a repository.

You have an instance field _repo, you do not show that code but I do not see any synchronization mechanism and I do not see how you dispose its resources when controller is re-created. Generally, in your controllers, you should avoid instance fields as much as possible.

Your API should never ever work directly with the repository to perform any business logic. It should interact with an high-level model (or a Service layer on the top of the Data layer exposed by your ORM). For example I'd imagine the Like feature like this:

public async Task<IActionResult> LikeUser(int recipientId)
{
    using (var service = _serviceFactory.Create())
        await service.AddLike(GetCurrentUserId(), recipientId);

    return Ok();
}

Yes, controller methods should not contain much more than this. All the logic must be TESTABLE then it is much easier to have it elsewhere. Note that in this fictional example I used a factory to create the service object: you may get it directly from your DI framework in the controller ctor but do not create it here (...new MyService()) because you want to test the controller with a mocked service.

Note that the AddLike() is probably implemented with a stored procedure, you really need performance here. Given that user should not be able to click Like for someone he already liked then when it happens it's definitely an error condition and as such it should trigger an exception. Code is probably more complex than this because of error handling but I think you now got the point:

try
{
    ...
}
catch (ItemNotFoundException e)
{
    return NotFound(...);
}
catch (ConcurrencyException e)
{
    // TODO: try again?
}

If you structure well your service layer then you can probably move all this boilerplate code into a function method and reuse it in all controller methods.


Splitting code into separate methods and avoiding the Unit Of Work / Repository pattern

What is the main purpose of the transaction? Is it to handle exceptions and then rollback? Or is there actually something to lock the database/table for everyone for during the creation of social media events. Can be that this is due to the demo code, but I see no need for the transaction itself.

If you remove the transaction, and just do SaveChanges once at the end, then you don't need the transaction. Which solves part of your problem I guess.

    public static void CreateSocialEvent(int employeeId)
    {
        using (var dbContext = new EmployeeEntities())
        {
            var employee = dbContext.Employees.FirstOrDefault(e => e.IsActive && e.IsSocialEmployee && e.EmployeeId == employeeId);
            if (employee == null)
            {
                throw new ArgumentException(string.Format("Unable to find employee by '{0}'", employeeId));
            }

            dbContext.Reminders.Add(new Reminder
            {
                EmployeeId = employee.EmployeeId,
                CreationDate = DateTime.Now
            });

            dbContext.SocialMailingListSubscribers.Add(new SocialMailingListSubscriber
            {
                EmployeeId = employee.EmployeeId
            });

            dbContext.Subscriptions.Add(new Subscription
            {
                EmployeeId = employee.EmployeeId
            });

            var department = dbContext.Departments
                .Include(d => d.Subscribers)
                .FirstOrDefault(d => d.DepartmentId == employee.DepartmentId);
            if (department == null)
            {
                throw new NullReferenceException("Departments could not be found");
            }
            employee.Subscribers = department.Subscribers;

            // Persist to database
            // if we fail to get here due to an exception,
            // the using statement will dispose and the exception will be thrown
            dbContext.SaveChanges();
        }
    }

And you could move some of the creation of object parts, like in the simplest way:

public class Reminder
{
    public int EmployeeId { get; set; }
    public DateTime CreationDate { get; set; }

    public static Reminder CreateForEmployee(int employeeId)
    {
        return new Reminder
        {
            EmployeeId = employeeId,
            CreationDate = DateTime.Now
        };
    }

    public Reminder() { }

    public Reminder(int employeeId)
    {
        this.EmployeeId = employeeId;
        this.CreationDate = DateTime.Now;
    }
}

So you could do:

    public static void CreateSocialEvent(int employeeId)
    {
        using (var dbContext = new EmployeeEntities())
        {
            var employee = dbContext.Employees.FirstOrDefault(e => e.IsActive && e.IsSocialEmployee && e.EmployeeId == employeeId);

            if (employee == null)
            {
                throw new ArgumentException(string.Format("Unable to find employee by '{0}'", employeeId));
            }

            // with a static method
            dbContext.Reminders.Add(Reminder.CreateForEmployee(employeeId));

            // or with the constructor
            dbContext.Reminders.Add(new Reminder(employeeId));
        }
    }

To make it fit on one line, if that is what you want. Or use DI to move the responsibility of creating the object out of the method.


Using Autofac to do DI in a static factory method

What are you registering CommandLineTokenizer etc for? this whole code block is equivalent to

return new CommandLineExecutor(logger);

If all these types are somehow used after all (inside CommandLineExecutor .ctor?), remember that everything created  Per LifeTime scope will be disposed at exit out of using and everything created  Per Dependency scope will become your responsibility to Dispose.


Show and paginate only child categories with wordpress query

The real problem here is that you are querying in loops (almost always a bad pattern) because you are relying on built-in Wordpress querying functions, rather than writing raw SQL to query all this data at once.

My guess is you can do a single query to get both the paginated results and the total number of rows without limit being applied (by using SQL_CALC_FOUND_ROWS).

You might consider opening StackOverflow question specifically about the multiple/slow query problems along with information on your database tables relevant to these queries to get a suggestion on how to write an appropriate query.

Outside of that, I find your code incredibly difficult to read, and while some of that might have to do with following style conventions in Wordpress (which really bad IMO), you should at least indent you code and place comments properly (i.e. not prepending comment on code lines).


PHP handle array when query database with one-to-many relationship

First, let's start with the way your query is formatted.  I would strongly recommend you get in the habit of breaking your query across lines when they get long like this.  I oftentimes use heredoc/nowdoc synteax for this.

For example:

$sql = <<<EOT

SELECT
  r.contact_id,
  contact_name,
  group_id,
  group_name,
  phone_id,
  phone_number
FROM contact r
LEFT JOIN contact_group s
  ON r.contact_group = s.group_id
LEFT JOIN phone_numbers t
  ON r.contact_id = t.contact_id
ORDER BY group_id, contact_id, phone_id

EOT;

This gives you a nice, clean visual presentation for your query in your code.

I think your query as written is a little odd, in that you specify the table for contact_id but not for any of the other columns you are selecting.  Some of your column names may be ambiguous across tables, so I try to make it a practice when writing join queries to specify the table names for ALL columns to remove ambiguity for the reader.

I would also suggest aliasing the columns.  If you want to refer to contact_id in your PHP code like you are doing, then you MUST alias r.contact_id to this like r.contact_id AS contact_id.

Finally, you should consider meaningful table aliases if using them (I actually typically do not use them except for sub-selects that need to be aliased).  What do r, s, and t mean? Why not c, cg, pn or similar?

That could leave you with a query like:

$sql = <<<EOT

SELECT
  contact.contact_id AS contact_id,
  contact.contact_name AS contact_name,
  contact_group.group_id AS group_id,
  contact_group.group_name AS group_name,
  phone_numbers.phone_id AS,
  phone_numbers.phone_number AS phone_number
FROM contact
LEFT JOIN contact_group
  ON contact.contact_group = contact_group.group_id
LEFT JOIN phone_numbers t
  ON contact_group.contact_id = phone_numbers.contact_id
ORDER BY group_id, contact_id, phone_id

EOT;

This is a little more verbose, and might take you a minute or two of extra typing when initially writing the query, but it has the effect of removing any ambiguity for what your query is doing for the reader.

Outside of format, your query seems odd in that it doesn't seem to match the relations you have noted.  You said the relationships are:

Contact Group ---(has)---> Contact ---(has)---> Phone number

Yet your joins would seem to suggest relations of:

Contact ---(has)---> Contact Group ---(has)---> Phone number

Can a contact exist that does not belong to a contact_group?  Your query suggests this is the case (due to LEFT JOIN), which would beg the question, how are you handling the nulls that could be returned for contact_group fields in such a case?

You are taking a very standard approach to populating a multi-dimensional array from a results set that represents one-to-many relationships.

I do question however if this is an appropriate approach given the fact that you are using LEFT JOINs here. As noted above, you could have null values for the contract group information and the phone number information.  You don't seem to be considering this at all.

This is especially critical given the fact that the contact group ID is the very first dimension in your array.  Are you really intending to group on null in this first dimension (technically such values would actually be assigned to an empty string array key)?

Since JSON can only represent two data structures - a numerically-indexed array, or an object - I would think that a numerically-indexed array would make more sense as the first dimension, meaning you might end up with JSON like:

[
    {"group_id": 1, ... },
    {"group_id": 2, ... },
    ...
]

I think numerically-indexed arrays might also be used to hold the contacts and phone number data nested underneath the contact group.

You are treating all values from the result set as strings (the way they are represented by default when retrieving from mysqli_fetch_array()).  Is this desired behavior, or does it make sense to cast primary key id's, for example, as integers?

Putting aside the problems noted above around LEFT JOINS and null.  I would suggest that you consider working with each row of your results set as an object.  IMO, this can make your code a lot cleaner and, in most cases, actually more truly represents what you are working with (an object representation retrieved from DB).

Taking this approach, as well as taking the approach noted on using numerically-indexed arrays for contact groups, contacts, and phone numbers, you might end up with something more like this:

$data = array();
$group = new stdClass();
$group->group_id = 0;
while ($row = mysqli_fetch_object($query)) {
    // build new contact group if needed
    if((int)$row->group_id !== $group->group_id) {
        // break existing reference between $group and $data
        // data in $data will remain after this dereferencing
        unset($group);
        $group = new stdClass();
        $group->group_id = (int)$row->group_id;
        $group->group_name = $row->group_name;
        $group->contacts = array();
        // build reference from group to location in $data
        // this allows you to simply work with $group here in loop
        // as opposed to $data[$index] which requires you to manually
        // track index values
        // taking similar apporach below for contacts as well eliminates
        // $data[$group_index]->contacts[$contact_index]->phone_numbers[]
        // types of references
        $data[] =& $group;

        // reset $contact
        unset($contact);
        $contact = new stdClass();
        $contact->id = 0;
    }
    // build new contact if needed
    if((int)$row->contact_id !== $contact->id) {
        // dereference contact
        unset($contact);
        // create new contact
        $contact = new stdClass();
        $contact->id = (int)$row->contact_id;
        $contact->name = $row->contact_name;
        $contact->phone_numbers = array();
        $group->contacts[] =& $contact;
    }
    // add phone number to current contact
    $phone = new stdClass();
    $phone->id = (int)$row->phone_id;
    $phone->number = $row->phone_number;
    $contact->phone_numbers[] = $phone;
}
unset($group, $contact, $phone);

You will note that taking this approach means that you are truly only building a single logical representation (a stdClass object) for each contact group and contact and simply adding phone numbers to the current contact and adding contacts to the current group.   I think thinking in terms of objects here really makes the code more meaningful in a real-world sense than building out a convoluted associative array.  Considering the JSON serialization converts both objects and associative arrays to object notation anyway, there really seems to be no value to using associative array here.


Project Euler #12 in C++ - highly divisible triangular number

This:

int i = 2;
while (overall_factors(i) < 500)
{
    std::cout << overall_factors(i) << std::endl;
    ++i;
}

can just be a for-loop:

for (int i = 2; overall_factors(i) < 500; ++i)
{
    std::cout << overall_factors(i) << std::endl;
}

I'd also recommend using a constant for 500 as it is otherwise a magic number.  This will make it clear as to what this value represents.

If the number isn't significant to the general algorithm, then a comment can be added instead.
There is no need for divisors to just return a 0.  It appears it's just modifying the map and displaying it.  Also, these are two different things, and a function should just have one role.  In this case, it should just modify the map.  You should then have a separate void function for displaying the map in the desired format.

Although passing the map by reference is okay here, passing it by value (in C++11) will also allow the compiler to decide to perform a move, if desired over a copy.


Logging and getting the response in a controller

First of all, the first code is perfectly fine in matter of conciseness and readability. You're being a lil bit obsessive, but it's not perfect in matter of  design.

Second, if I really had to do so to just improve the readability, I would refactor retrieveResponseFromWrapper() to accept a, let's say, WrapperRequest instance. On the other hand, I would refactor extractChainAndTunnelFromForm() to a createWrapperRequestFromForm() which obviously returns a WrapperRequest instance after its own internal processing of form data:

if ($form->isValid()) {
    $request  = $this->createWrapperRequestFromForm($form);
    $response = $this->retrieveResponseFromWrapper($request);

    // If you wanna go shorter for the sake of sanity:
    //
    // $response = $this->retrieveResponseFromWrapper(
    //     $request = $this->createWrapperRequestFromForm($form)
    // );

    // I also recommend to move this out, controllers just log access things
    $this->get('command_logger')
         ->log($request->getChain(), $request->getTunnel(), $response);
}

Now that I wrote it, you see, it's shorter and more unreadable! IMO shorter code and minimal number of methods are not necessarily an indication of more concise and readable code. The number of statements in a if block is not an effective factor to measure readability.

I remember when I was trying to find one-liners for every damn single thing I wrote. I went insane and even swapped ifs with equivalent AND/OR statements. It was of course a pleasure but I've learnt to embrace simplicity and verbosity in order to be more readable for others.

Back to the design thing; The above code is a better code, not because it's shorter or it has just one return value, but because it separates your domain logic apart from the controller and it avoids implementation leaks. This controller does not know about $tunnel and $chain, it just transports them as blackbox data. That's why we often need Data Validation components separated from the controller and the Form Validation component.

I think that would be a better idea to refactor our controllers as just a Transport Layer around HTTP instead of such minor improvements. To pursue this I always think that my app needs be fully functional when the data is fed through terminal instead of HTTP, without regular forms.

To conclude; A reader must always tend to read the code in Service/Repo/Model/... classes in order to understand the business logic. Reading the controller code of a well-designed application must be boring cause it's just the means not the thing!


Dividing by the total count based on occupation

Aliases

The aliases you have used in this query, K and CO, are meaningless. I would recommend using either the full table name, if it is short enough, or using a meaningful alias, such as People, Jobs or Fruit for a tables containing information regarding People, Jobs and Fruit respectively.

I would recommend always including AS when using an alias to prevent confusion.

X = 0, X= 0 or X =0?

Okay first things first, you have examples of X= 0, X = 0 and X =0. You should choose find a style you like and can read well and stick with it. I'd recommend X = 0. I find it easier to understand where each side of the statement ends with the separating spaces.

Joins

Next, we have this bit:

INNER JOIN TABLE2 CO ON(CO.id= K.id AND CO.status= 'Something' AND K.statuscode = 0  AND CO.statuscode =0))

Firstly, you don't need brackets around the ON part of this. Adding the unnecessary brackets can just end up confusing you. If you had used a combination of ANDs and ORs in the ON clause, then you would use brackets to make sure the statement is executed as you intended.

Secondly, you are checking that both statuscodes are 0 in the ON clause. The correct way to do this would be to make sure you only bring back records where the statuscodes are the same, and check one of the statuscodes in the WHERE clause.

Thirdly, CO.status = 'Something' should also be moved into the WHERE clause.

Lastly, is there a reason that the subquery uses INNER JOIN and the main query uses LEFT OUTER JOIN?

A Suggestion

Might I suggest removing the subquery and calculating the total number of jobs and storing the result in a variable? This should speed things up a little and make the main query a little easier on the eyes.

Bringing It All Together

This is what I ended up with:

DECLARE @Total_Jobs INT =
(
    SELECT COUNT(CO.Code)
    FROM TABLE1 AS K
    INNER JOIN TABLE2 AS CO
    ON CO.id = K.id AND CO.statuscode = K.statuscode
    WHERE CO.status = 'Something'
    AND K.statuscode = 0
)

SELECT CONVERT(VARCHAR,COUNT(CO.code)*100/@Total_Jobs)
FROM TABLE1 AS K
LEFT OUTER JOIN TABLE2 CO
ON CO.id = K.id AND CO.statuscode = K.statuscode
WHERE CO.status = 'Something'
AND K.statuscode = 0
GROUP BY K.occupation
ORDER BY COUNT(CO.Code) DESC


Counting number of nodes between two nodes

Your program is really based only of case where you have 5 nodes. This make your code really hard to change if you want to have a "list" of node of a different size.

The name of the class should represent a concept not an action, CountNodesBetweenTwoNodes could be something like CircularList or something like that. A name that would represent what the class is, not what it does.
Personally, I find that re-using the first argument in the loop to iterate over the list is not what I would want. I would use a third Node variable to let to show that I'm iterating and that my firstNode will not change during this method.

private int countNodesBetweenTwoNodes(Node firstNode, Node secondNode) {
    int count = 0;

    while(firstNode.next != secondNode) {
        count++;
        firstNode = firstNode.next;
    }

    return count;
}

I would rename the class variable Node fifth for Node last, what if you have more than five nodes ? Would you change your code ? I hope not, so by changing the name to represent that it's the last one, we are good to not limit our-self to five nodes.
Since we changed the name of the variable, we should change public Node getFifth() too for public Node getLast().
You should always specify a visibility for you class variable. Currently, first and fifth are package visibility, they should be private.
There is a bug in your class: you made your countNodesBetweenTwoNodes private. If I want to use your class myself, I could not use this method since I would not be in your class. You don't have this problem since you use the method in your main which is in the class. If you move your main method to another class, your program is not working anymore.


Extending Object.prototype in JavaScript

There are extraneous semicolons (null statements) in your code. Semicolons do not belong after function declarations and for loops.

  I'm extending the Object.prototype which should be fine.

I would argue that it's not fine. While it's unlikely to cause undesired side effects, breaking encapsulation and polluting all objects just for the sake of being able to write foo.removeMatching(bar) instead of removeMatching(foo, bar) seems like bad form.

if (!Object.prototype.hasOwnProperty.call(this, key)) continue;

Since this is an Object by definition, because you are attaching this to Object.prototype, there is no need to write it like that. This would achieve the same thing (unless you are shadowing hasOwnProperty in which case you have bigger problems):

if (!this.hasOwnProperty(key)) continue;

However there's no need to write this line in the first place. If the object doesn't have a property as its own property, attempting to delete it will do nothing.

  It's all gets enclosed in a closure to prevent namespace pollution.

This also seems unnecessary, why not just write it like this:

Object.defineProperty(Object.prototype, 'removeMatching', {
    value: function (predicate) {
        for (var key in this) {
            if (predicate(key, this[key])) {
                delete this[key];
            }
        }
    },
    writable: false,
    configurable: false,
    enumerable: false
});


Let's look at the code.

from random import randrange
import time

Your imports are very minimal! Good.

# Snow animation
# Snow is simply the `#` symbol here. Half of the snow moves at 1 char
# per frame, while the other half moves at 0.5 chars per frame. The
# program ends when all the snow reaches the bottom of the screen.
# The viewing area is 80x25. It puts 100 snow flakes to output, half
# fast, and half slow. Every frame it dispenses 4 flakes, 2 fast and
# 2 slow ones, at random locations at the top of the viewing area.

This looks more like a docstring to me. It would be nice to render it as such. You can do this by dropping the # signs, and surrounding it in """ quotes.

screen = {'x': 80, 'y': 20}
drops = []

Global variables are not that nice. But this is a simple file, so maybe we can leave it like this for now? Let's.

def createRainDrop(x, y, speed):
    return {'x': x, 'y': y, 'speed': speed}

I think something like a class would be better for this. Let's try

class RainDrop(object):
    def __init__(self, x, y, speed):
        self.x = x
        self.y = y
        self.speed = speed

Of course, now we need to replace createRainDrop(...) with RainDrop(...), and drop['...'] with drop.....

def createRandomDrops():
    dropCount = 4
    for i in range(dropCount):
        yield RainDrop(randrange(0, screen['x']), 0, min((i % 2) + 0.5, 1))

That's better.

def moveDrops():
    for drop in drops:
        drop.y = drop.y + drop.speed

We're modifying drop here, instead of asking it to modify itself. We should be writing something like drop.moveDown() here, or maybe drop.tick() ('tick' is what's commonly used to notify an event about stepping forward in time).

def drawDrops():
    out = [''] * screen['y']
    for y in range(screen['y']):
      for x in range(screen['x']):
        out[y] += '#' if any([drop.x == x and drop.y == y for drop in drops]) else ' '

    return '\n'.join(out)

Here, for all the positions on the screen, you're looping over all the drops. Ideally we'd turn that around:

def drawDrops():
    out = [[' ' for _ in range(screen['x'])] for _ in range(screen['y'])]
    for drop in drops:
        if int(drop.y) < screen['y']:
            out[int(drop.y)][drop.x] = '#'

Now that's a bit faster and cleaner.

def dropsOnScreen():
    return any([drop.y < screen['y'] for drop in drops])

Makes sense. Except I'd suggest to not use the [...], which creates a list. Better to use

def dropsOnScreen():
     return any(drop.y < screen['y'] for drop in drops)

This behaves the same, but does not have to create an intermediate list.

drops += createRandomDrops()

while dropsOnScreen():
    if len(drops) < 100:
        drops += createRandomDrops()

    print(drawDrops())
    moveDrops()
    time.sleep(0.100)

You want to get rid of the duplicated call to drops += createRandomDrops().

while True:
    if len(drops) < 100:
        drops += createRandomDrops()

    if not dropsOnScreen():
        break

    print(drawDrops())
    moveDrops()
    time.sleep(0.100)

But in my opinion, the extra createRandomDrops is not that bad.


Your algorithm makes the probabilities of some numbers much higher than other numbers. Is this intentional? For example, 0 will appear 3 times as often as 1. It would be better to simply have the input string "0123456789" and have the uniform distribution.

The range you supply in your for-loop is confusing, the requirements are for 6 digits, but, you use the magic-number 5. in the random. Consider using:

val shortest = 6
val longest = 10
val len = shortest + rnd.nextInt(longest - shortest + 1)
for (i <- 1 to len)

That is enough of an answer, on it's own, but I would suggest you consider the following. It is a little flawed in the sense that it never generates a value with a 0 as the first character.... I was part way through the answer when I realized this, but thought you should consider the approach anyway:

def randomNumericalString(): String = {
    return ((100000.0 + rnd.nextDouble() * (10000000000.0 - 100000.0)).toLong).toString
}

The above will generate a random number, with uniform distribution, between 100000 and 9999999999 (and here, as an ideone )


Extracting first non-null property inside list using Java 8's Optional

The problem here is that your Optional would be required to either return your method or to continue with the next loop iteration. This cannot be expressed that way in Java.

One solution is to convert from external iteration (using the for loop) to internal iteration using a Stream. You can find a lot of documentation for working with streams (start with the Javadoc for Stream and the java.util.stream package), so I won't go into low level details here.

addresses.stream()
    .map(Address::getHouse)
    .map(House::getNumber)
    .filter(number -> number != null)
    .findFirst();

This executes the mappings, drops all numbers that are null and returns the first non-null number. It solves the return-vs-continue problem, but it won't work as expected because Stream.map(…) will happily put a null value in the resulting stream. You would get a NullPointerException at map(House::getNumber) if some Address has no House.

You can use your original Optional chain as mapping function and your method would look like this:

private static String getFirstHouseNumber(List<Address> addresses)
{
    return addresses.stream()
            .map(address -> Optional.ofNullable(address)
                    .map(Address::getHouse)
                    .map(House::getNumber))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .findFirst()
            .orElse(null);
}

This looks more concise than your first method but it is not really that obvious what is going on. You can probably guess it but to say for sure you will probably need some moments.

Maybe one can come up with something a bit more readable but I'm afraid that given the current setup it won't get much better.

To get much more benefit (not just for this case but for the whole application) you may think about refactoring.

Note that the following may or may not be useful. As I don't know the rest of your application this are just some observations and hints from the perspective of this code snippet.

I see two main problems here:

Extensive use of null
Violation of law of Demeter

Is it really the case that all of your properties may be null here?

I guess each Person should have some Metadata (even if sparsely filled). You can always get a list of known addresses for a person. This list may be empty but it should not contain null values. An Address should always have a House on it if some Person lives there. So the only thing that may be null is the house number (e.g. if you know the person lives in city X but you don't know the exact street and house number).

Does your code at this point really have to know how your person is structured internally?

From the perspective of the code above I would expect to get a list of addresses directly from the person. I don't care about the metadata. Similarly I don't care about the house.

Maybe you check the house number for null just to verify if the address is complete? Maybe what you are actually looking for is the first valid and complete address of some person?

If all this assumptions apply, your code could look like this:

public Optional<Address> getValidAddress(Person person) {
    return person.getAddresses().stream()
            .filter(Address::isComplete)
            .findFirst();
}


Storing icons statically as strings in custom class

I do something similar, except rather than creating my own class, I create a UIImage class category.

File names are called UIImage+Icon.h and UIImage+Icon.m.

In the .h, we have this:

@import UIKit.UIImage;

@interface UIImage (Icon)

+ (UIImage*)someIcon;
+ (UIImage*)someOtherIcon;

@end

And then put your code in the .m as normal.

Be sure to note @import UIKit.UIImage; versus the #import.  You don't need to import the entire UIKit.  @import is new in Xcode 5 and vastly speeds up compile time as it only imports the required modules.

Anyway, the advantage to this versus what you're doing is that we call our methods as such:

[UIImage someIcon];

It's clear as day that we're definitely returning a UIImage object, because we're calling a UIImage class method.

EDIT: Having just noticed that your class also includes a method which returns NSString, I still recommend the class category.  In this case, the imageToNSString method would look like this:

- (NSString*)toEncodedString;

The method doesn't take an argument because it is an instance method.  Because this is a UIImage class category, you can refer to self, which gives you the UIImage instance on which this method was called.

I personally like the UIImage class category, but another option that is still potentially better than what you're doing would be to create C-style functions.

So you'll have a .h file that would include this function declaration:

UIImage * imageFromString(NSString *str);

As well as a list of NSString * const objects that you send as arguments.  Then your .m, you've just got the logic for returning an image from a string.

The main point here is that there are two options here that don't involve a class called Icon.  The problem is, if there's a class called Icon, I kind of expect to be working with Icon objects in some way.  And I might even try to instantiate an Icon object, which makes no sense...

Ultimately though, if you're NOT going to create a UIImage class category OR use C-style functions and still work with the Icon class, since you only have class methods and your class certainly shouldn't be instantiated, I highly recommend adding this to your .h file:

+ (id)alloc __attribute__((unavailable("Icon class can not be instantiated")));
- (id)init __attribute__((unavailable("Icon class can not be instantiated")));

This will throw red errors and prevent compilation if anyone tries to instantiate the Icon class.  This is the worst option of the three I purposed in this situation, but it can be acceptable in some cases perhaps.


isBalanced function for checking if string with brackets is balanced ([{}])

openBrackets can be a Set

openBrackets is only used to test if a character is an opening bracket. So, it can be declared like this:

const openBrackets = new Set(['(', '[', '{']);

and the test will become:

if (openBrackets.has(arr[i])) { ... }

Use for...of to iterate

The for ... of syntax avoids having to work with indices, as in this case you don't need the i variable at all (except to dereference the correct character from arr). Furthermore, you can iterate the string directly, without having to .split('') it first:

for (let c of string) {
  if (openBrackets.has(c)) {
    open.push(c);
  } else if (closedBrackets[c] && open.pop() !== closedBrackets[c]) {
    return false;
  }
}

Rename closedBrackets

Reading the name of this variable I would expect some sort of collection of brackets, not a mapping/correspondence between closing and opening brackets. Therefore, I would give it a different name. Something like bracketCorrespondence might work, although there might be some better names for it out there.

So, here's a version of the code with these suggestions applied:

const isBalanced = (string) => {
  let open = [];

  const openBrackets = new Set(['(', '[', '{']);

  const bracketCorrespondence = {
    ')': '(',
    ']': '[',
    '}': '{',
  };

  for (let c of string) {
    if (openBrackets.has(c)) {
      open.push(c);
    } else if (bracketCorrespondence[c] && open.pop() !== bracketCorrespondence[c]) {
      return false;
    }
  }

  return !open.length;
}

console.log(isBalanced('') === true);
console.log(isBalanced('()') === true);
console.log(isBalanced(')()') === false);
console.log(isBalanced(')(') === false);
console.log(isBalanced('()(()()()())') === true);
console.log(isBalanced('[](){}') === true);
console.log(isBalanced('[({})]') === true);
console.log(isBalanced('[(]{)}') === false);
console.log(isBalanced('const sth = () => { animal.sleep();') === false);
console.log(isBalanced('const sth = { bark: animal() }') === true);


In-Memory FileSystem in Java - Is there a better OOP approach?

create Subclasses / interfaces
if you think there is a difference in Behaviour then there is a need for a seperate class - if you think some classes have something in common, extract an interface!
so create a class Directory and a class File. Let both classes implement the Node Interface. (Note - in Java we don't use the hungarian notation )
inconsistency // oo-abuse
what's the purpose of Node if you don't use it? compare these two approaches

public List<String> ls(String path) vs.
public List<Node> ls(Node path)

in case 1 it is absolutly not clear how the String path should look like, especially since it is OS-dependant. (what would String[] subdirs = filePath.substring(1).split("/"); on other OS do?) It is also not clear what kind of output this Method delivers
in case 2 we have cleary declared what kind of input we expect, (even though i'm missing a parent attribut - that would ease up the searching) - we reduce the problem with different OSes to the single place where it belongs: at the constructor of the Node (Single responsibility). And we have a very accurate output (compared to the List<String> from case 1 - how would we know if a String is a Directory or a File? Node already provides all these information!)
File System vs. Editor
i'm not sure how addContentToFile() and readContentFromFile match for a FileSystem - in my opinion these two methods belong to an Editor/Viewer and not the the File System - create an Editor (an Editor class)!
think of the possibilities: you can then provide different Editors for different file Types?
Error Handling
i would expect a file system to be a bit more chatty about IllegalArgumentException (why are none thrown? how is such case treated?)


Generating HTML for prerolled d20 RPG initiative tables

I wouldn't use strings at all. I would write to a stream.

If wished, I would convert the stream to a string.

(defun d20 () (+ 1 (random 19)))

initlist can be written more compact:

(defun initlist (specs)
  (sort (loop for (a b) in specs collect (list a (+ b (d20))))
        #'> :key #'second))

Now we pass a stream to htmlinitlist and write the contents to the stream:

(defun htmlinitlist (specs stream)
  (write-string "

&nbsp;	&nbsp;
" stream)
  (loop for (a b) in (initlist specs) do
        (format stream
                "
~A	~A

&nbsp;	&nbsp;
"
                a b))
  (write-string "
" stream))

If we want to get a string from a stream, we can use with-output-to-string. This binds a stream variable, which we can use and pass around...

(defun htmlinitlists (specs count)
  (with-output-to-string (stream)
    (write-char #\space stream)
    (loop repeat (1+ count) do (htmlinitlist specs stream))))

Alternate version of htmlinitlist using only one FORMAT call:

(defun htmlinitlist (specs stream)
  (format stream
          "

&nbsp;	&nbsp;
~
           ~{
~A	~A

&nbsp;	&nbsp;
~}~

"
          (loop for (a b) in (initlist specs) collect a collect b)))

Benefit

All the various string operations (which are creating lots of intermediate strings which are immediately garbage) have been replaced with the usual output functions and a stream.


Algorithm:
It's brute-force, but for ten elements that's fine.  However, I don't think it will work correctly - it's going to stop at five pairs regardless of how many were generated.

Also, the outer loop should stop before the last element and the inner loop should start one after the current value of the outer loop.  Otherwise you're just making the same comparison multiple times.

The main thing I would suggest that there are other data structures besides basic arrays.  In this case, a vector of pairs would work well.

std::vector<std::pair<int,int>> results;

...

results.push_back(std::make_pair(input[a], input[b]));

...

if(results.size() == 0)
{
    std::cout << "No sum of integers found to equal desired total.\n";
}

...

for(int i = 0; i < results.size(); ++i)
{
    std::cout << '(' << results[i].first << ", " << results[i].second << ')';

.
.
Style:
Always put brackets around your blocks, especially when there's a matching block that does have them (the if/else for showing the results).

Give variables meaningful names, and don't re-use them just because they're the same type.  Also, you don't need to (and usually shouldn't) declare them all at the top of the method; declare them where they're used.

Separate the target number as its own variable, having it as the last item of the input array is less clear.

If you're not calling them anything more specific, i and j are the usual convention for loop variables.

The fake delay for "critical calculations" that in fact are already done is a bit silly. :P


Size improvements for cat reimplementation

Do not repeat yourself. Copying stdin doesn't differ from copying any other file. There is no need to special case stdin as you do at lines 15-21.
Avoid naked loops. Every loop does an important job that deserves a name. This is strong enough reason to factor it out as a function:
Expect errors

fgetc may fail. Once fgetc returns EOF, call feof or ferror to see what has actually happened.
printf may fail. Make sure to detect (printf returns -1) and report (analyze errno) errors.

Handle options. At least recognize a standalone - as a fake file name referring to stdin.


With your three globals, it's not clear what memo is from looking at it. Try previous_values instead. Additionally, populating the list with memory at the beginning makes me think they're related, which I'm not sure is actually the case.

boardrider suggests passing your globals as arguments to functions. I agree that this would be a good idea. Another approach would to just wrap it all in a Calculator class. Classes are good for managing state.

Your undo function is a bit weird:

def undo():
    """Restores the previous value. """
    global memo

    if len(memo) >= 2:
        global current_value

        current_value = memo[-2]

        memo.pop(-2)

The previous current_value remains in memory, which makes me not trust it. What happens if you repeatedly undo, then operate? I haven't stepped through to verify, but I suspect a bug.

I'd try this instead:

def undo():
    if len(memo) >= 2:
        global current_value
        memo.pop()
        current_value = memo[-1]

This would maintain the invariant that the current value is always the last item in the list.

My final comment I am much less unsure of, and is probably down to a matter of personal taste:

I'm not sure about this part of your division:

if is_divisible(current_value, to_div):
    current_value //= to_div
else:
    current_value /= to_div

Is this just to help prevent floating-point rounding errors? I think this is overcomplicating things without fully addressing the problem. What I mean is that I could contrive to multiply together two floating-point numbers that have the same value of integers, and it would yield another floating-point int-like number, which is what it looks like you're trying to avoid here. I just don't see value in worrying about this in one specific case.

As another idea, you could do something like if current_value == int(current_value): current_value = int(current_value) after each op.


Login System using PHP and PDO Prepared Statement

How safe is my code?

I would suggest if you protect the login form from

CSRF (Cross site request forgery) Attacks by generating a unique code for each session and assigning it to a hidden field in the form, and check every post request whether it matches the one from the session or not.

<input type = "hidden" name="token" value="' . $_SESSION['csrf_token'] . '">

Example: ignore naming convention

   class token {

     public static function generate_csrf_token() {
           if (!isset($_SESSION['csrf_token'])) {
              $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
           }
        }

    public static function check_csrf_token($token) {
        return $token === $_SESSION['csrf_token'];
    }
 }

Then you want to check when the form is submitted and compare both token.

Timing attacks, disable logins requests under a second, mostly bots and robots.

    //Gets the value when the page loads and set it in a session
    $start = microtime(true);

    if (!isset($_SESSION['microtime'])) {
     $_SESSION['microtime'] = $start;
    }

and after the login button is clicked, check and perform the same and then compare the time

if (isset($_POST['submit'])) {
   $finish = microtime(true);
   $seconds_passed = $finish - $_SESSION['microtime'];
   if ($seconds_passed < 1) {

?>

Limit requests from an ip, so for example say, 3 requests maximally allowed per a second, to protect from lots of attack.
Putting captcha and login attempts will be useful.
Session Hijacking multiple things:

Have an identification method that is making each user unique (perhaps hashing user agent and ip) and check every request if they match to see if the current user is the same. And have a session requests tracker that would re-assign a new session id after 25 requests for example.

 if (!isset($_SESSION['session_clicked_times'])) {
            $_SESSION['session_clicked_times'] = 1;
        } else {
            if (($_SESSION['session_clicked_times']) >= 25) {
                $_SESSION['session_clicked_times'] = 0;
                session_regenerate_id(true);
            }
            $_SESSION['session_clicked_times'] += 1;
        }

Also generate a new id once logged in, and so on.

This code:

 if( $RowCount == 0 ){
   // error
  } else{ // User exists

      if(password_verify($_POST['password'], $user['password'])){

     //login

      } else {
         //error
        }
    }
}

to just this (since they both handle the same thing in your case)

 if( $RowCount == 0 || !password_verify($_POST['password'], $user['password']) ){
       // error
      } else {
       //login
    }


NO NO NO NO NO!

Besides what others have pointed out, I find some serious flaws in your code.

You are not actually using blowfish. To use blowfish, your salt must begin with something like $2y$07$ see the PHP Documentation
Removing your $blowfish_salt variable from the code makes no difference! This will produce the same output. Therefore, we conclude that you are actually using a constant salt in your code.
The output of crypt is more secure than MD5. MD5 is an algorithm that is known to have a lot of duplicates. Many different inputs will produce the same results. That's not optimal. Using real blowfish algorithm is even more secure than what you currently have.

Here is some testing code I used to come to my conclusions:

<?php
$password = "bubu";
  $blowfish_salt = bin2hex(openssl_random_pseudo_bytes(22));

$blowfish_salt = "11b19e4e03d32f27f9db5646e56f63458113e9da56f7"; // Since this is the only randomness, I have replaced the randomness with this constant.

echo "salt is $blowfish_salt
";

$first = crypt($password, "X1;G^COU8U`Bo*A6@9<on5yQ6P87M]".$blowfish_salt);
echo $first . " ... constant with what you call blowfish
";

$hash = md5($first);
echo $hash . " ... md5-ed version of above. This is the result of your current code
";
echo md5(crypt($password, "X1;G^COU8U`Bo*A6@9<on5yQ6P87M]")) . " ... and oops, that was exactly the same!
";

$first = crypt($password, "X1;G^COU8U`Bo*A6@9<on5yQ6P87M]");
echo $first . " ... constant salt
";

$first = crypt($password, $blowfish_salt);
echo $first . " ... only blowfish salt
";
echo "
";
echo "BELOW USING 2Y PADDING:
";
echo "
";
$first = crypt($password, "\$2y\$07\$X1;G^COU8U`Bo*A6@9<on5yQ6P87M]".$blowfish_salt);
echo $first . " ... a lot, with blowfish. Causes error because salt is too long
";

$first = crypt($password, "\$2y\$07$\X1;G^COU8U`Bo*A6@9<on5yQ6P87M]");
echo $first . " ... constant salt. Still causes error because salt is too long
";

$first = crypt($password, "\$2y\$07\$".$blowfish_salt);
echo $first . " ... only blowfish salt. And now THAT is blowfish!
";

echo "
";
echo "Now back to md5 with this result again:
";

$hash = md5($first);
echo $hash;
?>

The output of this is:

salt is 11b19e4e03d32f27f9db5646e56f63458113e9da56f7
X154A2VqJVf4I ... constant with what you call blowfish
7b5f3730488255efcff9441a238d5c5d ... md5-ed version of above. This is the result of your current code
7b5f3730488255efcff9441a238d5c5d ... and oops, that was exactly the same!
X154A2VqJVf4I ... constant salt
11Xw1fe5HDjyo ... only blowfish salt

BELOW USING 2Y PADDING:

*0 ... a lot, with blowfish. Causes error because salt is too long
*0 ... constant salt. Still causes error because salt is too long
$2y$07$11b19e4e03d32f27f9db5uyeLJeUJh/VUoi1RFtAoDAE.eegj4bwO ... only blowfish salt. And now THAT is blowfish!

Now back to md5 with this result again:
e35cb490b47d3211dac9f85acfc2fb15

Please, take your time and study these results. Look at the code. Look at the results. Look at the code again. Look at the results again. Now look at the code one more time: Do you see the flaws? If you don't, I pointed them out at the beginning of my answer.

What you should do:

Generate a salt, store that somewhere (as suggested by Chris). Get rid of that constant-salt you have.
Use the real blowfish, and don't use MD5 afterwards

public function Pass_Hash ($password, $blowfish_salt) {
      $hash = crypt($password, "\$2y\$07\$" . $blowfish_salt));
      return $hash;
}
$generated_salt = bin2hex(openssl_random_pseudo_bytes(22));
Pass_Hash("a very secret password", $generated_salt);

Now we're talking.

However, I should add that I am not a security experts. There are likely several more aspects that one can think of. If you are interested in security and secure stuff, I recommend paying our StackExchange friends at Information Security a visit. But in the end I think that the question is: How secure do you want to be?


Verifying boardgame mathematics with MATLAB

Discussion

You have three dice, which you can assume to hold three places for 1, 2, 3, 4, 5, 6 and the four operations +, -, *, / would hold the two in-between places, which are shown as square brackets and round brackets respectively as shown in this blueprint - [] () [] () [].

The total number of possible combinations would be 6*4*6*4*6 = 3456. Out of these, you need to find the valid ones based on flooring and values in the range [1 100].

Looking at your code, I don't think -x+y would be a valid one, because you can't just pre-append a operator. If that is to be allowed, why not multiplication operator too? Moreover -x essentially means -1*x, for which you are already using two operators - - and * and assuming one of y or z to be 1. For these reasons, I am guesstimating, -x+y to be an invalid one, unless it says in the instructions manual to be a valid one.

Again, x\y won't induce anything new, as we are already juggling through all values of 1 to 6 across all three places around the four operators, as shown in the blueprint earlier.

Code

Considering all the assumptions and avoiding the "scandalous" cases, we would have this vectorized code -

%// Define possible values of x, y and z, denoting values from three dice
x = 1:6;
y = 1:6;
z = 1:6;

%// t1 would take care of x and y and the one operator in between
t1 = [bsxfun(@plus,x',y) ; bsxfun(@minus,x',y) ; bsxfun(@times,x,y') ; bsxfun(@rdivide,x,y')]

%// t2 would take care of x, y and z and the two operators in between
t2 = [bsxfun(@plus,t1(:),z) ; bsxfun(@minus,t1(:),z) ; bsxfun(@times,t1(:),z) ; bsxfun(@rdivide,t1(:),z)]

%// Get the valid ones based on flooring and limiting within the range [1 100]
t2 = t2(t2==floor(t2) & t2<=100 & t2>=1)
freq = tabulate(t2)

Output

freq =
    1.0000  151.0000    7.6186
    2.0000  157.0000    7.9213
    3.0000  146.0000    7.3663
    4.0000  148.0000    7.4672
    5.0000  130.0000    6.5590
    6.0000  150.0000    7.5681
    7.0000   94.0000    4.7427
    8.0000  106.0000    5.3481
    9.0000   87.0000    4.3895
   10.0000   89.0000    4.4904
   11.0000   53.0000    2.6741
   12.0000   91.0000    4.5913
   13.0000   35.0000    1.7659
   14.0000   37.0000    1.8668
   15.0000   46.0000    2.3209
   16.0000   36.0000    1.8163
   17.0000   14.0000    0.7064
   18.0000   41.0000    2.0686
   19.0000   10.0000    0.5045
   20.0000   34.0000    1.7154
   21.0000   16.0000    0.8073
   22.0000   10.0000    0.5045
   23.0000    7.0000    0.3532
   24.0000   42.0000    2.1191
   25.0000   16.0000    0.8073
   26.0000    7.0000    0.3532
   27.0000   10.0000    0.5045
   28.0000   11.0000    0.5550
   29.0000    5.0000    0.2523
   30.0000   33.0000    1.6650
   ......

Observation

freq percentage value for 26 [red colored] is 0.3532 that is slightly lower than for 25 [pink colored] which has 0.8073. Similarly, for 13 [red colored] it is 1.7659, that is again slightly lower than for 15 [looks like pink colored], which has 2.3209.

To confirm, you can create another column to the "tabulated" one and mark different weights for each number from 1 to 100 based on their colors. Then, see if such a pattern continues across the entire board. Good luck and hope this would make sense!


Given a set of random strings, write a function that returns a set that groups all the anagrams together in objective-c

This would be a better way to do the final storage into the dictionary. Attempt to retrieve an existing list. If it does not exist, create it and add it to the dictionary. You can then unconditionally add the current word to the array.

NSString *sortedString = [wordArray componentsJoinedByString:@""];

// Attempt to retrieve existing list
NSMutableArray * anagramStrings = [anagramsDictionary objectForKey:sortedString];
if( !anagramStrings ){
    // If it does not exist, create it and put it into the dictionary
    anagramStrings = [NSMutableArray array];
    [anagramDictionary setObject:anagramStrings forKey:sortedString];
}

// Add to the list
[anagramStrings addObject:word];

[wordArray removeAllObjects];

This avoids doing a copy every time, which in your original code is unnecessary in all cases but one.

Also worth noting is the last line here:

if(anagramStrings){
    //if anagram(s) of the word is already in the dictionary then add this word to the array
    //and store it back into the dictionary
    [anagramStrings addObject:word];
    [anagramsDictionary setObject:anagramStrings forKey:sortedString];
}

There is no need to put the mutable array back into the dictionary after getting a pointer to it, as you're doing. The array is not removed from the dictionary; your anagramStrings points to that exact same array.


Design Fix

The correct solution to this is to make your cache responsible for retrieving the entity on cache-miss.

Consider for a moment the goals of a cache:

Keep expensive to calculate / retrieve information in a manner suitable to quick access
Abstract away cache handling (invalidation, cache-misses, ...) from consumers
Give certain guarantees for the consistency of cached information

As it stands the way this code is setting up and using the cache utterly fails on the second point. Luckily javax.caching.Cache does support loading entries into the cache on misses using a CacheLoader.

For this to happen you need to create a CacheLoader that is aware of the EntityManager used to access the entities:

[..] config = new MutableConfiguration<String, T>()
  .setTypes(String.class, type)
  .setReadThrough(true) // enables silent loading
  .setCacheLoaderFactory(new FactoryBuilder.SingletonFactory(
    new CacheLoader<String, T>() {
      @Override
      public T load(String key) {
          return entityManager.find(type, key);
      }
      @Override
      public Map<String, T> loadAll(Iterable<? extends String> keys) {
          return Stream.of(keys)
            .collect(Collectors.toMap(Function.identity(), this::load));
      }
   });

You should notice at this point that you're locking yourself into caching on a single primary key (namely String). This is something that might bite you in the backside down the road, but if you only use Strings as primary keys for entities that should be alright.

n.b. that I haven't even checked whether this code compiles.


Writing cleaner PHP code to add additional options

General inconsistency
Basically your code is borderline off topic. Although it could work, it is not a working code in the sense a programmer could take it; but rather a set of copy-pasted code blocks loosely (and wrongly) connected to each other.
The main problem is inconsistent code structure. You have $data['success'] set at the end of the script but... it goes nowhere.
So it basically should be
if ($errors) {
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    $mail = new PHPMailer;
    // the rest or phpmailer code goes on
    if(!$mail->send())
    {
        $data['success'] = false;
        $data['errors']  =  ["Mailer Error: " . $mail->ErrorInfo];
    }
    else
    {
        $data['success'] = true;
        $data['message'] = 'Success!';
    }
}
// return all our data to an AJAX call
echo json_encode($data);

Note that another error has been fixed. $data['errors'] should be an array, but in case of phpmailer error you were sending a string.
Configuration options
error_log( "Errors" );

Always use the absolute filesystem path to a log file or you'll end up with log files in the every directory.
Also, it's better to configure such settings on the server level, for some errors may occur before the file gets parsed completely. Or at least put these settings into a configuration file and include it in all your php scripts.
Autoload
Instead of requiring files manually, consider using PSR-4 autoload and Composer. It's really easy, you just have to install Composer, then run two commands in console
php composer.phar require google/recaptcha
php composer.phar require phpmailer/phpmailer

and then add just a single require line into your code
require __DIR__ . '/vendor/autoload.php';

and all classes will be loaded automatically!
Validation and sanitization
You may want to verify whether the email address is valid.
if (empty($_POST['emailAddress'])) {
    $errors['emailAddress'] = 'Email Address is required.';
} else {
    $emailAddress = filter_var($errors['emailAddress'], FILTER_SANITIZE_EMAIL);
    if (!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
        $errors['emailAddress'] = 'Email Address is invalid.';
    }
}

and also sanitize the email body,
$emailBody = htmlspecialchars($_POST['comment']);


Making a function which takes char* exception-proof

First a question: why do you care that an extra string is being created?  Is this function used a lot.  If not, then I see no need to change.

But beyond that, although I don't know about C++ cleverness, is your replacement function so much more efficient?  You are calling pow repeatedly and using floating point to do an integer job.  Here is an alternative that would be cheaper.  It returns 0 on success, 1 on failure (bad string) and the number desired is output in result.   Notice that string is const.

int my_atoi(const char* string, int start, int length, long *result)
{
    char copy[length+1];
    memcpy(copy, string + start, length);
    copy[length] = '\0';
    char *end;
    *result = strtol(copy, &end, 0);
    return (*end != '\0');
}

You might also omit the start parameter and call with

my_atoi(string+start, length, &res);


Javascript to compute max width and height for a nested HTML element

What is

parseInt((control.outerHeight(true)) - control.height());

supposed to achieve?

The result of - is always going to be a number, so what this does is convert the number to a string and back to a number.  This can only lose precision and waste time.

Similarly, the use of parseInt on the first argument is also unnecessary

parseInt(control.parent().height()) - heightBuffer(control)

since

"4" - 1 === 3

In fact, the automatic conversion that - does is better than that done by parseInt since parseInt falls back to octal on some interpreters but not others.

"10"             - 1 === 9
parseInt("10")   - 1 === 9
"0x10"           - 1 === 15
parseInt("0x10") - 1 === 15
"010"            - 1        // throws reliably
parseInt("010")  - 1 === 7  // on some and 9 on others

so I'd get rid of all the uses of parseInt as an operand to -.

You seem to be setting min-height but the method is called MaxHeight.  That confuses me.

When you change the CSS

control.css('min-height', h)

you might want to specify units as in

control.css('min-height', h + "px")

I'm not sure how you're handling the widths of margins and borders on the controls.  Is that important to you?


Loading content from external HTML files

When you say

  I created 25 different functions for the 25 videos that I'm loading separately when its corresponding link is clicked.

Does that mean you have multiple function videoLoad#() { ?

I think this will help:

$("div#movie_list a").click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    id = e.target.id;
    loadVideo(id);
});

function loadVideo(id) {
    file = id + ".html";
    $.get(file, function (data) {
        $('#kz-video').html(data);
    });
});


Your code looks good, but there are four things I would improve:

Style

Overall your code follows the PEP 8 Style Guide, but:

Names should use snake_case, so index_of instead of indexOf, etc
Comments after code should leave 2 white spaces after the code:

self.size = 0 # length user thinks array is  <- wrong
self.size = 0  # length user thinks array is <- correct

I don't know if this is just my preference, but I think it's better to group the public methods like is_empty, index_of etc and group the overloads like __getitem__, __setitem__

Clear

At least for me, what I would expect of a method called clear is that it removes all objects, leaving the array empty. So in my opinion your clear method should just set self.size = 0. You don't need to set the elements to null because they don't matter anymore.

Is empty?

In Python, you can check if a list contains any elements by doing:

if my_list:

I think users would expect the same behaviour for your class, which you can implement with the __bool__ (Python 3.x) or __nonzero__ (Python 2.x) methods. Just return not is_empty()

Iterator

The biggest flaw I see in the code is your implementation of iteration. You are keeping the index in the array object; this means that the user cannot do:

for x in my_array:
    for y in my_array:

Because the _index is shared in both loops.

You can solve this by implementing the iterator in a different class. I would declare it as a nested class, starting with an underscore to indicate the user that it should be considered private:

class DynamicArray:
    class _Iterator:
        def __init__(self, dynamic_array):
             # ....
        # Implement '_index' and '__next__' in this class

    def __iter__(self):
        # Return a different object every time you are requested an iterator
        return _Iterator(self)


Triggering the execution of a job at the end of a timed campaign

Your problem is an integration and management problem, rather than a programming problem (though there are some issues there too).
Approach 3
Approach-3 is a problem, and I would not use it for your task. Repetitive tasks require a well designed and reliable infrastructure to handle them. The quirks of time are such that things like daylight-saving, system clock resets, and other issues will play havoc with things. For example, What will your task do when you 'spring forward' in daylight savings... will it fail because the next scheduled time never happens? In fall, will it go idle for over an hour when the same hour is repeated?
Cron (and on many Linux distributions, Anacron) has very well documented practices and behaviours for these types of issues, and the predictable, and reasonable use case makes a lot of sense. Use Cron.
Additionally, if there is an issue sending a mail, or anything requiring rescue in Approach 3, you will fail to reschedule, and your program will break.
Approach 2
This is actually quite similar to Approach 1, but it just shifts more logic in to the process method, and it mixes up the responsibilities in that method. SOLID principles suggest having just a single responsibility in each method, so I don't like this approach. Additionally, you can only process one campaign at a time using this approach.
Too much happening in one place, and possible opportunities for parallelism are removed.
Approach 1
I prefer this approach for the relative simplicity of the single-campaign method, and the way the campaigns are processed.
Improvements
Having said that, there are problems still. The biggest is that your program is not defensive enough. Even though you expect only one instance of the program to be running at any one time, you should still program defensively and assume there could be more.
Cron (anacron) will ensure that it does not start a second instance of the program if the previous instance has not yet completed, so cron will not cause  a problem, but you may have some mix up happening in your testing, or you may run it yourself when cron has it running already, leading to problems from there.
I am not very familiar with RoR, but the following looks like it could lead to conflicts and race conditions with other running processes:

  # Do not update campaign if deleted or deactivated
  if campaign.present? && !%w(deleted deactivated).include?(campaign.status)
    campaign.status = 'finished'

    UserMailer.post_campaign_notification(campaign.id, campaign.user.id).deliver

    campaign.save
  end

Posting the campaign e-mail could be a slow task and (even if it was fast) there is the possibility that another instance of the program may be processing the same campaign at the same time. If you are using a database for your campaigns you should consider a different approach. I recommend:

a transactional approach which checks to see whether the campaign is state='finished', updates it to finished, and returns the previous state, and then commits the transaction.
this guarantees the state will be marked as finished in a single 'atomic' operation
it saves the Campaign state before sending the mail.
there is only a short period of time while the campaign is 'locked'
if the previous state was not 'finished' then send the mail.

At worst case, now, the only risk is that the mail fails to send. That should be logged in a reliable way that allows you to (manually?) identify, resolve, and resend the mails.
Note that a failed mail will fail whether you mark the Campaign complete or not, and repeatedly resending the mail will not make it suddenly work. There is no reason to save the campaign after the mail-send.