Searching for a better implementation to EnumBase

So, extending my comment...

Enums are designed to represent a fixed number of states. This is their purpose. If that is what you need then nothing prevents you from using standart enum. If you want to specify items source as a collection of enum values - use IEnumerable<MyStandartEnum>, for example:

//collection of all enum values
var allVlues = Enum.GetValues(typeof(MyStandartEnum)).Cast<MyStandartEnum>();
//collection of elements which satisfy SomeCondition() (extension method)
var someValues = Enum.GetValues(typeof(MyStandartEnum)).Cast<MyStandartEnum>().Where(x => x.SomeCondition());

If you need some complicated logic added to enum, if you need to extend it, etc., that only means that enum is not the right abstraction in your case. Instead of trying to emulate enum's behaviour in some wierd abstract class, you should build a proper class to represent your data and then use generic collections (or implement your own).


Your have the right ideas for implementing make-sum and make-product.  You may improve upon them in the following ways, in my opinion.

Within the two functions, you employ an inner function iter to partition numeric and non-numeric terms.  Traditionally, one uses the name iter to represent an iterative function; your definition, however, is most certainly recursive.  To make it truly iterative, one may use two accumulators--one for the sum of all numeric terms and the other for the rest of the terms.  Then one may return the cons of the two accumulators when the iteration terminates.

One may allow make-sum (and similarly make-product) to handle other sum-type objects in its terms list as well--simply test with sum?, then append its terms.

Finally, there are several cases that must be handled when iteration terminates: rest may be empty or it may contain one or more items; sum-numbers may be zero or non-zero.

Here's an implementation (naming scheme is slightly different from yours--in the iter function, terms is the list of remaining terms to be iterated upon, sum-numbers is the sum of all numeric terms seen so far, rest is a list of all non-numeric terms seen so far):

(define (make-sum . terms)
  (define (iter terms sum-numbers rest)
    (cond
      ((null? terms) (cons sum-numbers rest))
      ((=number? (car terms) 0) (iter (cdr terms) sum-numbers rest))
      ((number? (car terms)) (iter (cdr terms) (+ sum-numbers (car terms)) rest))
      ((sum? (car terms)) (iter (append (cdar terms) (cdr terms)) sum-numbers rest))
      (else (iter (cdr terms) sum-numbers (cons (car terms) rest)))))
  (let*
      ((result (iter terms 0 null))
       (sum-numbers (car result))
       (rest (cdr result)))
    (if (null? rest)
        sum-numbers
        (if (zero? sum-numbers)
            (if (null? (cdr rest))
                (car rest)
                (cons '+ rest))
            (cons '+ (cons sum-numbers rest))))))

(define (make-product . terms)
  (define (iter terms sum-numbers rest)
    (cond
      ((null? terms) (cons sum-numbers rest))
      ((=number? (car terms) 0) (cons 0 null))
      ((=number? (car terms) 1) (iter (cdr terms) sum-numbers rest))
      ((number? (car terms)) (iter (cdr terms) (* sum-numbers (car terms)) rest))
      ((product? (car terms)) (iter (append (cdar terms) (cdr terms)) sum-numbers rest))
      (else (iter (cdr terms) sum-numbers (cons (car terms) rest)))))
  (let*
      ((result (iter terms 1 null))
       (sum-numbers (car result))
       (rest (cdr result)))
    (if (null? rest)
        sum-numbers
        (if (zero? sum-numbers)
            (if (null? (cdr rest))
                (car rest)
                (cons '* rest))
            (cons '* (cons sum-numbers rest))))))

One may also simplify the definitions of augend and multiplicand by using make-sum and make-product respectively:

(define (augend s) (apply make-sum (cddr s)))

(define (multiplicand p) (apply make-product (cddr p)))

Note the similarities between make-sum and make-product.  It may be possible to factor out some code.  One may also use library functions such as partition (if available) to simplify the code.


Size

The biggest thing that sticks out is that your string does not have a length member. So when testing for empty or size you have to scan the string to find the result (you don't actually need to do it for empty but you do).

Would it not be easier to keep track of the string length in a member and just return it?

Resetting Memory

    memset(this->pcString, 0, this->iCapacity);
    memcpy(this->pcString, strInstance.data(), this->iCapacity - 1);

Setting memory to zero then copying over it with new values seems completely redundant. Just copy the data into the memory you want.

Because you don't have an explicit length setting memory to zero in other places is required (but do you need to set the whole array to zero? Why not jus the first element. In C-Strings the '\0' character is the string terminator. So if the first character is '\0' then the string is empty and has length zero. At this point what the other characters hold is irrelevant.

Also you are using C functions to do your copying. Use the much better C++ functions. These will use the fastest technique to copy the current type.

std::copy(strInstance.pcString, strInstance.pcString +  strInstance->iCapacity,
          pcString);

Default Parameters

Your first two constructors are identical. You should DRY up your code and use a single constructor. The difference is one has zero parameters and the other takes none and defaults the size:

string::string(void)   // By the this is correct. BUT not often used in C++
                       // The empty list has exactly the same meaning.
{
    pcString = new char[INITIAL_SIZE];
    memset(pcString, 0, INITIAL_SIZE);
    iCapacity = INITIAL_SIZE;
}

string::string(int iSize)
{
    pcString = new char[iSize];
    memset(pcString, 0, iSize);
    iCapacity = iSize;
}

By using a default parameter you can write this in one function:

class string
{
     public:
        string(int iSize = INITIAL_SIZE); // Now you only need to write it once
                                          // If used with zero parameters the
                                          // the compiler will call this
                                          // constructor and use the default value.
}

Using this

This is a sign of bad code design.

You only need to use this if you have shadowed variables. If you have shadowed variables you are writing code that is hard to read and understand because you are using the same name to represent different objects.

So stop using this and turn your compiler warnings up so that it warns you about shadowed variables and then use meaningful unique variable names so that it is obvious what you are doing.

Uninitialized Objects

If your input is not what you expect you don't initialize the object.

string::string(const char *pcValue)
{
    if(pcValue)
    {
         // INIT CODE
    }
}
string::string(const string &strInstance)
{
    if(strInstance.empty() == false)
    {
         // INIT CODE
    }
}

Notice in both these cases there is no else. So if you don't fit the condition you do no work. Note in C++ unless you explicitly set the value it has an indeterminate value. Attempting to read an indeterminate value is Undefined Behavior. In your constructors you should explicitly try and set all members (Note: Members that have constructors will be initialized but POD objects don't have constructors int/float/pointers etc...).

Initializer List

You should prefer to use the initializer list in your constructor to set up members. In your code it does not matter because all your members are POD but it is a good habit to get into for all members because when they are not POD (or if somebody changes the type of you member to non POD) this will cause a lot of extra code. This is because the members are initialized by their constructor (if they have one) before the constructor is entered from the initializer list. If you don't explicitly put them in the list the compiler will add them using their default constructor. Subsequent assignment in the constructor code will use the assignment operator for that object.

string::string(int iSize)
    : pcString(new char[iSize])    // Initializer list
    , iCapacity(iSize)
{
    pcString[0] = '\0'; // Only setting the first char
}

Boolean Tests

If a value or expression is boolean. You don't need to test it against true/false. That's its value already.

    if(strInstance.empty() == false)

    // I would just write

    if (!strInstance.empty())   // The whole point in giving it a reasonable
                                // name like empty() is to make the code more
                                // readable in situations like this.

Destructor

string::~string(void)
{
    delete this->pcString;
}

You used the wrong delete. Because you used new [] you must use delete [] to release the memory.

string::~string(void)
{
    delete [] pcString;
}

Assignment operator

string& string::operator=(const string &strInstance)
{
    if(strInstance.empty() == false)
    {

So if the other string is empty() you are not going to do anything. I think that is a bug. If the other string is empty then this string should also become empty.

        delete this->pcString;  // missing [] see notes on destructor
        this->pcString = new char[this->iCapacity];

You correctly delete the pcString before re-use. BUT what happens if the call to new char[] fails? This can potentially throw an exception. If sombody catches that exception further down the road then you now have an object with pcString pointing at deallocated memory. Not a good idea.

When reallocating. You first allocate the new memory (make sure it works). if it does then you can delete your old memory. It should look like this:

string& string::operator=(const string &strInstance)
{
     // Step 1:
     // Do dangerous work into temporaries.
     // If this fails and throws an exception your object is
     // still in a good state.
     char* newPcString = new char[strInstance.iCapacity];
     std::copy(strInstance.pCString, strInstance.pCString + strInstance.iCapacity,
               newPcString);

     // Step 2:
     // Swap the temporaries and your internal state in an exception safe way
     std::swap(newPcString, pcString);
     this->iCapacity  = strInstance.iCapacity;

     // Step 3:
     // Now release the old memory. In this case it is not dangerious.
     // But if the objects in the array had destructors it could be dangerious.
     // This is why we do it after the state of the object has been completely
     // changed.
     delete [] newPcString; // Note the swap in Step 2.

     return *this;
}

OK. So that is the long way around of doing it. But there is a technique called the copy and swap idiom. That automates Step 1 and Step 3. So all you have to do is write Step 2.

string& string::operator=(string strInstance)
{
     std::swap(strInstance.pcString, pcString);
     this->iCapacity  = strInstance.iCapacity;
     return *this;
}

Where did Step 1 and 3 go? If you look at the parameter strInstance. You will notice that we passed it by value. This causes a copy of the original to be created (this is step1) and when the function exits the destructor is called and the parameter is destroyed thus invoking Step 3.

Operator +

Operator + is not doing what I expect it to.

string& string::operator+(const string &strInstance)

I would expect operator + to return a completely new object with the strings concatenated. What you have implemented is what I would expect the function operator+= to implement (because you are returning a string reference). If you want to return a new object then you should return by value (drop the &). Yes it looks inefficient to do so but the compiler will see this and perform RVO optimization to elide the copy).

If you look at this in some code.

string    bred   = "bred";  // calls the correct constructor.
string    butter = "butter"

toast(bred + butter);

std::cout << bred.data() << "\n";  // This prints "bredbutter"
                                   // This is not what I expect because
                                   // I have made no assignment to bred.

toast(bred += butter);             // Here I see an assignment so I am
                                   // OK with bred changing.

So I would change the operator to +=. Note writing operator+ in terms of operator+= is trivial.

Having a look at your code for operator+. It looks like you were actually trying to do it correctly. Couple of gotchas.

{
    int iNewSize = strInstance.size() + this->size() + 1;
    char *pcTemp = new char[iNewSize];
    // This is leaked.
    // Also efficient as you are going to call new inside the constructor.

    _snprintf(pcTemp, iNewSize, "%s%s", this->data(), strInstance.data());
    string *pStrResult = new string(pcTemp);
    // You are dynmaiclly allocating a new object here.
    // But you return by refernece.
    // So there is no where to delete this object.

    return *pStrResult;
}

// This is how I would do it.

string string::operator+(string const& strInstance)
{
    // Create a new string object with enough space.
    string    result(size() + strInstance.size() + 1);

    std::copy(pcString, pcString + size(), result.pcString);
    std::copy(strInstance.pcString, strInstance.pcString + strInstance.size()
              result.pcString + size());
    result.pcString[size() + strInstance.size()] = '\0';

    // Don't worry about returning by value.
    // NRVO will kick in and elide the copy and build this object in place
    // at the destination.
    return result;

}


Check if specific key exists in 2-dimensional array

If I have understood your question correctly you are seeking a function which can check if values of a 2-dimensional array equals FALSE. An example of such array structure could be:

$array = [
    0 => [0, 0, 0, 0, 0],
    1 => [0, 0, 0, 0, 0],
    2 => [0, 0, 0, 0, 0],
    3 => [0, 0, 0, 0, 0],
    4 => [0, 0, 0, 0, 0],
];

I have attempted to write an implementation from the context you have given. I have reduced your code down to a single for loop and opened the possibility to having any default value that evaluates to FALSE, such as false, null, 0 or an empty array. This is done through the native array_filter() function. I have also included some error checking. An example usage could be.

/*
 * Using array structure from previous example.
 *
 * Check if array elements starting at index 1 and 2
 * elements forward only contains values that equals
 * to FALSE.
 */
$valid = collisions($array, 1, 2);

Along with inline comments the code of the function should be pretty self explanatory.

/**
 * Check if the provided array has any values that does not
 * evaluate to FALSE in the given array range.
 *
 * @param array $array A two dimensional array.
 * @param int   $start An integer specifying an array index to start the check.
 * @param int   $size  An integer specifying how many array elements to check values for.
 *
 * @return bool Returns FALSE if there are collisions, TRUE otherwise.
 * @throws \OutOfRangeException
 * @throws \DomainException
 */
function collisions(array $array, $start, $size)
{
    /*
     * We ensure the outer array has only
     * numeric array keys.
     */
    $array = array_values($array);

    /*
     * Check if starting index is out of range of the provided array.
     */
    if(!array_key_exists($start, $array)) {
        throw new OutOfRangeException('The specified starting index is out of range of the provided array.');
    }

    /*
     * Compute the upper boundary
     */
    $boundary = (int)$start + (int)$size;

    /*
     * Check if the amount of elements to check AFTER the specified starting
     * index is out of range of the provided array.
     */
    if(!array_key_exists($boundary, $array)) {
        throw new OutOfRangeException('The specified amount of elements to check exhausts the provided array.');
    }

    for($i = (int)$start; $i <= $boundary; $i++) {

        /*
         * Check if the current array value is an array.
         */
        if(!is_array($array[$i])) {
            throw new DomainException("Invalid type of array value at index {$i}. Expected an array, type of " . gettype($array[$i]) . ' given.');
        }

        /*
         * If the native function array_filter() doesn't have a second
         * argument, it will filter out any values corresponding to FALSE. I assume
         * an accepted value is 0, which evaluates to FALSE.
         *
         * Therefore of the resulting array is NOT empty there are
         * values which does not equal to 0 (zero).
         */
        if(array_filter($array[$i])) {
            return false;
        }

    }

    return true;
}

The error checking and the first line $array = array_values($array); can be removed if you are sure the provided array always has the correct structure and has numerical indexes. But I would strongly recommend to not doing so, as good error checking can help you when bugs occur.

Performance wise this shouldn't be too bad. The many if statements when checking for errors are somewhat slow, but should be negligible. As far as I know the for loop doesn't operate on a copy of the provided array as foreach otherwise would. This is only a concern if you are having huge arrays. If this is the case I would strongly recommend using an iterator.

Regarding performance. Premature optimization is almost always not the answer. I would suggest you write SOLID code. Then when you are done you can profile your application and look for the performance heavy blocks. Remember that if your application relies on a database the biggest performance gains are properly in writing highly optimized SQL queries. Of course there are exceptions. If this function is used extensively throughout your code it's always good to think about optimization.

Happy coding!


ArrayBlockingQueue in which queue head is removed if the queue is full while adding an element

This has been discussed in stackoverflow

  Having a thread-safe backend collection does not necessarily make a
  correct program. When only your add method is synchronized, the
  take() method may run concurrently to it, so it is possible that
  after your if(blockingQueue.remainingCapacity() <= 0) test within
  add, a concurrently running take() removes an element, so the
  poll() within add may remove an element unnecessarily. There is a
  perceivable difference to the situation where add() would complete
  before the take(), as the consuming thread would receive a different
  item. It other words, the effect would be as if add would sometimes
  not remove the oldest item, but the second oldest one.

  On the other hand, if you use synchronized for all of your methods
  consistently, there is no need to have a thread-safe backend
  collection:

import java.util.ArrayDeque;

public class CircularNonBlockingQueue<E> {
    private final ArrayDeque<E> blockingQueue;
    private final int maxSize;

    public CircularNonBlockingQueue(int size) {
        if(size<1) throw new IllegalArgumentException("size == "+size);
        blockingQueue = new ArrayDeque<>(size);
        maxSize = size;
    }

    public synchronized int size() {
        return blockingQueue.size();
    }

    public synchronized void add(E element) {
        if(blockingQueue.size() == maxSize) {
            blockingQueue.poll();
        }
        blockingQueue.add(element);
        notify();
    }

    public synchronized E take() throws InterruptedException {
        while(blockingQueue.isEmpty()) wait();
        return blockingQueue.remove();
    }
}

  However, if you can live with weaker guarantees regarding the oldest
  element, you can use a BlockingQueue and don’t need any
  synchronized:

public class CircularNonBlockingQueue<E> {
    private final ArrayBlockingQueue<E> blockingQueue;

    public CircularNonBlockingQueue(int size) {
        blockingQueue = new ArrayBlockingQueue<>(size);
    }

    public int size() {
        return blockingQueue.size();
    }

    public void add(E element) {
        while(!blockingQueue.offer(element)) {
            blockingQueue.poll();
        }
    }

    public E take() throws InterruptedException {
        return blockingQueue.take();
    }
}

  It must be noted that neither of these solutions provides “fairness”.
  So if the number of producer and consumer threads is large compared to
  the queue’s capacity, there is the risk that producers repeatedly
  remove items without reactivating threads blocked in take(). So you
  should always ensure to have a sufficiently large capacity.


HasPostgres instance for IO with Snap framework

Yes, this looks good to me.  I've done exactly the same thing to facilitate debugging in my projects.  However, I would recommend that you put the IO instance in some special module where all your debugging code lives.  You really do not want instances like this making their way into any other code because it is akin to making a global statement that IO always has a test database available at localhost on port 5432.


There isn't much that can be reviewed. If you use Scala 2.10 then you should use an implicit class instead of an implicit conversion. Even better: use an implicit value class:

implicit class PipelineContainer[F](val value: F) extends AnyVal {
  def |>[G] (f: F => G) = f(value)
}

Furthermore, in Scala, type parameter are enumerated starting with an A, but this is more a style issue.


Write a program to find the longest word made of other words

The first thing that strikes me is that you've put everything within the Program class, which forces your methods to be static, and any program where everything is static is a program I want to rewrite :)

Let's start with FindLongestWords(string[]):

if (listOfWords == null) throw new ArgumentException("listOfWords");

This guard clause is throwing the wrong exception, it should be an ArgumentNullException. Now the goal of a guard clause is to fail fast. Interestingly if you leave it out, the next line would throw an ArgumentNullException all by itself, merely by passing it to the OrderByDescending extension method:

var sortedWords = listOfWords.OrderByDescending(word => word.Length).ToList();

I see you're using var - I like that. So sortedWords is a List<string>. I think the method could happily take any IEnumerable<string> instead of an array.

Now the next thing I see is a lie - dict would be an almost-acceptable name for any IDictionary, but it's a HashSet<T>...

var dict = new HashSet<String>(sortedWords);

And here we are. You're using System.Linq, so this loop could very well be rewritten with a much shorter Linq-expression:

foreach (var word in sortedWords)
{
    if (isMadeOfWords(word, dict))
    {
        return word;
    }
}
return null;

Turns into this one-liner (notice dict is gone!):

return sortedWords.FirstOrDefault(word => isMadeOfWords(word, sortedWords));

isMadeOfWords should be named IsMadeOfWords, and can be happy with some ICollection:

private static bool IsMadeOfWords(string word, ICollection<string> dict)
{
    if (String.IsNullOrEmpty(word)) return false;
    if (word.Length == 1)
    {
        return dict.Contains(word);
    }
    foreach (var pair in generatePairs(word).Where(pair => dict.Contains(pair.Item1)))
    {
        return dict.Contains(pair.Item2) || IsMadeOfWords(pair.Item2, dict);
    }
    return false;
}

I find that's more readable than the more concise form that ReSharper suggests:

    if (String.IsNullOrEmpty(word)) return false;
    return word.Length == 1
        ? dict.Contains(word)
        : generatePairs(word).Where(pair => dict.Contains(pair.Item1))
                             .Select(pair => dict.Contains(pair.Item2) || IsMadeOfWords(pair.Item2, dict))
                             .FirstOrDefault();

And then generatePairs should be renamed to GeneratePairs and can return IEnumerable<Tuple<string, string>> instead of List<Tuple<string, string>>. The only thing that itches here is the absence of var in for(int i = 1... - if you're going to use var, might as well go all the way!

I'd put that logic in its own class, and then... looks good!


Bugs

The outline of the function is

@Override
public boolean decideIfShouldRoll(int turnNumber, int rollNumber,
        int poolSize, int myScore, int opponentsScore) {
    if (myScore < 30 && opponentsScore < 30) {
        …
    }
    if (opponentsScore > myScore) {
        …
    }
    if (myScore > opponentsScore) {
        …
    }
    return true;
}

The return true at the end is problematic.  You're saying that, except in the opening moves, anytime the score is tied, you want to roll forever, essentially forfeiting your turn.

If we have 95 points and a pool of 5, we should stop rolling.  Your code tries to amass a pool of 15 points or 10 points.

Redundancy

The opponentScore > 20 test should always be true, since the opponent is in the lead, and the leader has at least 30 points.

@Override
public boolean decideIfShouldRoll(int turnNumber, int rollNumber,
        int poolSize, int myScore, int opponentsScore) {
    if (myScore < 30 && opponentsScore < 30) {
        …
    }
    if (opponentsScore > myScore) {
        …
        if (opponentsScore > 20) {
            …
        }
        return false;
    }
    if (myScore > opponentsScore) {
        …
    }
    return true;
}

Math.abs() is superfluous here, since we have already established that we are in the lead:

if (myScore > opponentsScore) {
    if ((100 - myScore) <= 20 && (myScore - opponentsScore) <= 10) {
        …
    }
    …
    if ((myScore - opponentsScore) > 10) {
        …
    }
    if ((100 - myScore) <= 20
            && Math.abs(myScore - opponentsScore) <= 10) {
        …
    }
    return true;

In fact, if you eliminate the Math.abs(), then you are redundantly restating the (100 - myScore) <= 20 && (myScore - opponentsScore) <= 10 case exactly.

Verbosity

Anytime you have if (condition) return true; else return false; you should just write return condition;.

I'm not a fan of needless arithmetic like if (100 - opponentsScore <= 20).  It would be shorter to write if (opponentScore >= 80), and just as clear.

Interface

The function name could be simplified to shouldRoll.

Assuming a fair die, there is no logical strategy in which the turnNumber or the rollNumber could be a factor in the decision.  It doesn't matter how you arrived at the current score and pool, because past performance is no indicator of future expectations.  Anything else would be a gambler's fallacy.  Therefore, I suggest eliminating turnNumber and rollNumber from the method signature.

I suggest renaming opponentsScore to theirScore, both to save a few characters and to mirror myScore.

Rewrite

There is too much code altogether!  You are really just trying to express a simple idea: in the face of an imminent loss, go for a pool of 30 points; if you have a comfortable lead, aim for just 15; otherwise, try to gather 20.

@Override
public boolean shouldRoll(int poolSize, int myScore, int theirScore) {
    if (myScore + poolSize >= 100) {
        return false;
    }
    int myLead = myScore - theirScore;
    int wantPool = (myScore < 80 && theirScore >= 80) ? 30              // Imminent loss, be aggressive.
                 : (myScore >= 80 && (0 < myLead && myLead <= 10)) ? 15 // Comfortable lead
                 : 20;                                                  // General case
    return poolSize < wantPool;
}


More efficient way than creating scanner of .txt file twice

I'd be very skeptical about making any changes to the current code you have when it comes to creating the scanners. However, I do want to indicate that reopening a file while it is still open is probably not a good idea. So I'd use a try-with-resources when you create the Scanner instances. I don't think reopening a file is so resource intensive that it needs to be avoided.

However, file access is commonly performed using a file pointer, and that file pointer can be reset. The question is then how to make a FileInputStream aware of that. This can be done by asking for the file channel (introduced with Java NIO2) and then setting the position on that.

So if we read the documentation of FileInputStream#getChannel() we get:

  Reading bytes from this stream will increment the channel's position. Changing the channel's position, either explicitly or by reading, will change this stream's file position.

Ah! Right what we are after, so here is code that leaves the file open:

try (FileInputStream fis = new FileInputStream(inFile)) {
    Scanner scanner1 = new Scanner(fis);
    System.out.println(scanner1.nextLine());

    fis.getChannel().position(0L);

    Scanner scanner2 = new Scanner(fis);
    // prints the same line!
    System.out.println(scanner2.nextLine());

    // the underlying file stream will be closed anyway, but yeah...
    scanner2.close();
    scanner1.close();
}

Reusing a scanner itself doesn't work. The reason is that Scanner instances cache data, which means that that data is not present anymore in any underlying stream. This is why no such functionality is supplied. Scanner is not a very heavy-weight component to instantiate, so I guess that's all right.

The above code is pretty ugly because how Java handles close(). Any call to Scanner.close() - implicit or explicit - will also close the underlying FileInputStream. That's of course not very useful in this scenario.

An ugly hack is to create a FilterInputStream-based decorator that simply forwards everything and then simply doesn't call close on the underlying stream. That way you can close the scanners without closing the underlying FileInputStream. But yeah, just as yucky as above code.

The fact that it is possible to re-read the file without re-opening it is not sufficient reason to use tricks like above. If you close the file then the file handle is released and when reopening the file is probably still cached.

I don't know enough about your application to know if rewriting your code to use Java NIO directly makes sense. Scanner was added to Java to make it easy to parse simple input, it was not meant to parse complex files, as the first line of documentation shows:

  A simple text scanner which can parse primitive types and strings using regular expressions.

Your code looks OK-ish. I'm very worried about the number and use of fields though. Generally a lot of fields is a red flag when it comes to class design. The fact that all the processing is performed in the constructor is not a good sign either. The separate part of encoding should take place in a separate method, which would make above solution even harder to apply.


Async telnet connection over StreamSocket

I see at least two points.

if you have a catch to catch a sytem Exception (wich is not good btw., it would be better to catch specific exceptions) and the only action is to throw that exception then its useless to have. If you need to rethrow an exception you should always omit the ex so just throw;, otherwise the StackTrace will be broken.
Having the public setter of the Status property is breaking encapsulation. Why should a user of the object be able to set this property? You should make it private.


Map a range of integers to a 64-bit integer

std::uint64_t get_index(std::uint64_t x)
{
    return 0u == x ? 0u : (x-1u)>> 6;
}

Will it faster, I doubt.

By the way, your code for x = 0 will yield -1, which is not same as your description. if you do not need x = 0 input, then you can remove the if statement as

std::uint64_t get_index(std::uint64_t x)
{
    return (x-1u)>> 6;  // for this, x must be not 0u.
}


Entering information about a business and finding matches

From a security perspective, you are vulnerable to malicious SQL injection, it only takes 1 malicious user..

Consider using prepared statements to plug this.

Furthermore, this hit my eye:

//find at least a partial match to the business name
if(name.length()>5){
    query += "businessName like '%" + name.substring(0, 4) + "%';";
}else{
    query += "businessName like '%" + name + "%';";
}

Since calling substring is a cheap operation, and it will return the value of name if the length is less than 5, I would go for simply

//find at least a partial match (first five characters) to the business name
query += "businessName like '%" + name.substring(0, 4) + "%';";

Also, 4 is a magical constant here, you could have named that constant and defined it.

//find at least a partial match to the business name
query += "businessName like '%" + name.substring(0, PARTIAL_MATCH_LENGTH) + "%';";

Also, in my mind, Java is for industrial strength with fullout names, so I would name some variables differently:

add -> addressParts
add1 -> addressPart

Finally, should getBusinesses know how to clean up name? Are you doing this in every single querying method that receives name ? There should be a class or method that knows how to clean name which should then be used by getBusinesses.


Filtering data from MYSQL database based on parameters passed with POST request

The entire long conditional is definitely worth to be decomposed and consolidated.

The main mechanics of optimization is based on 3 aspects:

determining a common logic/behavior that needs to be unified. In your case such a common fragment is:

$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
return $this->db->resultSet();

considering only populated fields
collecting bindings for particular fields

The final optimized function becomes as below:

public function filterContacts($user_id, $group, $email, $phone){

    $query = 'SELECT * FROM contacts WHERE user_id = :user_id';
    $bindings = [':user_id':=> $user_id];

    if ($group !== '0') {
        $query .= ' AND contact_group = :group';
        $bindings[':group'] = $group;
    }
    if ($email !== '') {
        $query .= ' AND email != ""';
    }
    if ($phone !== '') {
        $query .= ' AND phone_number != ""';
    }

    $this->db->query($query . ' ORDER BY name');
    foreach ($bindings as $k => $v) {
        $this->db->bind($k, $v);
    }

    return $this->db->resultSet();
}

In case if your DB clent $this->db allows to pass an array of bindings you can just  replace the loop with $this->db->bind($bindings); (check your DB client interface)


HTML - single page layout - absolute positioning

Have a look at this, maybe this helps a little. I made only little changes. first of all you have to know a child element is always positioned absolute or relative to his parent. so it is important to make child and parent elements, except you want a div as a placeholder to load the data in another way...

play arround with the code (like why is position:absolute 5px top and left only 5px from the orange...) it may helps to understand. also have a look at the class .app-page.active !

xxx

        yyy

zzz


Ok.

Lots of stuff going on here and I'm writing this as I work your example so bear with me...

In you code, polar contains six letters. And you don't care about letter repetition in your top examples so what you are calculating here are not permutations but variations. Secondly, you're example shows 22 ommitted lines so you have 24 from statements in your LINQ query... that's going to generate 6^24 variations (4738381338321616896)

That's a very large number. Even if you could paralelize this across 1000 servers, they would still need to be calculating 150million compressions ratios per second for this to complete in a year. (((6^24)/1000)/365)/86400) = ~150,253,000

As soon as you call foreach (var element in query) that query is going to execute and it's going to try and create a list of 4.7 Quintillion strings in memory. This is BAD. You're attempting a brute force calculation on an impossibly large problem set so you need to go back and rethink your approach to whatever it is you are trying to solve/accomplish

But again... lets just assume that you have enough power & bandwidth & compute resource (GPUs are shiny) And lets bring it back to more manageable numbers. lets says 6^10 =

Strings in General

Strings are immutable in .NET. Everytime you alter a string, you throw away the old one, and make a new one and the garbage collector has to come along and clean up after you. so this part here will be very expensive where you concat all those strings together, twice.

where GetCompressionRatio(sp1+...+vp15)>1.5
select sp1+...+vp15;

at the very least you would want to change this to

let concatval = sp1+...+vp15
where GetCompressionRation(concatVal) > 1.5
select concatVal

Big Numbers are Big.

Using LINQ like that to generate your variations is not optimal. As I suggested in the comments... use a library. The following code snippet.

var polar = new[] { "H", "Q", "N", "K", "D", "E" };

var sw = new Stopwatch();
sw.Start();
var results1 = from a1 in polar from a2 in polar
                from a3 in polar from a4 in polar
                from a5 in polar from a6 in polar
                from a7 in polar from a8 in polar
                from a9 in polar from a10 in polar
                select a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10;
var l1 = results1.Count();
sw.Stop();
Console.WriteLine("{0} variations in {1}ms", l1, sw.ElapsedMilliseconds);

sw = new Stopwatch();
sw.Start();
var results2 = new Variations<string>(polar, 10, GenerateOption.WithRepetition);
var l2 = results2.Count();
sw.Stop();
Console.WriteLine("{0} variations in {1}ms", l2, sw.ElapsedMilliseconds);

Console.ReadLine();

RESULTS

60466176 variations in 54161ms
60466176 variations in 4624ms

The Compression Method.

On my machine this is repeatedly capable of performing 100,000 compressions on a 10 character string in 2200-2300ms. With the following modifications, that comes down to 1800-1900ms. Small improvement that's possibly related to what else my machine was doing but still.

MemoryStream & GZipStream are IDisposable & should be wrapped in using() statements
removed unnecessary int assignments
removed unnecessary if(check) at top... you know this to be impossible based on your input set.

Code

static float GetCompressionRatio2(string input)
{
    using(var ms = new MemoryStream())
    using (var gzip2 = new GZipStream(ms, CompressionMode.Compress, true))
    {
        var raw = Encoding.UTF8.GetBytes(input);
        gzip2.Write(raw, 0, raw.Length);
        var percent = ((float)ms.ToArray().Length) / raw.Length;
        return percent;
    }
}


Is my MySQL library wrapper neat? How can I do better?

In C the naming conventions typically are lower_case_with_underscore for function names and types (although for types some people also use PascalCase). UPPERCASE is only really used for macro definitions.
In CONNECTION_INIT you have a bunch of hard-coded settings. These should come from a config file or via command line arguments.
In init_connection you write:

if((conn = MYSQL_CONNECT_DB(info)) == (MYSQL *) 0)

There is no reason to cast in order to compare it to NULL, simply == NULL works and is more idiomatic.
There is no reason to do the assignment and compare in one statement. Splitting it up makes the if statement less crammed:

conn = MYSQL_CONNECT_DB(info);
if (conn == NULL)
{
    ...

I assume printw is some kind of way to print debug/info/tracing messages. If so then this is not a good name for the function. Better would log_info or similar (depending on the exact purpose).
There is this magic refresh method called everywhere but it doesn't seem to follow any particular pattern. Seems suspicious to me.


Custom maximumBy and minimumBy in Haskell

Since maximumBy folds a list of elements into a single element, it seems like a perfect candidate to use foldr or foldr1. However, we would need a -> a -> a instead of a -> a -> Ordering.

Let's have a look at maximum first, which can be defined via max :: Ord a => a -> a -> a:

maximum :: (Foldable t, Ord a) => t a -> a
maximum = foldr1 max

That looks simple enough to adapt to our myMaximumBy:

myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
myMaximumBy f = foldr1 (maxBy f)

We now only need a maxBy that transforms an a -> a -> Ordering into a a -> a -> a:

maxBy :: (a -> a -> Ordering) -> a -> a -> a
maxBy comp x y = if x `comp` y == LT then y else x

Compared to your original solution, we now

replaced explicit recursion by foldr1
introduced a helper function that can get reused

Our new version is now easier to maintain and use.


Clipboard support in jQuery using revealing module pattern

Interesting question, your code is very readable.

However, if you only reveal an init function, then really there is not much sense in using a revealing pattern.

I would probably not self execute styleGuideHandler but pass it to the jQuery call:

$(document).ready(styleGuideHandler);

Other than that, just for giggles, I might also pass the few globals it uses:

$(document).ready(styleGuideHandler( document, Clipboard, hljs ));

Then when styleGuideHandler is executed, you run the code in init.


For something this simple, I think using the || is fine, however, if you need to use the list of acceptable integers more generally or avoid hard-coding the set in a single expression1, you can use something like this:

var newFileProgressIds = new[] { 10, 20, 21 };

var isNewFile = newFileProgressIds.Contains(progressID);

Or possibly use a HashSet<T>:

var newFileProgressIds = new HashSet<int> { 10, 20, 21 };

var isNewFile = newFileProgressIds.Contains(progressID);

1: Of course, in these examples, the values are still hard coded in one place, but precisely how you generate the list is unimportant.


You should probably review: com.google.common.collect.Iterators, especially com.google.common.collect.Iterators.concat() (com.google.guava:guava).  That implementation uses a member variable to hold and track the current iterator, in addition to the container of ordered iterators to inspect.

If you initialize current iterator with an empty iterator value (again, see guava), you'll eliminate some problem edge cases.

moveToNext() should not use recursion.  Instead, it ought to be a while loop that is determining the correct current iterator to use, and then returning the status of that iterator.  After all, you've already got a Stack, why do you need to use the stack also?

Take a good look at that constructor again - you happen to be getting an iterator from List.iterator(), but there's no reason at all to care if it came from List, or some other collection.

private final Stack<Iterator> iteratorStack = new Stack<Iterator>();
public FlattenIterator(List list) { this(list.iterator);  }
public FlattenIterator(Iterator iterator) { iteratorStack.push(iterator); }

The Dependency Injection pattern would perhaps suggest that you should have a constructor that accepts a Stack<Iterator>, and factory methods that create the Stack from the initial source iterator.  Not immediately clear - here, the stack is an implementation detail, so maybe it's not important.  On the other hand, if you can imagine sometimes swapping in a different implementation, that will run extra logging/instrumentation/debug code, then maybe you'll want to have that constructor.

Why not FlattenIterator<T> extends Iterator<T>?  Yes, the source is going to be mixed type, but you don't need to propagate that forward forever.

You might consider whether List is actually the right idea; here, you are using List<Object> as a poor man's Composite<T> (see Design Patterns, Gamma et al).  What you are really doing, after all, is visiting all leaves of a tree, so maybe the tree should be explicit, rather than implicit in the list.  If you have control over the caller, that's a design choice you might consider walking backwards.

It's not clear if remove() should be a no-op, as it is here, or throw an UnsupportedOperationException.  At a minumum, there should be a comment explaining why it doesn't throw.


Async login bug The try/catch around User.findOne does not accomplish anything because findOne is asynchronous. When findOne fails, it'll pass an error to the callback, but when the callback does throw err, nothing is there to catch the asynchronous error, so no response will be sent to the user. Another issue is that you aren't checking if user exists - if it doesn't, an error will be thrown when you try to access its password property. (You also aren't checking for whether .sign results in an error or not)
You could also consider using Promises instead of callbacks - findOne already returns a Promise, and Promises are often preferable because they're more easily chainable and their error handling can be cleaner.
Security looks reasonable, though:

Make sure connections are only permitted over HTTPS. HTTP requests are interceptable.
Even if the login bug above gets fixed, your current implementation is capable of informing anyone whether a given email is registered. For example, if I know your email address, I can try to login as you and examine the response to see whether the password was wrong or if no such email exists. This may not be desirable. If you wanted to fix it, have when the password doesn't match enter the same block as when the email isn't found, to make it indistinguishable to the user - you'd want to send a reply of Bad login in both cases.
On a similar note, when authentication fails, the appropriate status code to send is 401 (unauthorized), not 200.

Is how I'm checking usernames and password efficient?

Looks completely normal to me.

LOGGING: I log all connections to the server, and all login attempts. Is this a good practice

If one is logging, login attempts are one of the most important things to log. But console.log is not the right way to do it, at least not alone - say that some user was concerned about their logins, how would you examine their recent login attempts? Control-F-ing through the application stdout isn't a very manageable way of doing it. I'm not sure what the industry standard for this is, but you could consider saving to a logging database.
Email login You do:
const pw = req.body.password;
const submittedUser = req.body.email;

User.findOne({eMail: req.body.email}, async function (err, user) {
  if (err) throw err;
  console.log(user);
  const match = await bcrypt.compare(pw, user.password);
  console.log(match);
  if (match === true && user.eMail == submittedUser) {

You put the request email into a variable named submittedUser, which doesn't sound all that intuitive to me - better to use a variable name that indicates that it contains an email string, not a user, like email - you could destructure both at once with:
const { password, email } = req.body;

Then, later, use those variables instead of going through req.body again.
After the .findOne, there shouldn't be any need to do user.eMail == submittedUser - that check should be superflouous given the findOne call's constraint.
The body contains email, but the database contains eMail. The capitalization is different, which is an odd inconsistency which could cause typos and bugs. I'd recommend using a single property name - probably email, since that capitalization is much more common.
Rather than comparing the match against === true, you can just check if the match is truthy - or, another option, to reduce unnecessary indentation would be to throw if the match isn't truthy, and handle errors in a .catch.
Since .sign is callback-based, but you want to work with Promises, make it Promise-based with util.promisify.
Overall I'd hope to make the code look something like this:
const jwtSignPromisified = util.promisify(jwt2.sign).bind(jwt2);
app.post('/api/login', apiLimiter, async function (req, res) {
    const failLogin = () => {
        logLoginAttempt(email, false); // or something - 2nd param indicates success
        // could also pass IP address
        res.status(401).send('Bad login');
    };
    const { password, email } = req.body;
    try {
        const user = await User.findOne({ email });
        if (!user) return failLogin();
        const match = await bcrypt.compare(password, user.password);
        if (!match) return failLogin();
        logLoginAttempt(email, true);
        const token = await jwtSignPromisified({ user }, 'secrettokenhere', { expiresIn: '15min' });
        res.cookie(
            'access_token', 'Bearer ' + token, {
            //domain: 'localhost',
            path: '/',
            expires: new Date(Date.now() + 900000), // cookie will be removed after 15 mins
            httpOnly: true // in production also add secure: true
        })
            .json(user);
    } catch (error) {
        // This should not be entered under normal circumstances:
        logServerError(error);
        res.status(500).send('Unexpected server error');
    }
});

where logLoginAttempt and logServerError save to logging databases that can be examined.


Ruby code to parse and analyze social media stats in json format

Good work.

Here are some points where you can improve:

You can use input.sum { |x| x["like_count"] }.to_f instead of input.map { |x| x["like_count"] }.inject{ |sum, el| sum + el }
It is a good idea to do calculations with BigDecimal instead of Float.
435 is a magic number, you can put it into a constant with a good name.
The spaces before the parentheses aren't usual in the Ruby community style guide.
Check the dig method available for Hash instances.
You can use the new syntax for Hash instances when the keys are symbols: { hello: "world" }
Use double-quotes or single-quotes, you're mixing both.


According to this, subclassing datetime.datetime seems the way to go.

There is no use for the str_2_time method though. You can easily inline this, or even simpler, just use the datetime.datetime constructor:

def test_patch_datetime():
    for utc_time in [
        dt.datetime(2019, 1, 1, 10),
        dt.datetime(2019, 2, 1, 13),
        dt.datetime(2019, 3, 1, 16),
    ]:
        FakeTime.fake_time = utc_time
        dt.datetime = FakeTime
        assert dt.datetime.utcnow() == utc_time

You should be aware that this can have side effects in other parts of your code, so it might be needed to replace it back with the original class after  the test method:

def test_patch_datetime():
    datetime_orig = dt.datetime

    utc_times = [
        dt.datetime(2019, 1, 1, 10),
        dt.datetime(2019, 2, 1, 13),
        dt.datetime(2019, 3, 1, 16),
    ]
    for utc_time in utc_times:
        FakeTime.fake_time = utc_time
        dt.datetime = FakeTime
        assert dt.datetime.utcnow() == utc_time
    dt.datetime = datetime_orig
    # print(dt.datetime.utcnow())
    assert dt.datetime.utcnow() > max(utc_times)


Python Method for Text Input from Project Euler

First of all, let's make use of the with statement so that the file is closed automatically:

with open(path, 'r') as txt_file_object:
    text = txt_file_object.readlines()

With this, you don't have to call close() anymore, as the file will close automatically when you exit the with scope.

text = text[0]

You are only reading the first line of text. Is this really what you want to do?

You are using the variable text for two different things: for the input lines and for the output values. This is not very intuitive; in fact, the result can be a list of integers, so why would it be called text? Maybe result would be a better name for it.

BUT since now you don't have to close at the end of the function, you can return the result directly instead of saving it in a variable:

return [int(num) for num in text.split(sep)]

Returning will exit the with scope, so again the file will be closed automatically.

[let for let in text.split(sep)]

This selects all objects inside text.split(sep), so we can return the splitted list directly:

text.split(sep)

Similarly, there's a different way of applying a function to every item in a list, which is using map. Maybe the list comprehension feels more natural, so you can keep that if you want; still I'll show you just so you know:

# Creates a list by calling 'int' to every item in the list
list(map(int, text.split(sep))

You are repating a lot of code; you have four different results, but they are very similar, so let's try to provide a more generic way.

My concern here is handling the two possible dimensions. You are parsing the text in the same way (depending if it's int or str), but when it's two dimensions you do it for every line. So we could use Python's lambdas to decide first what type of parsing (int or str) we are doing, and then just apply it once or multiple times.

The lambda can take parameters; the only parameter we need in our case is the input text. We can't just use text directly because sometimes we want to parse the full text, but sometimes only the line:

if typ == "int":
    parse_function = lambda t: list(map(int, t.split(sep)))
elif typ == "str":
    parse_function = lambda t: list(t.split(sep))
else:
    raise ValueError("Unknown type.")

Now parse_function can be used like any other function, taking the text as input. So we can use it when deciding the dimension:

if dim == 1:
    return parse_function(text)
elif dim == 2:
    return [parse_function(line) for line in text]
else:
    raise ValueError("Unknown dimension.")

You do well in throwing exceptions for invalid input, but how is the user meant to know what possible values can be used for typ and dim? You could add that to the docstring. You should also say what the function does in the docstring.

Updated code

def read_array_from_txt(path, dim, typ, sep):
    '''
    Processes a text file as a 1D or 2D array.
    :param path: Path to the input file.
    :param dim: How many dimensions (1 or 2) the array has.
    :param typ: Whether the elements are read as 'int' or 'str'
    :param sep: The text that is used to separate between elements.
    @time: O(n)
    @space: O(n)
    '''
    with open(path,"r") as txt_file_object:
        text = txt_file_object.readlines()

        if typ == "int":
            parse_function = lambda t: list(map(int, t.split(sep)))
        elif typ == "str":
            parse_function = lambda t: list(t.split(sep))
        else:
            raise ValueError("Unknown type.")

        if dim == 1:
            return parse_function(text)
        elif dim == 2:
            return [parse_function(line) for line in text]
        else:
            raise ValueError("Unknown dimension.")


Are there any improvements I can make to my implementation of the strategy pattern?

You can do this more elegantly by specifying a Func delegate instead of an enum and a set of interfaces.

class Program
{
    static void Main(string[] args)
    {
        string message = "mytext";

        Changer chng = new Changer();

        string messageModified = chng.Change(message, Strategy2);
    }

    // These methods have a Func<string,string> signature
    // i.e. accept string as parameter and return a string
    static string Strategy1(string input)
    {
        return "hello1";
    }
    static string Strategy2(string input)
    {
        return "hello2";
    }
}

public class Changer
{
    public Changer()
    {
    }

    private Func<string,string> _stringModifier;

    public void SetStringModifier(Func<string,string> stringModifier)
    {
        this._stringModifier = stringModifier;
    }

    public string Change(string text, Func<string,string> stringModifier)
    {
        SetStringModifier(stringModifier); // why?

        return _stringModifier(text);
    }
}

  what was meant by the comment //why?

I would have thought that one of the following might be better.

Either, set the strategy once and use it repeatedly, like this ...

public class Changer
{
    public Changer()
    {
    }

    private Func<string,string> _stringModifier;

    public void SetStringModifier(Func<string,string> stringModifier)
    {
        this._stringModifier = stringModifier;
    }

    public string Change(string text)
    {
        return _stringModifier(text);
    }
}

... or like this ...

public class Changer
{
    public Changer(Func<string,string> stringModifier)
    {
        this._stringModifier = stringModifier;
    }

    private Func<string,string> _stringModifier;

    public string Change(string text)
    {
        return _stringModifier(text);
    }
}

Or, pass the strategy into the Change method every time, in which case there's no need to store it in as member data, like this ...

public class Changer
{
    public Changer()
    {
    }

    public string Change(string text, Func<string,string> stringModifier)
    {
        return stringModifier(text);
    }
}

  Thank you, another question is, wouldn't this allow the user to just write their own strategy and pass it to chng.Change() method?

Yes it would. That's often a good thing: it makes the class more 'flexible', so that it can be used in ways you hadn't imagined.

  And if my end goal is to make this an API, is that acceptable? Should I restrict them like I did in my original post using the enumeration?

I don't know. If you want to keep the enum, you could still use a Func delegate instead of an interface with several subclasses (and use a switch statement instead of repeated if/else).

public class Changer
{
    public Changer()
    {
    }

    private Func<string,string> _stringModifier;

    public void SetStringModifier(Types type)
    {
        switch (type)
        {
            case Types.Type1:
                this._stringModifier = Strategy1;
                break;
            case Types.Type2:
                this._stringModifier = Strategy2;
                break;
            default:
                throw new NotImplementedException();
    }

    public string Change(string text)
    {
        return _stringModifier.Modify(text);
    }

    static string Strategy1(string input)
    {
        return "hello1";
    }
    static string Strategy2(string input)
    {
        return "hello2";
    }
}


Modeling a classroom with teacher and students using the mediator pattern in Go

Ok, let's start from the top: Is this a mediator pattern?

I'd argue what you have is 2 components of a mediator pattern (2 objects that interact) without an actual mediator. To just quote the first line of the wiki entry for the mediator pattern:

  In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact.

So it's an object encapsulating interactions between a set of objects. What you're doing is creating 2 types that interact, and because it's modelled on a teacher/student example, where students are quite passive, you're calling the teacher the mediator. However: how does the teacher encapsulate how a set of objects (ie the students) interact? It doesn't.

This isn't a bad thing, though, as you're probably coming from another, more classically OOP language, and you're trying to replicate what you're used to in go. That's a common mistake people make. Go is not a classical OO language, though. It doesn't have classes, yet has (ducktype/implicit) interfaces. It doesn't have inheritance, but has composition. It doesn't have exceptions, it doesn't have a specific things like static properties, or static methods. So please, don't force yourself to stick to the classical OO patterns. Use the freedom and expressive power Go brings through it's slightly different type system.

Other criticisms I have directly relating to your code:

func (a *ClassMate) Class() string {
   return a.forum
}

Why use a pointer receiver here? This is basically making what should be a perfectly safe function unsafe. Imagine:

go func() {
   student.forum = "some random message"
}()
fmt.Printf("student says: %s", student.Forum()) // or whatever

What is the output going to be? Can you be sure it's always going to be the same?

The same applies to the Learned() func for the student and Spread(messqger string) for the teacher/"Mediator". Especially the teacher, in fact. The Spread function might be fired off concurrently, as it may take some time to return. If you imagine a scenario where someone ends up doing something like this:

go teacher.Spread("some really important life-lesson")
teacher.TeachTo(anotherStudent)
// and some more calls like this
teacher.TeachTo(anotherStudent2)
teacher.TeachTo(anotherStudent3)

How confident are you that the result of the code above will be reliable and reproducible? I'd much rather have a copy of the slice head available to me at the point where the call is made, rather than to rely on the behaviour of a range loop. The moment you add some checks, or other logic in the Spread function, you're at risk of the behaviour changing.

Lastly, as noted in my comment: TeachesTo(c *Student) is invalid code. Student is an interface type, there is no pointer-to-interface type. It's either a pointer to a type implementing said interface, or the interface itself.

Moving on from the code itself, and more into more general comments/suggestions on how to approach things in a more idiomatic golang type of way.

I can't help noticing you're calling this an awful lot in succession:

teacher.TeachesTo(student)

Golang supports for variadic arguments, just pass in all the students at once. The name of the func is also quite misleading. If I see TeachesTo, I expect the call to actually interact with the object I'm passing in, as and when I pass it in. I don't expect a later call to Spread to actually perform the action. I'm expecting to be able to call TeachesTo, and be done with it. I'd change the Mediator interface to a Classroom or Course interface along the lines of:

type Course struct {
    EnterTeacher(t Teacher) error // Teacher being an interface
    EnterStudents(s ...Student) error // variadic, only requires a single call
    AddLesson(data []string) error // using []string, but probably should be structured
    StartLesson() error
    TeacherLeave() error
    StudentsLeave() error
    EndLesson() error
    GetComplaints() []string // complain type?
    GetBannedStudents() []Student
    GetScores() map[string]float64 // results by student name?
    // and so on...
}

Now we actually have a mediator. We just add a teacher, add one or more lessons, we can start/stop lessons, get some kind of state (like scores, banned students, complaints about the way the teacher interacts with the students etc...

The implementation could be a simple thing like:

type course struct {
    name       string
    t          Teacher
    s          []Student
    lessons    []Lesson // create a type that's fitting
    day        int // can be used as offset in lessons
    scores     map[string]float64
    complaints []string
    banned     map[string]Student
}

Other repercussions of this approach: you'll notice both the type and the fields are not exported. That's how it should be: the whole point of a mediator is that you encapsulate the way objects interact. You shouldn't leave them exposed to external interaction, for that very reason.

Usage, quite simple

package school // or whatever

// google functional options if this is confusing you
type CourseOption func (c *course)

// add funcs like these for banned students, lessons, students, etc...
func SetCourseTeacher(t Teacher) CourseOption {
    return func(c *Course) {
        c.t = t
    }
}

func NewCourse(n string, opts ...CourseOption) Course {
    c := &course{
        name: n,
        scores: map[string]float64{},
        banned: map[string]Student{}, // initialise these to avoid issues when accessing these
    }
    for _, o := range opts {
        o(c)
    }
    return c
}
// a couple of implementation examples:

func (c *course) EnterStudents(s ...Student) error {
    // ensure we're not entering a banned student
    for i := range s {
        if _, ok := c.banned[s[i].Name()]; ok {
            return fmt.Errorf("student %s is banned", s[i].Name())
        }
        if _, ok := c.scores[s[i].Name()]; ok {
            return fmt.Errorf("student %s already entered", s[i].Name())
        }
    }
    // this is messy, but required
    for i := range s {
        s.scores[s[i].Name()] = 0 // add new name to score list
    }
    c.s = append(c.s, s...) // append students from arg to students in list
    return nil
}

As you can see, I can now safely add any number of students, and return errors in case some of them are banned already, and a different error in case the student was already added. It also initialises the state correctly. Now let's see some actual mediation implemented:

func (c *course) StartLesson() error {
    if len(c.lessons) <= c.day {
        return fmt.Errorf("no lesson can be started, Last lesson %d of %d", c.day, len(c.lessons))
    }

    // mediator decides which lesson object the teacher uses, and determines the teacher should prepare it
    if err := c.t.PrepareLesson(c.lesson[c.day]); err != nil {
        return err
    }
    // pass in students to which to teach the prepared lessen to, like a mediator does
    if err := c.t.Teach(c.s...); err != nil {
        return err
    }
    return nil
}

func (c *course) EndLesson() error {
    if !c.t.InClass() {
        // obviously...
        return fmt.Errorf("teacher not in class, cannot end lesson")
    }
    // see if teacher banned anyone
    for _, banned := range c.t.ProblemStudents() {
        // find student in slice, cut from slice and add to banned map
        // at this point, a map of students is easier to handle, but I can't be bothered
        // to rewrite most of this answer ;-p
    }
    for i := range c.s {
        // listen to complaints from students, too
        c.complaints = append(c.complaints, c.s[i].Complaints()...)
    }
    // mediator checks if the lesson was important, and instructs the teacher
    // to prepare a test. How the test is taken, is part of the lesson preparation and the teaching implementations
    if c.lessons[c.day].Important() {
        c.t.PrepareTest()
    }
    c.day++ // increment this, so we don't accidentally start the same lesson again
    return nil
}

Now at this point, this is getting rather convoluted and complex. It's suffering from the classical OEP-bloat (Over-Engineered-Programming). Something the golang designers wanted to discourage in their language.

Note that all of the code I provided above is very unsafe the moment you're going to use it with concurrency: the use of maps is, by definition unsafe. If you have someone calling:

go course.EnterStudents(studentSlice[4:]...)
go course.EnterStudents(studentSlice...)
studentSlice := append([]Student{prependStudent}, studentSlice[4:6]...)
go course.EnterStudents(studentSlice...)

Guess what will happen, that is: if it's even possible... (hint: it's not).

I'd recommend you use the sync package, and always test/compile with the race-detector.


General feedback

I will try to go over some points that can be useful to note. Firstly there are several things I like about your code. Firstly it is very readable. Secondly I like that you split your logic. You also split finding the string and printing it. This is good. With this being said there are always things which could and should be improved

Semantics

You should use the if __name__ == "__main__": module in your answer.

def fizz_buzz(num):
    if num%3==0 and num%5==0:
        return 'FizzBuzz'

    elif num % 3 == 0:
        return 'Fizz'

    elif num % 5==0:
        return 'Buzz'
    else:
        return num

if __name__ == "__main__":

    for n in range(1,100):
        print(fizz_buzz(n))

Which makes your code reusable for later. Eg you can call functions from your file in other programs.
Your else clause at the end of the code is useless. You could have written

    elif num % 5==0:
        return 'Buzz'
    return num

Alternatives

One problem with your code is that you have multiple exit points. Now this is not something to sweat too hard over, and it is not a goal to always try have a single exit. However it can be easier to debug a code with fewer exit points. This is of course much more relevant in longer and more complex code. Though it is a good thing to always have in mind. One way to do this is to define a new variable string

def fizz_buzz(num):
    string = ''
    if num%3==0 and num%5==0:
        string = 'FizzBuzz'

    elif num % 3 == 0:
        string = 'Fizz'

    elif num % 5==0:
        string = 'Buzz'

    if string:
       return string
    return num

The code now only has two exit points however it can still be improved. One key point is that if a number is divisible by 3 and 5, it is divisible by 15. So we can gradually build the string, like shown below

def fizz_buzz(num):
    string = ''

    if num % 3 == 0:
        string += 'Fizz'

    if num % 5==0:
        string += 'Buzz'

    if string:
       return string
    return num

As a last point the return statement could be written using a terniary conditional operator

return string if string else n

Which combines the two exit points into a single one. To sumarize

def fizz_buzz(num):
    string = ''
    if num % 3==0: string +='Fizz'
    if num % 5==0: string +='Buzz'
    return string if string else num

if __name__ == "__main__":

    for n in range(1, 100):
        print(fizz_buzz(n))

Closing comments

Python has a style guide PEP 8 which explains in excruciating detail how to structure your code. I whole heartily recommend skimming through it and follow it.

The problem FizzBuzz is very, very simple. It can be solved in a number of ways using just a simple line. Syb0rg, showed one way to write this code

for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i)

You can even shorten this into

i=0;exec"print i%3/2*'Fizz'+i%5/4*'Buzz'or-~i;i+=1;"*100

Using some cryptic pythonic voodoo. However as I said in the introductory I like your code, because it is easy to understand. Almost always it is better to have clear, readable code than cryptic code which is a few lines shorter. This of course disregards any speed improvements and such


Overview

Good first try. It seems like it works. But currently it only works for vectors and ints.

Some thoughts for improving the algorithm in the future.

If you look at most C++ algorithms they don't take a container as a parameter (vector<> is a container), instead they take iterators into the container. That way the algorithm can be used on any type of container (or a sub range of a container).

Also be using templates you can make the code work with any type that supports the comparison operator less than operator<.

Code Review

Vertical White Space

Nothing wrong here:

#include <vector>
#include <iostream>
using namespace std;
void sort(vector<int> & bar);
void mergeSort(vector<int>&left,vector<int>& right,vector<int>& bars);

But it seems a bit cramped all together. If you add some judicious vertical white space you can make it easier to read. I tend to separate logically distinct parts with an extra blank line. Like this:

#include <vector>
#include <iostream>

using namespace std;

void sort(vector<int> & bar);
void mergeSort(vector<int>&left,vector<int>& right,vector<int>& bars);

Using namespace

Please don't do this:

using namespace std;

Yes. All the C++ text books use it. But they are trying to save space because a book only has so much space available for printing. In real programs this is actually quite dangerous and should be avoided.

The reason the Standard namespace is called std is so that prefixing members with std:: is not a big hurdle.

Read this for details: Why is “using namespace std” considered bad practice?

Prefer prefix ++

    for (size_t i = 0; i < 11; i++)

OK. In this case (and a lot of cases) it makes no difference if you use the prefix or postfix version. But it can make a difference when the object being incremented is an object (lot of container iterators). A lot of the time when modifying C++ code, you change the type in one place and the type changes will cascade through your code, so it is best to always use the most efficient version no matter what the current type is. So in these cases prefer to use the prefix increment.

If you always use prefix ++ then you will always have the optimal increment.

    for (auto i = 0; i < 11; ++i) // Also note the use of auto

rand() is not very random

        nums.push_back(rand() % 1000);

This is the C random number generator. C++ has its own random number generator that is much better.See here for interface and example: http://en.cppreference.com/w/cpp/numeric/random

Also note that because you don't use srand() you will get the same sequence of numbers every time (which is a useful feature for testing).

Prefer Range based for:

When iterating over a container (something that supports begin/end) prefer to use the range based for.

    for (size_t i = 0; i < nums.size(); i++)
        cout << nums[i] <<endl;

    for (auto const& num: nums) {
        cout << num << "\n";
    }

Always use {} around sub blocks

I know it looks safe not to bother in places like this:

    for (size_t i = 0; i < nums.size(); i++)
        cout << nums[i] <<endl;

But it is a common type of error to add an extra indent line or use a function that happens to be multiple statement macro. To avoid these issues simply add braces.

    for (size_t i = 0; i < nums.size(); i++) {
        cout << nums[i] << "\n";
    }

Prefer '\n' over std::endl

The main difference in the two is that std::endl in addition to adding \n to the stream will flush the stream. The stream will already auto flush at the optimal times and forcing a manual flush will only result in a degradation in performance.

Don't use system dependent code

    system("pause");

This only works on windows. Easier to just ask the user for input.

    std::cout << "Hit Return to continue\n";
    std::string line;
    std::getline(std::cin, line);

Don't need return in main

    return 1;

The main() function is special. If you don't specify a return value then the compiler will auto generate one for you that returns 0.

So it has become traditional for simple applications that never fail to have no return statement as an indication that this application will never fail. If I see a return statement at the end of main I will look through main to find the other return statements that indicate a failure state.

You should also note that a return value of non zero from main() is an indication to the operating system that the application failed. So return 1; lets the OS know your application failed and can potentially cause it to throw up an error screen to the user.

The & and * are part of the type

The & and * are part of the type in C++ and usually placed syntactically with the type information.

void sort(vector<int> & bar) {

Putting a space between the type and the & just looks strange.

void sort(vector<int>& bar) {

Don't run if statement together

    if (bar.size() <= 1) return;

Prefer to use two lines for this (and the sub block brace).

    if (bar.size() <= 1) {
        return;
    }

When debugging the code and stepping through it this will make your life easier.

Use reserve

    int mid = bar.size() / 2;
    vector<int> left;
    vector<int> right;

To prevent potential re-allocation of the underlying storage you can use reserve to make sure these vectors have enough space.

    left.reserve(mid);
    right.reserve(bar.size() - mid);

Prefer to use standard algorithms rather than manual loops.

    for (size_t j = 0; j < mid;j++)
        left.push_back(bar[j]);
    for (size_t j = 0; j < (bar.size()) - mid; j++)
        right.push_back(bar[mid + j]);

There is a standard copy. You should check out the standard for a list of helpful algorithms. http://en.cppreference.com/w/cpp/algorithm

    std::copy(std::begin(bar), std::begin(bar) + mid, std::back_inserter(left));
    std::copy(std::begin(bar) + mid, std::end(bar), std::back_inserter(right));

One Line Per Variable (and use meaningful names)

    int i = 0, j = 0, k = 0;

There is a big push for self documenting code. Part of this is to make sure that you can understand what is happening by reading the names of the variables and the functions. So names like i,j,k are not meaningful (unless you happen to have done a lot of fortran programming).

    int leftLoop  = 0;
    int rightLoop = 0;
    int barLoop   = 0;

Stable Sort

An important property of sorting is to try and keep equal object in the same relative order after the sort. A sort that does this is called a stable sort. This means if two values are equal you should choose the one from the left rather than the right vector.

        // This is not stable.
        // When the objects are equal you select the one from the right.
        // To make this sort stable change to use `<=`
        if (left[j] < right[k]) {
            bars[i] = left[j];
            j++;
        }
        else {
            bars[i] = right[k];
            k++;
        }

Simplify using Ternary

This is a dangerous piece of advice. Use it judiciously as overuse can make the code harder to read. But sometimes it is useful to use ? : operator as it can make the code simpler and easier to read.

But sometimes it is useful to use the ternary operator instead of and if then else block. I think this is one of these places (others will disagree so use if you like).

        bars[i] = (left[j] <= right[k])
                    ? left[j++]
                    : right[k++];
        ++i;

Advanced Section

I would redesign this to use templates and iterators.

template<typename I>
void sort(I begin, I end);
template<typename I>
void merge(I leftBegin, I leftEnd, I rightBegin, I rightEnd, I destination);

When you start using templates and don't know what the type being sorted is things can get complicated because the underlying type may be very expensive to copy around. So you should prefer to move object rather than copy objects (for integers it makes no difference so I did not mention it above).

for(auto& val: container) {
    dest.emplace_back(std::move(val));
}

Also there is a move algorithm for moving objects from one container to another.

std::move(std::begin(container), std::end(container), std::back_inserter(dest));

You allocate a lot of temporary vectors (there is a left/right in each recursive call to sort()). You can pre-allocate these vectors and re-use them throughout your recursion (with a tiny bit of extra work).


All-Python implementation of n-dimensional convolution

Specific suggestions:

All t abbr mks th c hard 2 rd. Plz repl abbrs w/full wrds. Think of variable names as comments – they don't matter at all to the computer, but they do matter to anybody reading the code. A good rule of thumb is that if any of your comments explain what is coming up rather than why it was done like that, you can probably replace the comment with more elegant code. I've been working over a year with some colleagues on a medium-size new system, and we've taken this approach to heart: about 0.5% of the lines in Python files have comments on them.
Conversions often take a lot of time, especially on a lot of items, and even more especially in a loop. Working with only lists or only tuples might speed up things a bit. In terms of readability, tuples are generally used when there is a fixed number of items, often of different types. Neither of these seem to apply to this code.
The contents of the function can probably be split into at least three more for readability:

validation,
mode handling, and
the loop contents.

The modes could be related as Enum values:

class Mode(Enum):
    FULL = "full"
    VALID = "valid"
    SAME = "same"

def …(…, mode: Mode = Mode.FULL):

General suggestions:

black can automatically format your code to be more idiomatic.
isort can group and sort your imports automatically.
flake8 with a strict complexity limit will give you more hints to write idiomatic Python:

[flake8]
max-complexity = 4
ignore = W503,E203

I would then recommend adding type hints everywhere and validating them using a strict mypy configuration:

[mypy]
check_untyped_defs = true
disallow_untyped_defs = true
ignore_missing_imports = true
no_implicit_optional = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_ignores = true


ConditionalActions through std::function Lambdas

This is long winded:
std::vector<CConditionalAction> vecConditionalActions;
vecConditionalActions.push_back(FirstConditionalAction);
vecConditionalActions.push_back(SecondConditionalAction);
//vecConditionalActions.push_back(MoreConditionalActions);
vecConditionalActions.push_back(LastConditionalAction);

Easier to use the constructor to put everything in place.
std::vector<CConditionalAction> vecConditionalActions
    {
        FirstConditionalAction,
        SecondConditionalAction,
        // MoreConditionalActions,
        LastConditionalAction
    };

// Note: You should probably make that a static variable so it is
//       only built once the first time it is created.

I don't see the point in writing a functor to hold a functor (a lambda) then wrap that in a functor (std::function) to hold in a vector. The whole CConditionalAction class is not necessary.
std::vector<std::function<bool()>> vecConditionalActions {
        [&](){if (false){return true;}return false;},
        ....
    };

I am surprised this compiles:
std::function<bool()> m_ConditionalAction = nullptr;
                                      ///   ^^^^^^^^

But it does. But what does it mean? Not sure. Not sure I want to find out either as there is no pointer semantics involved here. But since you have a constructor this will never be activated anyway. Writing code that has no clear meaning is a bad idea.
I am assuming your code in the lambdas is just example code as it does nothing.
Final Thought.
The point of this exercise was:

to make a huge if-else construct more human readable, extendable and configurable (switch positions of conditions)

I don't think you have a succeeded. I think this code just makes the code more obscure by hiding the actions in a separate file.


Duplicate code in day of the week event handlers

What you need to do is:

Add a parameter of type System.DayOfWeek called, say, day_of_week.
Replace the fields BinaryDataGrid.Sunday, .Monday, etc. with a Dictionary<K,V> that has a key of type System.DayOfWeek and use day_of_week to access values within that dictionary.
Do the same for your _sun, _mon etc. global variables. (For which you will burn in hell, incidentally.)

If you cannot modify BinaryDataGrid, then write two helper methods, one for getting and one for setting the value of the day member of BinaryDataGrid: Each method has a switch( day_of_week ) and modifies the appropriate member of BinaryDataGrid.

Good luck and have fun.


To start with, I'd add the activation probability as a parameter of the independant_cascade_igraph function. That way you are assured that the attribute is defined on the edges and can also manage default value. Thus you are not required to know the name of the edge attribute  in advance to use your function:

def independent_cascade_igraph(G, seeds, probs=0.1, steps=0):
    # init activation probabilities
    if (type(probs) in (int, float) and (0 <= probs <= 1)) or all(0 <= p <= 1 for p in probs):
        G.es['act_prob'] = probs
    else:
        raise Exception("Found probability outside of [0, 1]")

However I recommend you define your own Exception so further handling is better performed.

The copy of the seeds can be simplified since it represent vertices which are always integers:

    # perform diffusion
    A = seeds[:] # prevent side effect

The two functions for the diffusion hold the same logic, only the stopping condition differ. DRY:

    if steps <= 0:
        # perform diffusion until no more nodes can be activated
        return _diffuse(G, A)
    # perform diffusion for at most "steps" rounds
    return _diffuse(G, A, steps)

def _diffuse(G, A, steps=None):
    vertices = G.vcount()
    tried_edges = set()
    layer_i_nodes = [A[:]]
    while True:
        len_old = len(A)
        activated_nodes_round, tried_edges_round = _diffuse_one_round(G, A, tried_edges)
        layer_i_nodes.append(activated_nodes_round)
        tried_edges |= tried_edges_round
        if len(A) == len_old:
            break
        if steps is not None:
            steps -= 1
            if not steps or len(A) >= vertices:
                break
    return layer_i_nodes

Updating the set is more idiomatic.

You don't need to return A from _diffuse_one_round since it is modified in place:

def _diffuse_one_round(G, A, tried_edges):
    cur_tried_edges = set((s, nb) for s in A for nb in G.successors(s)) - tried_edges
    activated_nodes = [node for src,node in cur_tried_edges if node not in A and _prop_success(G, src, node)]
    A.extend(set(activated_nodes))
    return activated_nodes, cur_tried_edges

I'm going to assume that you actually what to retrieve the attribute here, orherwise just remove this function, all the attribute handling at the beginning and use random.random() <= 0.1 in the list comprehension:

def _prop_success(G, src, dest, r=random.random): # Faster access to random
    id = G.get_eid(src, dest)
    return r() <= G.es[id]['act_prob']

You can then test with:

test_g = Graph([(1,2), (2,1), (1,3), (3,1), (2,3), (2,4), (3,4), (3,5), (4,5), (5,6), (6,5), (6,4), (6,2)], directed=True)
independent_cascade_igraph(test_g, [1], [.5, .5, .2, .2, .3, .5, .1, .2, .2, .6, .6, .3, .4])

Note however that the very purpose of _diffuse_one_round, its gained simplicity and the fact that it has the non-trivial side effect of modifying A in place, all play in favor of merging it in the while loop of _diffuse instead of keeping it:

def _diffuse(G, active_nodes, steps=None):
    vertices = G.vcount()
    visited_edges = set()
    activation_history = [active_nodes[:]]
    previous_len = None
    while previous_len != len(active_nodes) and (step is None or step):
        previous_len = len(active_nodes)
        current_edges = set((begin, end) for begin in active_nodes for end in G.successors(begin)) - visited_edges
        activated_nodes = [node for src,node in current_edges if node not in A and _prop_success(G, src, node)]
        active_nodes.extend(set(activated_nodes))
        activation_history.append(activated_nodes)
        visited_edges |= current_edges
        if steps is not None:
            steps -= 1
    return activation_history

I also renamed some variables to make the code more explicit, which you should do more often.


Implement operation and simulation mode in an interface

You could simply have if-statements in each method of your class. This would probably result in (slightly) lesser lines of code than my suggestions. However, I think that solution has a lot of repeated code and is quite static. What if you wanted a device that simply simulates? Or one that simply operates?

My suggestion is to abstract the classes a bit more and have seperate classes for each mode. Then have a final DualModeDevice class that inherits from both of them:

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

    def operation_start(self):
        # Do operation specific code
        self.start()

    def operation_stop(self):
        # Do operation specific code
        self.stop()

    def operation_pause(self):
        # Do operation specific code
        self.pause()

    def operation_resume(self):
        # Do operation specific code
        self.resume()

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

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

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

    def simulation_pause(self):
        # Do simulation specific code
        self.pause()

    def simulation_resume(self):
        # Do simulation specific code
        self.resume()

class DualModeDevice(OperationDevice, SimulationDevice):
    def __init__(self, mode='simulation'):
        super(DualModeDevice, self).__init__()
        self._mode = mode

        # To be continued

Each function in SimulationDevice and OperationDevice needs to be named differently because of how Python interprets and resolves inheritence. If there is a identically named function from multiple inheritances, it will use the first available reference from the MRO (method resolution order).

Now with that being said, you could implement dual mode in two ways:

Function mapping

One way is to simply have a dict that holds a mapping from mode to function:

class DualModeDevice(OperationDevice, SimulationDevice):
    def __init__(self, mode='simulation'):
        super(DualModeDevice, self).__init__()
        self._mode = mode
        self._start_map = {
            'simulation': self.simulation_start,
            'operation': self.operation_start
        }
        # Repeat the above line for `stop`, `pause`, and `resume`.
        # Or you could combine them into a single `dict`.

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

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

getattr

If you felt like being sneaky, you could use the getattr function (assuming consistent function names):

class DualModeDevice(OperationDevice, SimulationDevice):
    def __init__(self, mode='simulation'):
        self._mode = mode

    def run_command(self, command, mode=self.mode):
        getattr(self, '{}_{}'.format(mode, command))()

Since functions boil down to callable properties in classes, we can simply use getattr to get the correct function, then call it.


VBA Loop through multiple sheets to output formulas in multiple columns

A couple of tips.

When using With, make sure that you correctly reference the subordinate lines. Check the following example.

With Range("KA1").Offset(i1 - 1, 0) '<--- You have ...
With .Range("KA1").Offset(i1 - 1, 0) ' ... should be

Consider using FillDown or some similar command to do bulk edits. This will save looping, especially the loop that flips between the VBA engine and the Excel engine (which is expensive time-wise). Normally I suggest using arrays, but your use of formula suggests this other way.

The following example has not been tested.

Dim formulaOneRange as Range
    Set formulaOneRange = .Range("KA25:KA" & lastRow)
    With formulaOneRange
        .Formula = "=IF(SUMIF(RRSData!$A$2:$O$10000,OFFSET($KA$1,CELL(""row"",THIS),-285),RRSData!$M$2:$M$10000)>0,SUMIF(RRSData!$A$2:$O$10000,OFFSET($KA$1,CELL(""row"",THIS),-285),RRSData!$M$2:$M$10000),"""")"
        .NumberFormat = "0.00"
        .Value = .Value
    End With
    Set formulaOneRange = .Range("KB25:KB" & lastRow)
    With formulaOneRange
        .FormulaR1C1 = "=IF(RC[-1]="""","""",If(RC[-1]>1.1,""High"",If(RC[-1]<0.8,""Low"",""Neutral"")))"
        .Value = .Value
    End With
    Set formulaOneRange = .Range("KC25:KC" & lastRow)
    With formulaOneRange
        .FormulaR1C1 = "=IF(RC[-1]="""","""",If(RC[-1]>1.1,""High"",If(RC[-1]<0.8,""Low"",""Neutral"")))"
        .Value = .Value
    End With

Of course, the code could be tidies up a bit as per below, but I thought the extra lines will show my thinking a bit more clearly.

' My example code above ...
Set formulaOneRange = .Range("KC25:KC" & lastRow)
With formulaOneRange

' Could be ....
With .Range("KC25:KC" & lastRow)

Also, defining the range in an easy to manage variable would assist if you wanted to use FillDown or do some other manipulation within each section.


I'm using SHA-512 right now but I think I'll change it to mcrypt later.

Neither of those are the proper tool for the job. Mcrypt is meant for symmetric encryption (AES, TwoFish, DES, etc.), not password hashing.

If you're running PHP 5.5+, use password_hash() and password_verify()

Otherwise, https://github.com/ircmaxell/password_compat is the way to go.

EDIT: Example code:

<?php
Class User
{
    private $db;

    public function __construct($db)
    {
        $this->db = $db;
    }

public function Login($user_email, $user_pass, $remember = false)
{
        $query = $this->db->prepare("SELECT id, password FROM users WHERE email = :email");
        $query->bindValue(':email', $user_email);
        $query->execute();

        if($query->rowCount() > 0) {
            $user = $query->Fetch(PDO::FETCH_OBJ);
            if (password_verify($user_pass, $user->password)) {
                $_SESSION['loggd_id'] = $user->id;
                if($remember == true) {
                    setcookie('lggd_sess', hash('sha512', mcrypt_create_iv(64, MCRYPT_DEV_URANDOM)), 84600);
                    return true;
                }
                return true;
            } else {
                return 'Incorrect Email/Password Combination.';
            }
        } else {
            return 'Incorrect Email/Password.';
        }
    }
}

When you insert a row in the DB, you want to use password_hash($user_password)


Simple code for calculating damage increase

Define some data structures.

Data definitions are clear, complete, obvious, in one place
DRY principle - a single place to change data values
client code does not change if data values change
Declared "Default" Element to keep code consistent
Reusable

.

public DamageFactor {
   public float Wisdom    { get; protected set; }
   public float Domanince { get; protected set; }
   public float Control   { get; protected set; }

   public DamageFactor (int wisdom, int domanince, int control) { ... }
}

public Dictionary<Element, DamageFactor> Damage = new Dictionary<Element, DamageFactor>() {
    { Element.Fire,    new DamageFactor { Wisdom = 0.3f, Dominance = 0.1f, Control = 0.1f },
    { Element.Earth,   new DamageFactor { Wisdom = 0.3f, Dominance = 0.1f, Control = 0.1f },
    { Element.Wind,    new DamageFactor { Wisdom = 0.3f, Dominance = 0.1f, Control = 0.1f },
    { Element.Water,   new DamageFactor { Wisdom = 0.3f, Dominance = 0.1f, Control = 0.1f },
    { Element.Impact,  new DamageFactor { Wisdom = 0.1f, Dominance = 0.3f, Control = 0.1f },
    { Element.Default, new DamageFactor { Wisdom = 0.1f, Dominance = 0.1f, Control = 0.3f }
};

public Dictionary<Element, int> Resistance = new Dictionary<Element, int>() {
    { Element.Fire, 12 },
    { Element.Earth, 9 },
    { Element.Water, 7 },
    { Element.Wind, 5 },
    { Element.Impact, 3 },
    { Element.Default, 1 }
};

public static float DamageIncrease(SpellData attack, Entity caster) {
//Elemental damage is more increased by wisdom attribute
//Impact damage is more increased by dominance attribute
//summon level is increased by control attribute

float bonus = 0f;
bonus = caster.wisdom    * Damage[attack.element].Wisdom +
        caster.dominance * Damage[attack.element].Dominance +
        caster.control   * Damage[attach.element].Control;

return attack.damage + bonus;
}

public static float RealDamage(SpellData attack, Entity target, Entity caster) {
    float max_variation = attack.damage_variation / 2f;
    float min_variation = max_variation - attack.damage_variation;
    float resist_percent = 0f;
    float dmg = DamageIncrease(attack, caster) + Random.Range(min_variation, max_variation);

    resist_percent = Resistance[attack.element];
    dmg -= (dmg * resist_percent / 100f);

    if (dmg < 1f)
        dmg = 0f;

    return dmg;
}


My implementation of a for_each function that traverses a std::container by some step size integer N

We could use Container::size_type or std::size_t for the increment_by parameter, or (as standard algorithms like std::for_each_n seem to do) make it a template argument and use the same type while incrementing n.
The standard library algorithms take iterators rather than containers. You mention allowing users to specify an "index location they want to use for their starting position", which would be accomplished by passing an iterator range instead of calling begin and end.
I don't think the default increment_by argument value is useful. If we needed a step size of 1, we'd call std::for_each or use a range-based for loop.
std::for_each returns the function object (which can be helpful for something like summing values). We could do the same.
Follow the standard library conventions with naming template arguments (e.g. name the minimum required iterator type, make it clear that the function is a unary function).

Modified version:

template<class InputIt, class Size, class UnaryFunction>
UnaryFunction for_each_by_n(InputIt begin, InputIt end, Size step, UnaryFunction f) {

    if (step == 0)
        return f;

    while (begin != end)
    {
        f(*begin);

        for (Size n = 0; n != step; ++n)
        {
            if (begin == end)
                return f;

            ++begin;
        }
    }

    return f;
}

(edit: removed unnecessary std::move per Juho's comment).


Review of HTML markup for this blog concept

Your img is missing the alt attribute.

I assume that here a graphic will be inserted via CSS? Then this will not be accessible by users without CSS support, and it will probably not be accessible by screen reader and/or keyboard users. The link should have content, i.e., an img (with alt attribute) or text ("Read more") (which can be visually hidden, if required).

Also, you shouldn’t use the i element in such a case (as your use doesn’t match i’s definition). Go with span if you need an element.

Why did you skip a heading level (from h2 to h4)? Either use h3 for the second heading, or go with h1 everywhere (but then you need to use sectioning elements explicitly!):

Skating Down Venice Beach

Venice Beach

If the text titled "Venice Beach" is just some general information about it (not unique to this image), consider to use the aside element instead of section.