Meta-circular interpreter for lambda calculus in Haskell

I wanted to give a more full answer, but I can't fully commit to it, so here are a few things:

Instead of having Wrong built into the result type, you would rather want Maybe Val, or better yet, Either String Val or Either Error val, since there are multiple possible causes for failure.
I'm a little skeptical about Fun (Val -> Val): This seems to serve two purposes:

The final result of interp could be a lambda.

Theoretically it must always be, but for a practical purpose, perhaps, you've decided that integers are different from functions. And that if one were to return a value that hasn't reduced to an integer, then rather produce a Haskell function that can resume evaluation later.

The drawback is that you can't further transform the structure hidden away in a Fun (Val -> Val) in the same way as you can with a Term; you can only reduce it further using interp. For example, you can only pretty-print the result if it's an integer, or a failure.
As an intermediate representation of a term being evaluated. But since any lambda reduction rule provides another term, Term should be an excellent intermediate representation.

When you express an intermediate state as Fun (Val -> Val), it also contains an implicit Env, which is in some sense a reader monad pattern. Typically you might represent this with Control.Monad.Reader instead.
I think keeping an Env might be neat - I've seen several examples of people building quite advanced lambda calculus interpreters that do this. But when I first thought how I'd make it myself, I thought of

interp (App (Lam x body) arg) = subst x body arg
interp (App (Var x) _arg) = Left ("Free variable " ++ show x)

since, if I encountered a Var x on the left-hand side of an application, I'd know that it hadn't been substituted by an outer reduction. But I'm not wise enough to say which is better here, that was just my first thought.
I'd rename Cons to Num or Int: Cons seems a bit contrived for constant, and Const is a bit vague, since you really mean integer constant. But what constant is there about a lambda term? I mean, theoretically it could also be a function if the interpreter allowed it.
If your intermediate representation was Term and not Val, and your interpreter was monadic (e.g. for handling errors) you could merge add into apply, since Add is just a special-case function application:

interp (App (Lam x body) arg) = subst x body arg
interp (App (Var x) _arg) = Left ("Free variable " ++ show x)
interp (Add e1 e2) = add <$> interp e1 <*> interp e2

add (Int m) (Int n) = return (Int (m + n))
add x y = Left ("Cannot add non-integers " ++ show x ++ " and " ++ show y)

Pretty-printing m and n here is possible because Term's structure is not hidden within a Haskell -> function.
You have two things that could be expressed in terms of monads: Making Env implicit using a reader monad, and handling errors using Either. This could be expressed as

type Env = Map Var Term
type Interpreter = Env -> Term -> Either String Term

or rather using Control.Monad.Trans.Reader:

type Env = Map Var Term
type Interpreter a = ReaderT Env (Either String) a

which is equivalent under the hood, but it means you can do stuff like:

interp (Add e1 e2) = add <$> interp e1 <*> interp e2

  I don't care about alpha renaming

I'm not sure how to interpret this, but the following thought comes to mind:

It is idiomatic to model your data type as close to the domain, so the fact that Lam "x" (Var "y") passes type-check but can not evaluate (unless there's some kind of initial environment that catches free variables) is a problem. One way to address this I've seen is e.g. de Bruijn indexing as performed e.g. by James Fisher which is one way to say that he also doesn't care about alpha renaming by never having the need. One could even convert freely between one interpretation with variables and another without, depending on which representation is most convenient for a given purpose.


Simple counting fair semaphore implementation

As for your question of what happens to the intrinsic lock when the InterruptedException is thrown: As soon as wait() is called, the thread relinquishes the lock, which is stated in the documentation of Object.wait(). Continuing to hold the lock would defeat the purpose of wait(), which is to wait for some other thread to do something for which it needs the lock and be notified when that thread is finished with the task and no longer needs the lock, so that the current thread can start trying to re-acquire the lock.

This means that, in order to return from wait() and, if needed, execute the catch block, the thread has to acquire the lock again first. Once the thread does have the lock, however, entering the catch block will have no effect on the thread's ownership of the monitor.

I found this question, which, along with the answer given there, might contain what you're interested in.

Update

Here's a test to demonstrate that, even if the catch block is not synchronized, it will still only be executed after the thread has re-acquired the lock, because the thread must first return from wait(), which will only happen when it has the lock it was waiting on.

static void testControlFlow() {
    final Object lock = new Object();

    final Thread threadA = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                synchronized (lock) {
                    while (!Thread.currentThread().isInterrupted()) {
                        lock.wait();
                        /* Theoretically, it is possible that threadA will
                           be spuriously woken up AND be interrupted by
                           threadB between this wake-up and the next loop
                           iteration. If this unlikely scenario happens,
                           then the catch block will never be executed because
                           no InterruptedException will ever be thrown */
                    }
                }
            } catch (InterruptedException e) {
                System.out.println("threadA has caught an InterruptedException");
            }
        }
    });

    Thread threadB = new Thread(new Runnable() {
        @Override
        public void run() {
            while (threadA.getState() != Thread.State.WAITING) {
                //ensure that threadA acquires the lock before threadB
            }
            synchronized (lock) {
                threadA.interrupt();
                while (threadA.getState() == Thread.State.WAITING) {
                    //wait for threadA to wake up
                }
                System.out.println("threadA has woken up");

                while (threadA.getState() == Thread.State.RUNNABLE) {
                    //see if threadA can catch the exception without holding the lock
                }

                if (threadA.getState() == Thread.State.BLOCKED) {
                    System.out.println("threadA is now blocked and trying to acquire the lock");
                } else {
                    assert threadA.getState() == Thread.State.TERMINATED;
                    System.out.println("threadA has terminated while threadB was still holding the lock");
                }
            }
        }
    });

    threadA.start();
    threadB.start();
}

Output is:

threadA has woken up
threadA is now blocked and trying to acquire the lock
threadA has caught an InterruptedException


Implementation of LinkedList C++ using friend

You could do this:

template<typename T> class LinkedList {

    struct LinkedListNode {
        T m_element;
        LinkedListNode* m_next;

        LinkedListNode(T element)
        :
        m_element{element},
        m_next{nullptr}
        {}
    };

public:

    LinkedList()
    :
    m_head{nullptr},
    m_tail{nullptr}
    {}

    void add(T element) {
        LinkedListNode* node = new LinkedListNode(element);
    }

private:
    LinkedListNode* m_head;
    LinkedListNode* m_tail;
};

int main() {
    LinkedList<int> l;
}

That way, your LinkedListNode implementation is not available outside of your LinkedList.


Ruby script to load .xlsx files into a MySQL database

For starters, I'd break the script up into many more methods. If nothing else it'll avoid the "pyramid code" (all that nested indentation) you've got going on. But it should also make the code easier to understand, maintain and extend.

I'd also, as an overall approach, favor writing a file of INSERT statements, rather than inserting each row, one at a time. At least for testing, I'd highly recommend this. You can always read this file directly into mysql later. The point is that if, say, the first 2 rows get inserted fine, but the 3rd fails, you'll already have those first 2 row in the database, when you run the script again. And since the .xlsx files only get removed if everything works out, the same file may be imported several times - perhaps failing halfway several times - resulting in a bunch of doubled rows.

Speaking of files, I'd avoid completely removing the xlsx file once it's done. Probably better to move it or rename it, so you still have it, but it won't get read again. In general, just try to avoid destructive operations unless necessary.

Anyway, the code below is an attempt to break up your code. I haven't tried it, so don't just blindly run it or anything.

Moreover, I'm using RubyXL's get_table method here - I don't know if that's actually useful in your case. However, I imagine that the xlsx-files have a header row, since you always skip the first row. If those headers are sensical, you can use them to your advantage, and avoid the hard-coded (and opaque) column indices.

Some of the methods here have optional arguments that default to instance variables. I won't recommend that for production use; it's there for testing purposes. You can either make the arguments required, or you can remove the arguments, and rely on instance variables.

# Hash for translating xlsx columns to mysql columns
# The procs may not be necessary; get_table may handle conversion
COLUMN_TRANSLATIONS = {
  "Service"     => { column: "service",     proc: :to_s },
  "Impressions" => { column: "impressions", proc: :to_i },
  "Clicks"      => { column: "clicks",      proc: :to_i },
  "Cost"        => { column: "cost",        proc: :to_f },
  "Total"       => { column: "total",       proc: :to_f }
}.freeze

# Gets the relevant .xlsx-files
def xlsx_files(directory = @paid_adv_work_path)
  path = File.join(directory, "*(PPC)*.xlsx")
  files = Dir.glob(path)
  files.reject { |file| File.basename(file) =~ /^~/ }
end

# Use get_table to get structured data
def read_xlsx(file)
  workbook  = RubyXL::Parser.parse(file)
  worksheet = workbook.worksheets[0]
  worksheet.get_table(COLUMN_TRANSLATIONS.keys)[:table]
end

# Translate into a mysql-friendly format
def translate_table(table)
  table.map do |row|
    row.map do |column, value|
      lookup = COLUMN_TRANSLATIONS[name.to_s] # get_table uses symbol keys; we want strings
      value = value.send(lookup[:proc])
      [lookup[:column], value]
    end
  end
end

# Insert a row
def insert_rows(rows, connection = @db)
  columns = COLUMN_TRANSLATIONS.map { |name, info| info[:column] }
  rows.each do |row|
    columns = row.keys.join(", ")
    values  = row.values.map { |value| "'#{connection.escape(value)}'" }.join(", ")
    query = "INSERT INTO ppc (#{columns}) VALUES (#{values});"
    connection.query(query)
  end
end

# Put it together per-file
def import_xlsx_file(file, connection = @db)
  table = read_xlsx(file)
  rows  = translate_table(table)
  insert_rows(rows, connection)
end

# And all together now...
def import
  xlsx_files.each do |file|
    begin
      import_xlsx_file(file)
      # Handle file removal/renaming here
    rescue => e
      @log.info "Failed to import #{file}: #{e.message}"
    end
  end
end

An advantage of having the optional arguments is that you can swap out the database connection with a stand-in object, like:

class QueryLogger
  def initialize(logger)
    @logger = logger
  end

  def query(string)
    @logger.info(string)
  end
end

And try something like import_xlsx_file(some_file, QueryLogger.new(@log)) to log the queries instead of actually running them on the server.


Bad instructions

Perhaps the lab is instructing you specifically to write code in a certain way just for learning purposes, but there is some questionable advice in the instructions that I would recommend disregarding.

Printing the game instructions using multiple print statements is poor practice.  Combining the instructions into one long triple-quoted string is more readable and efficient.

Introducing a done flag variable is a bad idea in general.  If your goal is to direct the execution of code in a loop, use statements like continue, break, return, or raise.  Setting a variable just to have it tested later is needlessly indirect.  In fact, I would say that for this exercise, a done flag fails to capture enough state information for a realistic game.  (More on that below.)

Logic

The input is case-insensitive.  To avoid code repetition, you should immediately normalize the input to lowercase (or uppercase, as the instructions suggest):

user_choice = input("Your choice? ").upper()

There are five menu options, plus the "Quit" option.  Of those five, two are "instantaneous", and three involve the passage of time.  Of the three options that involve passage of time, two cause you to cover some distance.  The code should therefore be structured such that similar code is placed together.  Also, you should avoid generating and discarding random numbers that you aren't going to use (for example, fullSpeed = random.randrange(10, 21) when the user hasn't even decided to make a move).

# Quit
if user_choice == "Q":
    break

# Status check
elif user_choice == "E":
    print(…)

# Drink from canteen
elif user_choice == "A":
    if canteen == 0:
        print("You're out of water.")
    else:
        canteen -= 1
        thirst = 0
        print(…)

# Stop for the night
elif user_choice == "D":
    natives_traveled += random.randrange(7, 15)
    camel_fatigue = 0
    print(…)

# Moderate speed
elif user_choice == "B":
    natives_traveled += random.randrange(7, 15)
    miles_traveled += random.randrange(5, 13)
    camel_fatigue += 1
    thirst += 1

# Full speed
elif user_choice == "C":
    natives_traveled += random.randrange(7, 15)
    miles_traveled += random.randrange(10, 21)
    camel_fatigue += random.randrange(1, 4)
    thirst += 1

It's odd how you write variable *= 0 when you could just set variable = 0.

By my interpretation, it should not be possible to stumble across an oasis while resting for the night.  It would be even more realistic (and easier to code) if the probability of finding an oasis were proportional to the distance covered, but I don't get to make the rules.

When evaluating the situation at the end of the loop, I would place the position checks first, then the health checks, then any applicable warnings.  You don't really care about the natives drawing near or finding an oasis if you've already crossed the finish line.  You can also simplify the thirst and fatigue checks if you test for death first.  (By the way, in Python, you can also write double-ended inequalities like 5 < camelFatigue <= 8.)

# Position checks
if miles_traveled >= 200:
    print("You made it across the desert!")
    break
elif natives_traveled >= miles_traveled:
    print("The natives caught and beheaded you.\nYou're dead!")
    break

# Health checks
# 1 in 20 chance of finding an oasis
if user_choice != "D" and random.randrange(20) == 0:
    camel_fatigue, thirst, canteen = 0, 0, 3
    print("You have found…")
elif thirst > 6:
    print("You died of dehydration!")
    break
elif camel_fatigue > 8:
    print("Your camel is dead.")
    break

# Warnings
if natives_traveled >= miles_traveled - 15:
    print("The natives are drawing near!")
if thirst > 4:
    print("You are thirsty")
if camel_fatigue > 5:
    print("Your camel is getting tired.")


Framed external link redirect - vBulletin

Here's how I optimized your code:

$curdir = getcwd();
chdir('./');
define('NO_REGISTER_GLOBALS', 1);
define('THIS_SCRIPT', 'drc-redirect');
$globaltemplates = array('drc_redirect');
require_once('./global.php');

if (isset($_GET['l'])) {
    //format passed url
    $passed_url = $_GET['l'];
    unset($_GET['l']);
    if(count($_GET))
        $passed_url = $passed_url . '&' . http_build_query($_GET);

    //deals w/ the display if $passed_url is a valid URL
    if (filter_var($passed_url, FILTER_VALIDATE_URL)) {
        $site = parse_url($_SERVER['HTTP_HOST']);
        $site = $site['path'];
        $url = parse_url($passed_url);

        //the passed url is not an external link
        if ($site == $url['host']) {
            Header( "Location: ". $_SERVER['QUERY_STRING'] );
        }
        //the passed url is an external link
        else {
            eval('print_output("' . fetch_template('drc_redirect') . '");');
        }
    }
}

Below are the modifications that I did:

Using isset() for checking $_GET.
Using http_build_query() instead of looping through each element in $_GET.
Using filter_var() to check if the passed URL is valid.

Explanations in detail:

isset() allows for proper checking of the intended variable from $_GET. It also returns a boolean for the if condition, as opposed to just placing $_GET which is an array.
The looping of the $_GET variable will backfire if there are at least 2 elements in it. The else condition on the foreach loop overwrites the previous values for $url2. Now this can be corrected to having every $key/$value be concatenated everytime. We can utilize http_build_query() instead because it can get the job done, and there's no need to loop the $_GET array.
Finally, parse_url() sometimes is not able to return the scheme of a given url string. filter_var() along with the FILTER_VALIDATE_URL filter can validate URLs regardless whether the scheme was specified or not.


Convert string of hex into vector of bytes

Note that this code will not work on any non-ASCII strings. These are more and more common, especially considering the global community we are a part of (and don't forget emoji ).
Use Vec<_> to avoid redundantly specifying the inner type when collecting.
Use byte literals b'x' instead of casting characters to bytes.
You can match on ranges of characters. I find this aesthetically pleasing.
Don't collect an iterator into a Vec just to call into_iter on the Vec. Instead, use the original iterator with partition.
Don't convert from u8 to char and back. You only need to make a single transformation.
There's no need to use the turbofish with the final collect since it's being returned and the type can be inferred.
There's no need to call into_iter for zip's argument, it's implied because it takes an IntoIterator.
Instead of partitioning into vectors, just grab two values out of the iterator at a time. Using fuse allows calling next after it's already returned None.
Your code handles the check of a hex digit twice, leading to the unreachable. Instead, perform the conversion when performing the check.

fn parse_hex(hex_asm: &str) -> Vec<u8> {
    let mut hex_bytes = hex_asm.as_bytes().iter().filter_map(|b| {
        match b {
            b'0'...b'9' => Some(b - b'0'),
            b'a'...b'f' => Some(b - b'a' + 10),
            b'A'...b'F' => Some(b - b'A' + 10),
            _ => None,
        }
    }).fuse();

    let mut bytes = Vec::new();
    while let (Some(h), Some(l)) = (hex_bytes.next(), hex_bytes.next()) {
        bytes.push(h << 4 | l)
    }
    bytes
}


First use ++it instead it++ with iterators.
You can replace this loop:

for (vector<int>::const_iterator itr = vec.begin();
     itr != vec.end() + 1; itr++)`

with range-based for:

for (auto i : v)

vec.end() returns iterator representing element after the last element in vector
if (itr != vec.end()) loop also does this check
I think you can rewrite your code to be clearer and with less ifs
also you can use std::to_string instead of intToString
also if you want to append . at the end of string you can do it outside of the loop

Here is the code with few things fixed; still I think you can do even better than that if you rethink your conditions.

void createLines(vector<int>& vec, string& line)
{
  int start = *vec.begin(), end = -1, offset = 0; // initial offset to start

  for (auto i : vec)
  {
    if (i == start + offset)
    {
      end = i;
      ++offset;
    } // check if line numbers are consecutive and not reading at end of vector
    else // not consecutive
    {
      if ((end != -1) && (end != start))
      {
        line.append(to_string(start) + "-");
        line.append(to_string(end));
      } // if there existed consecutive numbers, display with dash
        // must be difference of at least 1
      else // else, there were no consecutive numbers
        line.append(to_string(start));

    line.append(", ");

  start = i; // set start to next line number. Soft reset.
  offset = 1; // change default offset to 1. 0 for first case.
  end = -1;
} // not consecutive
} // Get all line numbers and format for proper output
 if ((end != -1) && (end != start))
 {
   line.append(to_string(start) + "-");
   line.append(to_string(end));
 }
 else
   line.append(to_string(start));
line.append(".");
} // createLines()


Move the os.environ and sys.path calls into a new setUpClass method instead of have them at the global level?
pass at the end of setUp should be removed, similarly the commented out print.
I'd put the constants for the URL and the headers into fields or methods (self.url() / self.url) to reduce duplication.
The docstrings are a bit much.  Ideally the code would be very self explanatory so that it almost spells out what you currently have (duplicated) in the docstring.
I'd put things that belong together in the same file; so same endpoint and requests definitely in the same file and probably in the same test class as well.  I'd go for practicality first - if you need to have convoluted setup because you want to handle many different tests, then split it into multiple classes such that the tests are again easy to read.


I can improve the performance by 25% or so, by stopping the regular expression after the opening parenthesis, and so avoiding the need for a while loop or indeed a function at all:

get_line_symbols = re.compile(r'(\w+)\(').findall

(Note that it's a good idea to use the r modifier on regular expression strings, to avoid the risk of accidentally writing something like '\b', which needs to be written as r'\b' or '\\b' if it's to mean a word boundary rather than the backspace character.)

I get a further speedup by switching from the built-in re library to the third-party regex library. Using both of these improvements is about three times as fast as the code in the post.


This is a fine implementation.
It's well-formatted and nicely written.
I find the idea of using a LinkedHashSet quite clever and interesting.
There are a couple of points to improve though.

You have a bug

Do you notice something fishy here?

while (foo[i] > bar[j] && j < bar.length) {
    j++;
}
if (foo[i] < bar[j]) {

The condition in the while checks foo[i] > bar[j] before j < bar.length.
So when j reaches bar.length,
this will throw an ArrayIndexOutOfBoundsException.

Flipping the && may seem like an obvious remedy.
But it won't be enough,
because of the next if statement after the while loop,
you'll again have the problem if j has already reached bar.length.

An example input to demonstrate this issue: 33;3,4

Unit testing

It's always handy to have some unit tests around when solving challenges like this.
For example:

@Test
public void test_9_10_11_x_33_34_35() {
    assertEquals("", findIntersection("9,10,11;33,34,35"));
}

@Test
public void test_3_7_8_22_x_11_22() {
    assertEquals("22", findIntersection("3,7,8,22;11,22"));
}

@Test
public void test_11_12_13_14_x_14_15_16() {
    assertEquals("14", findIntersection("11,12,13,14;14,15,16"));
}

@Test
public void test_20_21_22_x_45_46_47() {
    assertEquals("", findIntersection("20,21,22;45,46,47"));
}

@Test
public void test_77_78_79_x_78_79_80_81_82() {
    assertEquals("78,79", findIntersection("77,78,79;78,79,80,81,82"));
}

@Test
public void test_33_35_x_3_18_26_35() {
    assertEquals("35", findIntersection("33,35;3,18,26,35"));
}

@Test
public void test_33_x_3_4() {
    assertEquals("", findIntersection("33;3,4"));
}

An alternative implementation

Consider this alternative implementation that passes all the tests:

private String findIntersection(String input) {
    String[] parts = input.split(";");
    String[] arr1 = parts[0].split(",");
    String[] arr2 = parts[1].split(",");
    return findIntersection(arr1, arr2);
}

private String findIntersection(String[] arr1, String[] arr2) {
    StringBuilder builder = new StringBuilder();
    for (int pos1 = 0, pos2 = 0; pos1 < arr1.length && pos2 < arr2.length; ) {
        int value1 = Integer.parseInt(arr1[pos1]);
        int value2 = Integer.parseInt(arr2[pos2]);

        if (value1 == value2) {
            builder.append(value1).append(",");
            ++pos1;
            ++pos2;
        } else if (value1 < value2) {
            ++pos1;
        } else {
            ++pos2;
        }
    }
    if (builder.length() == 0) {
        return "";
    }
    return builder.substring(0, builder.length() - 1);
}

This implementation has an advantage and disadvantage compared to yours:

Advantages:

It doesn't always convert all input values to integers. For example when you have a long list and a short list, and it turns out that they cannot have an intersection, the rest of the long list will not be converted to integers
It should be faster to generate the output from a StringBuilder than from a LinkedHashSet

Disadvantage: in common cases it converts input values to numbers twice.
This is because in every step of the while loop, when only one of the positions advance, then on the next step the other number will be converted to integer again.

There is possibly one more advantage:
it's not clear if in the output the values should be separated by single commas,
or by comma + space as in yours (and in the output of Set.toString).
Since the values are separated by , in the input,
I would assume the same rule for the output as well,
but I could be wrong.
But if I'm right,
then to get the right output you would have to strip the spaces from the result of the Set.toString call.


Generating Table Sections from A Property in a List of Objects

You asked for a more elegant approach... This is certainly more concise:

var dict = completed
    .GroupBy(
        item => item.DateClosed.ToString("MMMM dd yyyy"), // Key selector
        item => new TradeCell(item)) // Value selector
    .ToDictionary(g => g.Key, g => g.ToList());

However, you don't actually need the dictionary (that's just to keep the same behaviour as the foreach). This should do the job:

foreach (var groupOfCells in completed.GroupBy(item => item.DateClosed.ToString("MMMM dd yyyy"), item => new TradeCell(item)))
{
    _table.Root.Add(new TableSection(groupOfCells.Key) { groupOfCells .ToList() });
}

Remember not to abbreviate names. dict doesn't mean anything to anyone.

I'd also suggest grouping by DateClosed.Date and converting to a string in your UI layer. I don't know if you need it, but it's much harder to localise if you include hard coded format strings all over the place.


I don't think there's anything that can be improved to your approach.

Minor improvements do apply;

function showWeb(e:Event=null){
webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight);
}

could use some indentation,

btn.addEventListener(MouseEvent.CLICK,  showWeb)

contains a double space and is missing a semicolon.

But I don't think it's possible to preload the StageWebView via some function.

What you DO want to take care of is any errors that might be thrown your way.

For that, add a listener: (code from this SO answer)

webView.addEventListener(ErrorEvent.ERROR, onError);
function onError(e:ErrorEvent):void
{
    trace("Page is not available.");
}


Dynamic variable - is that best way to dynamically assign?

I think it is quite defendable to use dynamic here. I'm not too familiar with EF, but it could very well be that you can't make the objects type-compatible.

Even if you could, I would not do it if it was only to make this piece of code work.

Declaring email as object will not help in any way.

The only alternative I can think of is to have two code paths for both cases:

            if ( source.ActionTypeId == (int)ActionTypes.EmailInbound )
            {
                email = source.EmailMessage.EmailInbound;
                return new ActionModel
                {
                    ActionTypeId = (ActionTypes)source.ActionTypeId,
                    Content = email.Body,
                    Created = email.DateSent,
                    GravatarUrl = HtmlHelperExtensions.getGravatarUrl(email.FromAddress, 25),
                    Subject = email.Subject,
                    User = Mapper.Map<User, UserModel>(source.EmailMessage.User),
                    EmailReplyTo = email.From,
                    ShowReplyButton = true,
                    ThreadUid = source.ThreadUid,
                    IsReply = source.IsReply
                };
            }
            else
            {
                email = source.EmailMessage.EmailOutbound;
                return new ActionModel
                {
                    ActionTypeId = (ActionTypes)source.ActionTypeId,
                    Content = email.Body,
                    Created = email.DateSent,
                    GravatarUrl = HtmlHelperExtensions.getGravatarUrl(email.FromAddress, 25),
                    Subject = email.Subject,
                    User = Mapper.Map<User, UserModel>(source.EmailMessage.User),
                    EmailReplyTo = email.From,
                    ShowReplyButton = true,
                    ThreadUid = source.ThreadUid,
                    IsReply = source.IsReply
                };
            }

But I think the solution with dynamic is better. You can't catch all errors at compile time. I would reccomend a unit test (two really) so that if anybody changes the database schema, this is detected at build time.


Efficiency with strcpy, strcat and malloc

Fairly good C. Few notes:

sizeof(char) is by 1 definition. It doesn't hurt to multiply by it, but still totally unnecessary.
malloc return value better be tested against NULL.
Calling functions of strn (emphasis on n) family in this context is kinda paranoid: you've already allocated enough memory; no need for extra safety. In fact, I'd rather go for sprintf("%s%s%s", querystring, query1, username, query2).
int comparison is just noise. It's OK to directly test results of strcmp(). BTW, strncmp in this context looks paranoid again.
I am not familiar with mysql. Shouldn't you release row somehow?


This is really an algorithms question. For example, consider this loop:

for(ii=0;ii<desval;ii++)/*Evaluate the probability total cutoffs*/
{
    ptot[ii]=array_sum(p,ii);
}

why are you calling array_sum() every time through this loop when the only thing that changes is the addition of one more element?
Why can't this loop be:

sum= 0;
ptot[0]= 0;
for(ii=1;ii<desval;ii++)/*Evaluate the probability total cutoffs*/
{
    ptot[ii]=(sum+= p[ii - 1]);
}


If you want to make the compiler spit out errors when the exceptions aren't caught, make your classes that derive from Exception, but not RuntimeException. Note that unless you have control over the source from whence they came, since you can't change the definition of classes, you have to create your own custom ones.

You've got a bunch of random newlines that just make your code look ugly. I'd suggest removing all of them in the code you've posted.

Rather than having separate catch blocks for each, you can put them all into
one. The general form is this:

catch (ExceptionTypeA | ExceptionTypeB name) { /* ... */ }

Also, the standard in Java is to put the opening brace on the same line as the statement it belongs to, so

catch (UncategorizedSQLException e)
{
    return new ErrorMessage(errorInvalidQuery).toJson();
}

should really be

catch (UncategorizedSQLException e) {
    return new ErrorMessage(errorInvalidQuery).toJson();
}

        } catch (DataAccessException e) {

            if (e instanceof UncategorizedSQLException)
                {
                //Invalid cypher query
                throw (UncategorizedSQLException)e;
                }

            else throw e;
        }

Ignoring the wacky indentation and unconventional brackets, there are two tips I wanna give:

catch statements are done in order, using (what's basically) an instanceof check that stops after the first match. This means that if you put a superclass before a subclass, that subclass will never get hit -- so just put the subclass first:

catch (UncatergorizedSQLException e) {
    throw e;
}
catch (DataAccessException e) {
     throw e;
}

Of course, you can sidestep that whole issue by getting rid of the try and declaring that your method throws those two exceptions -- since you're doing nothing but rethrowing, it's simpler and easier. Basically, since you've already declared that you're throwing, just remove the try and its associated catches.

Follow that, and your first method (with formatting) becomes just this:

public String runQuery(String q) throws JsonGenerationException, JsonMappingException,
                                        UncategorizedSQLException, DataAccessException {
    Graph g = jdbcTemplate.query(q, new Neo4jGraphResultSetExtractor());
    json = g.toJson(); //throws JsonGenerationException, JsonMappingException
    return json;
}

And your second becomes (changing the whitespace to follow the majority of the catches):

public String submitCypherQuery(String query) {
    try {
        return neoConn.runQuery(query);
    } catch (UncategorizedSQLException e) {
        return new ErrorMessage(errorInvalidQuery).toJson();
    } catch (DataAccessException | ClassNotFoundException | JsonGenerationException |
             IOException | JsonMappingException e) {
        return handleUnexpectedError(e);
    }
}


Split string in half and change case accordingly

Midpoint math is often a pain in the whatnot, but a real trick is to add 1 to the length before halving it. Additionally, instead of repeating the math multiple times, you can do it just once.

def sillycase(silly):
    mid=(len(silly) + 1) / 2
    firstHalf = silly[:mid].lower()
    secondHalf = silly[mid:].upper()
    return firstHalf + secondHalf

At that point, it becomes small enough to not need the temp variables:

def sillycase(silly):
    mid = (len(silly) + 1) // 2
    return silly[:mid].lower() + silly[mid:].upper()

print (sillycase("hello"))
print (sillycase("helloa"))
print (sillycase("helloab"))

http://ideone.com/CqUdl5

Note the use of the integer divide which is suitable for both python 2.x and 3.


Globals

The problem is with your global variables.

You have way too many global variables and this is a problem because a global variable may, by definition, be modified from anywhere in your program.

This means that the reader of your program has to keep in mind all the values of all the variables at the same time.

Now for a small script like this this is no big deal, but imagine having not 5 global variables but 50 of them. Now you understand how hard it can become to follow un-organized code.

I suggest that each function should take the variables that it operates on as arguments and, if it modifies them, then it should return the new values back.

For example the function that prints out the final recipe can easily be adjusted to take as arguments the three arrays.

Premature optimization

I see that you keep a variable that indicates how long the input list is; that is premature optimization because you may just recalculate the length just before looping.

In fact in a user interface driven program you should not worry at all about performance because computers are very very fast nowadays.

To be complete there is an even more efficient way of looping, that is using the zip built in but that is a more advanced topic.

pricing

I also had a look at your pricing function.

I think the whole try except block should be extracted into its own function as getting an input that must be a number from the user is a pretty common task.

This will allow you to reuse that particular piece of code.


I don't really like having using switch code!, it seems clumsy like
  I'm missing something in unwrapping.

Yes, that will crash if the function is called with an error code
that does not correspond to one of the HMErrorCode enumeration values.
Better use optional binding with if let ...:

class func handleError(error: NSError) -> Bool
{
    if let code = HMErrorCode(rawValue: error.code) {
        switch code {
        case HMErrorCode.FireDateInPast:
            showAlertWithTitle("Invalid date", body: "Date must be in the future")
        case HMErrorCode.AccessDenied:
            showAlertWithTitle("Access Denied", body: "You don't have permission to access the specified item")
        // Other cases ...
        default:
            NSLog("Couldn't handle error with code \(error.code)")
            showAlertWithTitle("Error", body: "Couldn't successfully complete action")
            return false
        }
    } else {
        NSLog("Unknown error with code \(error.code)")
        showAlertWithTitle("Error", body: "Unknown error \(error.code)")
        return false
    }
    return true
}

It is also not obvious from your code why the function has a (boolean) return
value, as the caller ignores it.


Quite a few things sprang to mind immediately, but as I delved deeper I realized that, well, there are a lot of issues. So here goes.

Outright bugs, I think

User.apikeys - what? Shouldn't that be @user.api_keys? But I notice you don't test the index action, which would have caught that.

Security Issues

You're not really using params filtering correctly. You're permitting (rather than requiring) some top-level params, but never actually filter the "sub-params". The point is usually to filter the nested params, e.g. params.require(:api_key).permit(:foo, :bar).
But judging by your tests, it seems that creating an API key doesn't need any params at all, which makes things simpler.

Secondly, create new API key records through the has_many association on User (which I assume you have); don't set the user_id directly. I.e. @user.api_keys.new(...). But read on first.

If the idea is that a user can only create API keys for himself/herself (which the tests seem to indicate), then don't find the user by params[:user_id]. Right now, it's very easy to craft a request with a different user_id param, and destroy API keys that belong to other users in the system.

So if you only want the current user to create keys for himself/herself, the route doesn't need to be nested at all, since you only ever need the currently logged in user. I'm assuming you're using Devise, so the current user is accessible via the aptly named current_user helper method. (You can also dispense with the nested routing, if you only want the current user).

Even so, any user would still be able to delete other people's keys, because you don't check whether a given id param actually belongs to the current user (or the @user for that matter). Basically, if someone's logged in, they can just call the destroy action with completely arbitrary numbers and destroy everything.

Heck, you can do that from the JS console in a browser. Try typing $.ajax({url: "/users/x/developmentcenter/y", type: "DELETE"}) where x is your own user ID (which you can see in a URL somewhere) and y is any number between 1 and whatever the maximum for your database's ID column is. If y happens to a key id - any key - it'll get destroyed.

The mixins could also be a source of security issues. See the section below about that.

Consistency and Naming

In your index action you have @api_key = User.apikeys.
Why is one singular, and the other one plural? @api_key should be called @api_keys (since it's a collection), and the has_many relation on User should be api_keys with an underscore (since that's how you write it everywhere else). Again, I'm thinking that last part is a straight-up bug.

Your create_new_api_key doesn't do what it says; it doesn't create anything. Call it api_key_params instead, since that's what it returns. Besides, it's pretty confusing to have two methods called create_new_api_key and create_api_key... which one do you think actually creates an API key? But again, judging by your tests, you don't need create_new_api_key at all, since no params filtering should be needed.

Pointless Mixins

I understand that you don't like long methods, but making a mixin module is excessive. Do you intend to create/destroy API keys (and redirect) in other controllers? I'm guessing that the answer is "no" (if it's "yes", you've got other problems). So your mixins can only be mixed into 1 specific class, which completely negates the point of having "mixins".
The only thing you're "gaining" is that you've split your code into two files. Now you've got two places to look whenever you have to work with the code. Personally, I had to look back and forth quite a few times to figure stuff out. Since this is supposed to be a very straight-forward controller, that's not a good sign.

Besides, responsibility is all over the map now. In create_api_key you pass in both the user and the new API key instance. So there, your controller code handles params, and object instantiation. But in destroy_api_key you only pass only the user, and let the mixin method mess around with params to find the API key to destroy.

Optimally, a mixin has zero dependencies on its use context (your code depends on at least params, redirect_to which are only relevant for controllers), and is of general use (your code simply isn't). What you're doing is moving some lines of code and making things worse.

I can't actually see where you include the module... if you're doing it in ApplicationController you're polluting every controller with completely irrelevant methods.

And all those methods become public methods on every controller they're included in, meaning they function as actions. So worst case scenario, if you've got a too-liberal routing scheme, all of those methods can be called as actions simply by putting their names in the URL.

Odds and Ends

Don't pass the id attribute to path/url helpers; pass the record itself. If you ever want to override to_param in your models to make nicer URLs, it won't have any effect if all your code explicitly passes only the id attribute. I.e. redirect_to user_path(user.id) → redirect_to user_path(user)

Furthermore, for link_to and redirect_to you don't even need to use a path/url helper if it's a resourceful route; you can just pass the record. Rails will figure the rest out. I.e.
So redirect_to user_path(user) → redirect_to user

If you've only got index, create and destroy actions, then make that explicit in the routes. And there's no need for a slash in the path argument.
resources :api_keys, only: [:index, :create, :destroy], path: 'developmentcenter'

Your last test is missing an expectation. It just calls some stuff, but doesn't actually test anything. I'd suggest at least an expect {...}.to change(ApiKeys, :count).by(-1).

More tests in general - for instance, tests of all the security stuff mentioned above.

Proof-read your flash messages (and test 'em while you're at it).

Here's how I'd write it. I'm assuming you only want users to create/delete their own keys and no params are required to do so

class ApiKeysController < ApplicationController
  before_action :authenticate_user!

  def index; end # just access current_user.api_keys directly in the view

  def create
    api_key = current_user.api_keys.new
    if api_key.save
      redirect_to current_user, notice: 'Created a new API key'
    else
      redirect_to current_user, alert: 'Could not create a new API key. Please try again'
    end
  end

  def destroy
    api_key = current_user.api_keys.find params[:id]
    api_key.destroy
    redirect_to current_user, notice: 'API key has been deleted.'
  end
end

No mixins, yet shorter than the original, and a lot more secure


As requested by Ryan Gates I should post my results. I don't remember the entire scope of what i did, but I do know where the code is :)

So the basics are that I want the thread to be able to exit without causing any strange hicups if the user decides to use my library incorrectly. So I made the thread turn into a background thread. I was able to remove the ugly switch statement and just check the appropriate bits are set to make sure I can start my thread (basically only allows one thread to read a smart card instead of multiple reading the same card)

On Disable what I did was set my flag to kill the loop in my readerThread thread. I then wait for it to exit by using the thread.Join Clear as mud??? I can try to clear up more if anyone has questions.

public override bool Open()
{
    //Code to setup SmartCard

    readerThread = new Thread(CardStatusChange);
    readerThread.IsBackground = true;

    return true;
}
public override bool Enable()
{
    run = true;
    //thread start checking for card events
    Globals.tracer.TraceInformation("Checking Thread State:{0}", readerThread.ThreadState);
    var startable = (readerThread.ThreadState & ThreadState.Unstarted);
    if (startable > 0)
        readerThread.Start();

    return true;
}
public override void Disable()
{
    run = false;
    if(readerThread.ThreadState == ThreadState.Unstarted)
        readerThread.Join();
}


Student information demo in Swing using MVC

First of all MVC is not a "real" design pattern as it lacks atomicity. It's something that adresses some points of the SOLID-principles, especially the single responsibility principle. Furthermore you may use design patterns to realize MVC. If you follow the SOLID-principles carefully you will certainly come up with this 3-class struture in your usecase anyway.

Secondly you apply the MVC correctly. It's good to have a starting point that is more concrete to most of the developers as the SOLID-principles. These developers will produce better code if they use this "best practise" as I would call it. This "best practise" provides a good balance between productivity and code quality even though there are many more improvements possible.

One example:
Currently two classes are technology dependent: Student_View and Student_Controller. Both know Swing as the UI technology. It's better to have less classes depending on technology. A naive way is to melt controller and ui to have only one class. But that violates the single responsibility principle (S in SOLID) as the class wil get MORE responsibilities as it has before. We would take a step backwards if we do so. So the task should be to preserve responsibilities AND decrease technology dependencies.

How to do that:

Use the listener pattern! Let the UI implement the Listener-Interface and register it in the controller so the controller does only know "Listeners". The principle applied here is "dependency inversion" (D in SOLID).

What I want to say is: Yes, you did apply MVC correctly. But is this the core? No. Is it the end? No. It's something you will come up with as a intermediate result if you use the real design patterns mentioned in this book (Design Patterns: Elements of reusable Object-Oriented software) AND apply the SOLID principles and the law of demeter correctly.

Some points to your code in detail:

You have public/package scope variables that should be private scope
You tear apart the Button construction as it should contain the ActionListener declaration as well
Use lazy getter instantiation for your UI elements and use these getter only

So you have some issues in encapsulation, locality and dependency.

I provide you an advanced version that meets these requirements.

public class MVC_Design_Demo extends JFrame {

    public MVC_Design_Demo() {

        add(new Student_View());

        setPreferredSize(new Dimension(500, 500));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
        getContentPane().setBackground(Color.black);

    }

    public static void main(String[] args) {
        MVC_Design_Demo mvc = new MVC_Design_Demo();
        mvc.setVisible(true);
        mvc.pack();
    }

}

public class Student_Controller {

    private Student_Model newStudent;

    private Set<StudentListener> listeners;

    public Student_Controller() {
        this.newStudent = retrieveStudentInfo();
        this.listeners = new HashSet<>();
    }

    public static Student_Model retrieveStudentInfo() {

        Student_Model sm = new Student_Model();

        sm.setFirstName("John");
        sm.setLastName("Smith");

        return sm;
    }

    public void addListener(StudentListener listener) {
        this.listeners.add(listener);
        listener.registeredAsListener(this.newStudent);
    }

    public void setFirstName(String fName) {
        this.newStudent.setFirstName(fName);
        notifyOnFirstNameChanged();
    }

    private void notifyOnFirstNameChanged() {
        for (StudentListener listener : listeners) {
            listener.onFirstNameChanged(this.newStudent.getFirstName());
        }
    }

}

public class Student_Model {

    private String fname, lname;

    public String getFirstName() {
        return this.fname;
    }

    public String getLastName() {
        return this.lname;
    }

    public void setFirstName(String newFname) {
        // Some business logic
        if (newFname.equals("Bill")) {
            this.fname = newFname + "y";
        } else {
            this.fname = newFname;
        }
    }

    public void setLastName(String newLname) {
        this.lname = newLname;
    }
}

public class Student_View extends Panel implements StudentListener {

    private JTextField student_fname, student_lname;
    private JLabel stu_fname_label, stu_lname_label;
    private JButton changeName;

    private Student_Controller controller;

    public Student_View(){

        setPreferredSize(new Dimension(200,200));
        setBackground(Color.red);
        add(getLabelStuFName());
        add(getTextFieldStudentFName());
        add(getLabelLName());
        add(getTextFieldStudentLName());
        add(getButtonChangeName());

        setVisible(true);

        this.controller = new Student_Controller();
        this.controller.addListener(this);

    }

    private JButton getButtonChangeName() {
        if (changeName == null) {
            changeName = new JButton("Change student data");
            changeName.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    controller.setFirstName("Bill");
                }

            });
        }
        return changeName;
    }

    private JLabel getLabelLName() {
        if (stu_lname_label == null) {
            stu_lname_label = new JLabel("Last Name: ");
        }
        return stu_lname_label;
    }

    private JLabel getLabelStuFName() {
        if (stu_fname_label == null) {
            stu_fname_label = new JLabel("First Name: ");
        }
        return stu_fname_label;
    }

    private JTextField getTextFieldStudentLName() {
        if (student_lname == null) {
            student_lname = new JTextField(20);
        }
        return student_lname;
    }

    private JTextField getTextFieldStudentFName() {
        if (student_fname == null) {
            student_fname = new JTextField(20);
        }
        return student_fname;
    }

    @Override
    public void registeredAsListener(Student_Model newStudent) {
        this.getTextFieldStudentFName().setText(newStudent.getFirstName());
        this.getTextFieldStudentLName().setText(newStudent.getLastName());
    }

    @Override
    public void onFirstNameChanged(String firstName) {
        this.getTextFieldStudentFName().setText(firstName);
    }

}

public interface StudentListener {

    void registeredAsListener(Student_Model newStudent);

    void onFirstNameChanged(String firstName);

}

Some annotations:

In the model there is now a little business logic to illustrate that you may get an adapted result to present to the ui. ("Bill" will be converted to "Billy")

All former public or package scope variables are private now so you can ensure they will not be manipulated accidentially.

Lazy initialization is introduced for all ui components. The single responsibility principle was applied here. Furthermore, lazy initialization makes the code more flexible as you remove the neccessity to care about the instantiation order/timepoint.

The creation of the ActionListener is now part of the button creation. It was removed from the controller. Previously it was neccessary to have the Button public to access the "addActionListener"-method. The Button is private now. Furthermore you established a "long" dependency to the method "addActionListener". The "law of demeter" was applied, I shortend the dependency. This was the first step to make the controller independent from Swing.

The introduction of the listener pattern is the second step to make the controller independent from Swing. (dependency inversion)

The model informs the listener once when the listener is registered. So the listener can initialize itself.

The model notifies all listeners if the first name changes.

The model is created within the UI class. Now you have some less classes knowing the model. (less dependencies)


I don't see any reason why you have to pass the two customers to you transfer method. But first, there are some main remarks :

Do you want to do a transfer from Customer or Account ? Usually I transfer from different accounts not customers. So let's assume that what you want is a method to transfer a given amount of money from one account to another.
You cannot assume that you will have a console when transferring. How can someone reuse this code for a web app ? Please, use a parameter to receive the amount to transfer. And in the meantime, don't ask for the recipient's routing number, because it will be into the recipient account.

So you will have a method like Account.transfer(double amount, Account recipient)

@Test
public void transfer_must_move_amount() {
    Account michael = new Account();
    Account max = new Account();

    michael.transfer(15, max);

    assertThat(max.getBalance()).isEqualTo(15);
}

Your code just have to be refactored a little :

public void transfer(double amount, Account recipient) {
        double transferAmount = amount;
        int routingNumber = recipient.ROUTING_NUMBER;
            if (routingNumber == ROUTING_NUMBER) {
                System.out.println("Your funds will transfer instantly, you and your recipient share the same bank!");
                System.out.println("Bank name: " + bankName);
            } else {
                System.out.println("Your funds will transfer in 2-3 business days.");
            }
        this.balance -= transferAmount;
        recipient.balance += transferAmount;
    }

This test will fail with Expected: 15.0, Actual: 0.0. This is because you balance is static and static members belong to the class instead of one Account. Remove it and everything will be okay.

But there is much more than can be improved on your code.

Protect the Account#balance property form the outside; make it private and initialize it to 0 to be sure.

By doing that your Customer will be red because acc.balance is not avlid anymore. This a good thing because by copying the value, if you change the balance in your Account the customer one will not change anymore. Remove it and replace it by a getBalance() method that will return the balance from your Account.

Since you have one addAccount method, I suppose that a customer may have many accounts, so replace the Account acc field with a collection of Account. The getBalance will returns the sum of all accounts.

Back to the Account where your two deposit and withdraw methods are unused. You may use them via your transfer method. This may safe you later if some Account have some fees on those operations. You just have to override those methods and the transfer method will not be touched.

The only things that we have not touched is the ROUTING_NUMBER. Usually this information is part of your account number. So it may be the good time to add a AccountNumber class. This one is a value object that enforce some rules and can be used to verify if two accounts are in the same bank.

--
I have ignored the nextId and bankName from this review because they are out of your "transfer" scope.

https://github.com/gervaisb/stackexchange-codereview/tree/q183675


Remapping and interpolating 255x1024 array

p2p(m + 1) does not depend on n. You may safely extract its calculation from the inner loop:

for m in range(0,255):
    p2p_value = p2p(m + 1)
    for n in range(0,1024):
        X[m,n] = X[m,n] - p2p_value

If you call smile() multiple times, it is worthwhile to precompute p2p once.

Some further savings can be achieved by accounting for the sequentiality of p2p arguments. Notice that p2p(m+1) - p2p(m) is a polynomial of lesser degree; you may
calculate it incrementally:

    p2p_value += p2p_delta(m)

Edit:

Some math:

Let \$P(x) = ax^3 + bx^2 + cx + d\$. You may see that \$P(x+1) - P(x) = 3ax^2 + 3ax + a + 2bx + b + c = 3ax^2 + (3a + 2b)x +(a+b+c)\$ is a second degree polynomial, a bit easier to calculate than the original third degree one. Which leads to the code (fill up the list of coefficients according to the above formula):

    p2p_delta = np.poly1d([...])
    p2p_value = p2p_delta(0)
    for m in range(0, 255)
        for n in range(0, 1024)
            X[m,n] -= p2p_value
        p2p_value += p2p_delta(m)


At a glance, the code looks reasonably good.

Either initialize everything in the constructor:

protected possibleResults gameResult;
private static SecureRandom randomNumbers;

public Craps() {
    this.gameResult = possibleResults.UNDEFINED;
    this.randomNumbers = new SecureRandom();
}

… or get rid of the constructor completely (it is implicit):

protected possibleResults gameResult = possibleResults.UNDEFINED;
private static SecureRandom randomNumbers = new SecureRandom();

There is a curious mix of private and protected members.  Why?  I suggest making them all private unless you see a need to expose them.

The gameResult member should be made private; other classes should have to call a public method getResult() to retrieve it.  That prevents other code from setting the gameResult.

As an enum, possibleResults should follow the naming conventions for classes (beginning with a capital letter).  I suggest shortening the name to

public static enum Outcome { UNDEFINED, WIN, LOSE };

Putting it as the first thing in the Craps class would be good, so as to avoid interrupting the class definition with an enum definition.


*ahem* Data.Map is an overkill for this program. It needs the containers package. Also, if a number is divisible by \$k\$ of your \$K\$ divisors, your algorithm is \$\mathcal O(K + k \log K)\$ (*), so worst case (\$K = k \$) you will have \$\mathcal O(K \log K) \$.

This is due to the definition of factors. Compare your factors with the following variant:

factors' :: Int -> [(Int, String)]
factors' x = filter (\(y,_) -> x `mod` y == 0) factorPairs
  where factorPairs = M.toAscList factorWords

It's almost the same, and has the same algorithmic complexity as your previous factors, namely \$\mathcal O(K)\$. But this time, you're getting more information from a single function: you can define both factors and fizzbuzz in terms of factors', without using the original map/list anymore:

factors :: Int -> [Int]
factors = map fst . factors'

fizzbuzz :: Int -> String
fizzbuzz x = case concatMap snd (factors' x) of
               [] -> show x
               xs -> xs
-- feel free to use your "where style" here instead

As you can see, a list of pairs is enough to capture everything, since you're going to traverse all of them either way. It also leads to a complexity of \$\mathcal O(K)\$ (*). If you're concerned about the order of elements, a single Data.List.sort at the original definition can help.

However, even this might be an overkill if you never intend to increase the number of factors. If all you want to do is to solve fizzbuzz, you can drop down to a guard solution:

fizzbuzz :: Int -> String
fizzbuzz x
  | isDivisibleBy 15 = "FizzBuzz"
  | isDivisibleBy  5 =     "Buzz"
  | isDivisibleBy  3 =     "Fizz"
  | otherwise        =     show x
 where isDivisibleBy n = x `rem` n == 0

Which beats all other discussed solutions in terms of complexity and clarity.

(*) Only counting filter and lookup, not actual concatenation.


Maximum Subarray Problem - Iterative O(n) algorithm

Subarray representation

Name of low and high: I prefer lower and upper because they contain the same number of characters, so that code lines up nicely. ☺
Inclusive-inclusive intervals: Your low and high variables form an inclusive-inclusive interval.  Usually, you would be better off with an inclusive-exclusive interval, especially in a language with zero-based arrays.  Consider examples

std::vector::end in C++
String.substring(beginIndex, endIndex) in Java
range(start, stop) in Python

The generic benefit of having high being one greater than the last element is that high - low is the number of elements.  This is nicer — you don't have to hard-code 16 or 15 anywhere:

int array[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
int lower = 0, upper = sizeof(array) / sizeof(array[0]);

A specific benefit for this problem is that any interval with lower == upper represents an empty interval.  You don't have to use -1 for that.
Type of low and high: Array indices should be size_t rather than int.  Especially since your array consists of ints, there could be confusion as to whether int *lower should be a pointer to the first data element (i.e., &array[0]) or a pointer to the index of the first element.  Not having to support -1 lets you use size_t instead, which clarifies your intentions.
Clusters of variables: Variables blah_sum, blah_low, and blah_high are always initialized and updated together.  There should be a struct representing subarrays, with operations "init" and "extend".

typedef struct {
    int sum;
    size_t lower;
    size_t upper;
} subarray;

static void init_subarray(subarray *sa, size_t i) {
    sa->sum = 0;
    sa->lower = sa->upper = i;
}

static void extend_subarray(subarray *sa, size_t i, int increase) {
    sa->sum += increase;
    sa->upper = i + 1;
}

Nitpicks

Const-correctness: max_subarray() should take a const int array[].
Brace style: Pick a brace style and stick with it.

Algorithm

Your code is wrong.  For an input array { -1, 5 }, it prints 4 instead of 5 as the maximum sum.

As @cat_baxter points out, Kadane's algorithm is simpler.

/**
 * Finds the earliest consecutive block of array elements with the maximum sum.
 *
 * Parameters:
 * lower  IN: a pointer to an integer that is the array index of the first
 *            element to consider (normally 0).
 *       OUT: a pointer to an integer that is the array index of the first
 *            element of the maximum subarray.
 *
 * upper  IN: a pointer to an integer that is one greater than the array index
 *            of the last element to consider (normally sizeof(array) /
 *            sizeof(int)).
 *       OUT: a pointer to an integer that is one greater than the array index
 *            of the last element of the maximum subarray.
 *
 * Returns: the sum of the maximum subarray
 */
int max_subarray(const int array[], size_t *lower, size_t *upper) {
    subarray max, tmp;
    init_subarray(&max, *lower);
    init_subarray(&tmp, *lower);

    for (int i = *lower; i < *upper; i++) {
        if (tmp.sum < 0) {
            init_subarray(&tmp, i);
        }
        extend_subarray(&tmp, i, array[i]);

        if (tmp.sum > max.sum) {
            max = tmp;
        }
    }
    *lower = max.lower;
    *upper = max.upper;
    return max.sum;
}

int main() {
    //The maximum subarray-sum is 43 for the following
    int array[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
    size_t lower = 0, upper = sizeof(array) / sizeof(array[0]);

    printf("%d\n", max_subarray(array, &lower, &upper));
    printf("%zu %zu\n", lower, upper);

    return 0;
}


Take a look at
Object Relational Mapping,
especially
Object-relational impedance mismatch
on Wikipedia.

Basically there problems with this as soon as it gets a bit more
complicated and you need to query e.g. a lot of objects at once, or you
have joins, and so on.

Let's take $this->getRowFromPlayers.  I'm assuming, that that method
will fetch one row from the database.  So you already have a
bottleneck here because you'll have to run n separate queries for
each of your n IDs when you want to get like a list of objects by
their IDs, which is very inefficient.  So you'll have to construct
objects from the outside, mapping a result of multiple rows from the
database to newly constructed (or cached) objects.

Another problem often comes up in that your objects don't exactly are
the table rows, they are just mapped onto objects, so testing by
identity is mostly meaningless unless you keep track of objects and
return the same object for the same row of a table.  It gets complicated
very fast.

Obviously there are already solutions for this, so I suggest you take a
look at existing PHP libraries for this.


Rotate the sub-list of a linked list from position M to N to the right by K places

I see a number of things that may help you improve your program.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.

Make sure the comments don't mislead

The code currently includes this comment and function:

// inserting at the beggining
void push( Node **head, int data ) {

However, that comment is false (and spelled incorrectly).  In fact, the data is appended to the end of the linked list.  For that reason, I'd suggest changing the name to append.

Use nullptr rather than NULL

Modern C++ uses nullptr rather than NULL.  See this answer for why and how it's useful.

Return something useful from functions

It is not very useful to have every function return void.  Instead, I'd suggest that push (now renamed to append per previous suggestion) could return a pointer to the head of the list.  Here's one way to write that:

// append data to end of linked list
Node* append(Node *head, int data) {
    auto newNode = new Node{data, nullptr};
    if (head == nullptr) {
        return newNode;
    }
    auto temp{head};
    while (temp->next) {
         temp = temp->next;
    }
    temp->next = newNode;
    return head;
}

Don't leak memory

This code calls new but never delete.  This means that the routines are leaking memory. It would be much better to get into the habit of using delete for each call to new and then assuring that you don't leak memory.

Use objects

The Node object is a decent start, but I'd recommend and actual linked list object to better take care of memory management and node initialization.

Sanitize user input

If the user enters a negative number or a number that's larger than the array, or numbers that are not in the right order, bad things happen in the current program.  In general, it's better to be very wary of user input and test for and handle any bad input.

Fix the bug

If the subsequence includes the first node, the output is incorrect.  That's a bug.

Rethink the problem

There are two essential parts to the algorithm.  First, we identify the subsequence and then we do the rotation.  With some thought, you can figure out either 0 or 3 next links will need to be changed.  We can immediately understand that if \$n - m + 1 = k \mod (n-m+1)\$ then no links need to change and we're done.  Otherwise 3 links need to change.  Let's number each of the nodes, starting from 1.  So the first node is \$N[1]\$, and the second is \$N[2]\$, etc.

Now the first node that needs to be altered is \$N[m-1]\$.  It needs to point to \$N[m + k]\$.
Next \$N[n]\$ (the last node of the subset) points to \$N[m]\$ (the first of the subset).
Then \$N[m + k - 1]\$ must point to \$N[n+1]\$

With that in mind, it should be apparent that only a single pass through the data structure is needed with only two temporary pointers.  I'll leave it to you to write the code for that.


Pass Cassandra session reference to http handlers

Yes, there definitely is a better way to do this. The easiest way would be to use reciever functions (aka methods) as handler functions. Rather than returning a handler from the ItemHandler func (bad name BTW), simple declare a handler directly.

Here's an example of how you could acchieve this:

type MyServer struct {
    cql *gocql.Session
}

func (s *MyServer) ItemHandler(w http.ResponseWriter, r *http.Request) {
    // use s.cql here
}

func New(cql *gocql.Session) (*MyServer, error) {
    s := &MyServer{
        cql: cql,
    }
    // more stuff here
    return s, nil
}

Then, in your main package, simply write this:

s, err := cassandra.InitCassandraClient()
if err != nil {
    fmt.Println("Unable to set up Cassandra client!")
    os.Exit(1)
}
// assume package name server
srv, _ := server.New(&s)
// now ItemHandler with srv as receiver is the handler
router.HandleFunc("/item", srv.ItemHandler)


gc is the name of the Garbage Collection interface module. It shouldn't matter too much, but, when reading your code, it feels like that you are asking the garbage collector to find books and then I remind myself that it isn't actually the garbage collector.

index = random.randint(1, 1000000)

This was mentioned in the last post. Even if you can't find the specific number you need, you should at least assign 1000000 to some variable something like MAX_BOOK_NO so the meaning of such a number is more obvious.

    i = 0
    for book in book_req:
    ...
        i += 1

This is simplified with enumerate:

    for i, book in enumerate(book_req):
    ...


As for the overall structure of the code, I would try to avoid the if-elif-else chains. Instead you can use either a dictionary with a keys "0", "1", etc. and with functions such as exit_menu, add_points etc. or a list that stores just stores exit_menu add_points etc. in the order and in a particular order.

To go even beyond this, you could add a function attribute to exit_menu, add_points, etc. called display_name and generate the start menu by iterating through the list and loading each display_name.

Here is an (incomplete) example of what it should look like:

def create_profile():
    print("Creating Character Profile... ")

option_dispatch = [create_profile]

while menu_option != 0:
    menu_option = int(input("Please select an option: "))
    option_dispatch[menu_option]()


Iterator and Generator versions of Python's range()

First of all, to validate that the function is working,
it's good to use assert statements:

assert [0, 1, 2, 3, 4] == [x for x in irange(5)]
assert [2, 3, 4] == [x for x in irange(2, 5)]
assert [2, 1, 0, -1, -2] == [x for x in irange(2, -3, -1)]

With these statements covering my back,
I refactored your irange method to this:

def irange(*args):
    len_args = len(args)

    if len_args > 3:
        raise TypeError('irange() expected at most 3 arguments, got %s' % len_args)

    if len_args < 1:
        raise TypeError('irange() expected at least 1 arguments, got %s' % len_args)

    sanitized_args = [int(x) for x in args]

    if len_args == 1:
        start_element = 0
        end_element = sanitized_args[0]
        step = 1
    else:
        start_element = sanitized_args[0]
        end_element = sanitized_args[1]
        step = 1 if len_args == 2 else sanitized_args[2]

    current = start_element

    if step > 0:
        def should_continue():
            return current < end_element
    else:
        def should_continue():
            return current > end_element

    while should_continue():
        yield current
        current += step

Points of improvement:

Since len(args) is used repeatedly, I cache it in len_args
Added len(args) < 1 check too, in the same fashion as len(args) > 3
Simplified the type checking of args:

Sanitize with a single, simple list comprehension
If there are any non-integer arguments, a ValueError will be raised with a reasonably understandable error message

Simplified the initialization of start_element, end_element and step
Greatly simplified the stepping logic

As for the iterator version,
it would be easiest and best to implement that in terms of the generator version.


Python : adding a columns with count of missing values by row

The difference between the two code snippets is that the first creates a new DataFrame while the second modifies the original DataFrame in-place.
The first snippet can be simplified to
X_ = dfObj.assign(nan_count=dfObj.isna().mean(axis=1).astype('float32'))


Python client to fetch JSON data from REST API, retrying on failure

EDIT: Answer updated to use a while-loop rather than recursion, as noted in the comments. I also recently learned about the max recursion depth in Python being a good argument against recursion in the first place.

One way you could solve this is by separating the error handling logic into its own function, and then repeatedly calling a connection function:

# Handles an error in the given response. Returns True if we should try connecting again
def handle_error(response):
    if response["errors"][0]["type"] == 'INVALID_SESSION_ID':
        print("Session expired, initiating new session.")
        authorization = get_authorization(username, password)
        return True
    return False

def connect():
    attempt_connection = True
    while attempt_connection:
        response = get_data(authorization)
        if response["responseStatus"] == "SUCCESS":
            attempt_connection = False
            process_data()
        elif response["responseStatus"] == "FAILURE":
            attempt_connection = handle_error(response)
            if not attempt_connection:
                print(response["errors"])

handle_error could, of course, be split up into more functions, one for each potential error. Depending on the response format, you may also want to check for each key in response before accessing it.

You could also specify retry as a number of times to reconnect before giving up, i.e if you were attempting to connect over multiple proxies. Then you would just decrement the counter after each failure, and print the error when the counter hits zero.


Armed with the article and information provided by @StriplingWarrior, I conducted an experiment and am posting it as an answer to my own question. Please feel free to comment if I have erred in my conclusions.

Assumptions

SQL Server can avoid compilations of previously executed queries by using four mechanisms to make plan caching accessible in a wide set of situations.

Adhoc query caching
Autoparameterization
Prepared queries, using
either sp_executesql or the prepare and execute method invoked
through your API
Stored procedures or other compiled objects
(triggers, TVFs, etc.)

SQL Server stores it’s caching plans in a metadata table called sys.dm_exec_cached_plans

Examining the cache

LEGEND:

Proc (Stored procedure) – “By default, the cached plan will be reused for all successive executions…. unlike the plans cached and reused with sp_executesql, you have an option with stored procedures and user-defined scalar functions to force recompilation when the object is executed.”
Prepared (Prepared statement) – ”The stored procedure sp_executesql is halfway between adhoc caching and stored procedures. Using sp_executesql requires that you identify the parameters and their datatypes, but doesn’t require all the persistent object management needed for stored procedures and other programmed objects.”
Adhoc (Adhoc query) – “…even when SQL Server caches your adhoc queries, you might not be able to depend on their reuse. When SQL Server caches the plan from an adhoc query, the cached plan will be used only if a subsequent batch matches exactly.”

DATA:

Determine what caching mechanisms are used outside the context of a stored procedure

Running the attached query NoStoredProcs.sql (see Resources section) yields the following results:

You can see that the Query executed with sp_executesql has its query plan cached as a  Prepared type while the inline statements were cached as Adhoc types.
Determine what caching mechanisms are used within the context of a stored procedure

Running the attached query WithStoredProcs.sql (see Resources section) yields the following results:

SP_Get_Person1 – Proc & Prepared

SP_Get_Person2 – Proc

SP_Get_Person3 – Proc & Adhoc

CONCLUSION:

It would seem that since there was no additional Adhoc cache plan created for SP_Get_Person2 that its structure can stand on its own (within a Stored Procedure), in terms of database caching. This can be confirmed by the fact that an Adhoc cache plan was created for this query outside the context of the stored procedure, but not when placed inside the stored procedure.

Performance

LEGEND:

Client processing time - The cumulative amount of time that the client spent executing code while the query was executed.
Total execution time - The cumulative amount of time (in milliseconds) that the client spent processing while the query was executed, including the time that the client spent waiting for replies from the server as well as the time spent executing code.
Wait time on server replies - The cumulative amount of time (in milliseconds) that the client spent while it waited for the server to reply.

DATA:

SP_Get_Person1

SP_Get_Person2

SP_Get_Person3

CONCLUSION:

From the results above, I can only conclude that any performance gains or losses between SP_Get_Person1 and SP_Get_Person2 are inconclusive/negligible since the average total execution time consistently differs in terms of microseconds. However, it is interesting to note that the average time for SP_Get_Person3 is significantly lower. I would strongly caution that this is not necessarily evidence of a reliable performance gain since every search would result in a new Adhoc query (SQL server did not autoparamatarize this query during my tests). Therefore it is inconclusive what the effect of a growing set of Adhoc queries would have on the database. Furthermore, we lose the safety of typed parameters when using this method.

Resources

NoStoredProcs.sql

use DemoDatabase

dbcc freeproccache;
GO
DECLARE @SearchText varchar(50)
SET @SearchText = 'Abatemarco'
Select * FROM PERSON Where LASTNAME Like '%' + @SearchText + '%'

GO
DECLARE @SearchText varchar(50)
SET @SearchText = 'Abatemarco'
EXECUTE sp_executesql N'Select * FROM PERSON Where LASTNAME Like ''%'' + @SearchText + ''%''', N'@SearchText varchar(50)',
                      @SearchText = @SearchText;

GO
DECLARE @SearchText varchar(50)
SET @SearchText = 'Abatemarco'
EXECUTE ( 'Select * FROM PERSON Where LASTNAME Like ''%' + @SearchText + '%''')

GO
SELECT usecounts, cacheobjtype, objtype, [text]
FROM sys.dm_exec_cached_plans P
    CROSS APPLY sys.dm_exec_sql_text (plan_handle)
WHERE cacheobjtype = 'Compiled Plan'
    AND [text] NOT LIKE '%dm_exec_cached_plans%';

WithStoredProcs.sql

use DemoDatabase

dbcc freeproccache;
--DROP PROCEDURE [SP_Get_Person1]
--DROP PROCEDURE [SP_Get_Person2]
--DROP PROCEDURE [SP_Get_Person3]
GO

    CREATE PROCEDURE [dbo].[SP_Get_Person1]
            @SearchText varchar(50)
    AS
    BEGIN
            SET NOCOUNT ON;
            EXECUTE sp_executesql N'Select * FROM PERSON Where LASTNAME Like ''%'' + @SearchText + ''%''', N'@SearchText varchar(50)',
                                  @SearchText = @SearchText;
    END

GO

    CREATE PROCEDURE [dbo].[SP_Get_Person2]
            @SearchText varchar(50)
    AS
    BEGIN
            SET NOCOUNT ON;
            Select * FROM PERSON Where LASTNAME Like '%' + @SearchText + '%'
    END
GO

    CREATE PROCEDURE [dbo].[SP_Get_Person3]
            @SearchText varchar(50)
    AS
    BEGIN
            SET NOCOUNT ON;
            EXECUTE ( 'Select * FROM PERSON Where LASTNAME Like ''%' + @SearchText + '%''')
    END
GO

    --SET STATISTICS IO ON
    --SET STATISTICS TIME ON
GO

    Execute [SP_Get_Person1] @SearchText = 'Abatemarco'

GO

    Execute [SP_Get_Person2] @SearchText = 'Abatemarco'

GO

    Execute [SP_Get_Person3] @SearchText = 'Abatemarco'

GO

    --SET STATISTICS IO OFF
    --SET STATISTICS TIME OFF
GO
    SELECT usecounts, cacheobjtype, objtype, [text]
    FROM sys.dm_exec_cached_plans P
        CROSS APPLY sys.dm_exec_sql_text (plan_handle)
    WHERE cacheobjtype = 'Compiled Plan'
        AND [text] NOT LIKE '%dm_exec_cached_plans%';

Tools

Statistics were gathered using the Include Client Statistics button in SQL Server Management Studio. Only the last 10 query results are stored and averaged. The results can be cleared from the menu: Query -> Reset Client Statistics.


First off, you should clean up the indention. Currently the wrong indention makes the code hard to read.

The next problem is that your variables width, prev and data are lacking the var keyword making them global und thus making the surrounding IIFE pointless. Unfortunatly you are actually reading the prev variable in the second hover function globally. This will go especially wrong if you happen to have multiple elements with the class portfolio-piece__link one one page. You may want to move the definition of those variables outside of your hover functions and declare them locally inside the IIFE. That way it also has the advantage that you don't need to create them on each hover.

Then what you need to consider is your code will not react to window resizes. What happens if the user originally opens your page with a small window size (< 640) and then resizes the window. BTW, why do you want this effect only on larger window sizes in the first place?

Finally you may want to consider writing this to be generic and not hard code it to only work with that specific class and property name.

EDIT:
Moving the variables outside the hover functions is of course not sensible, if you have multiple elements. I wrote that before I realized that. Instead you should store the old text, for example using jQuery's data method. Example:

function replaceText($element, text) {
   element.fadeOut(300, function(){
        $this.text(text).fadeIn(300);
    });
}

$('.portfolio-piece__link').each(function() {
  // Store original text
  var $this = $(this);
  $this.data('original-text', $this.text());
}).hover(function(){
    var $this = $(this);
    var data = $this.attr('data-portfolio');

    replaceText($this, data);
}, function(){
    var $this = $(this);
    var text = $this.data('original-text');

    replaceText($this, text);
});

BTW, I forgot one thing originally: You have duplicate code for replacing the text. You should replace it with a method as I did above.


Your switch is wrong: "/9J/4" is for JPG images, not PNG (e.g. as shown in these examples).


Unwanted return values in lambda functions?

Just replace Func delegate with Action delegate if you don't want return value:

private void ExecuteCommand(string commandText, Action<SqlCommand> action)
{
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(commandText, conn))
        action(cmd);
}

Then getting schools will look like (with help of LINQ you can get rid of local list of schools):

public IEnumerable<School> GetSchools(string searchChars)
{
    DataSet ds = new DataSet();

    ExecuteCommand("dbo.usp_esrvs_API_SchoolList", cmd => {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@SearchValue", searchChars));
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
    });

    return from row in ds.Tables[0].AsEnumerable()
           select new School(row.Field<int>("esrvs_Account_ID"),
                             row.Field<string>("SchoolName"));
}

NOTE: Consider to use Dapper both methods above are equivalent to:

private IEnumerable<School> GetSchools(string searchChars)
{
    using (var conn = new SqlConnection(connectionString))
        return conn.Query<School>("dbo.usp_esrvs_API_SchoolList",
                                  new { SearchValue = searchChars },
                                  commandType: CommandType.StoredProcedure);
}


Counting contiguous subarrays with a negative sum

To get a rough idea, you could consider: how 'deep' does the recursion go, and for each layer, how much work has to be done? See for example the tree in 8.2 Worst-case partitioning, as this is similar to what we have here.

Recurse for every element in the list, so the depth of the recursion tree is of the order n.

For each layer, there is the for loop, which is of the order n, and the array copying, which is also of the order n. So for each layer, there of the order O(n) amount of work to do.

So the algorithm does have complexity O(n^2). Also, is it really necessary to make the copy of the array each time? If your function had a second int start parameter (which is incremented with each recursive call), you could begin the for loop from further down the array with each recursive call, without the need for copies.

This might be a bit crude (and perhaps misleading if you choose the wrong scale), but you can always test it out with some different input sizes to see what happens. Note that with arrays above around 25000 elements I was getting StackOverflowErrors (although rereading the HR task, it was given the array size <= 100). You could do this by generating some random input of different sizes, and timing your function:


Code Challenge: basic arithmic operations using only incrementation operator

public enum Operation
{
    Addition,
    Multiplication,
    Exponentation
}

If you gave these explicit values:

  public enum Operation
  {
    Addition = 1,
    Multiplication = 2,
    Exponentation = 3
  }

... you could avoid the + 1 for the operation:

  return Hyper(left, (int)operation, right);

Because Hyper(...) is private, and you are supposed to know how to use it, there is no need for checking the input values in there. It is safe to leave it to Evaluate(...) to do that:

public static int Evaluate(int left, int right, Operation operation)
{
  if (left < 0) throw new ArgumentOutOfRangeException(nameof(left));
  if (right < 0) throw new ArgumentOutOfRangeException(nameof(right));
  if (!Enum.IsDefined(typeof(Operation), operation)) throw new ArgumentOutOfRangeException(nameof(operation));

  return Hyper(left, (int)operation, right);
}

it is safe because:

  if (n == 0) return b + 1;
  if (b == 0) return n == 1 ? a : n == 2 ? 0 : 1;

will catch zeros for n and b while a never changes so no arguments will never be lesser than zero - as you can only decrement by one.

Personally I would change the order of b and n to be the same as for Evaluate(...):

static int Hyper(int a, int b, int n) {...}

All in all in my writing it would look like:

  public enum Operation
  {
    Addition = 1,
    Multiplication = 2,
    Exponentation = 3
  }

  public static class Expression
  {
    public static int Evaluate(int left, int right, Operation operation)
    {
      if (left < 0) throw new ArgumentOutOfRangeException(nameof(left));
      if (right < 0) throw new ArgumentOutOfRangeException(nameof(right));
      if (!Enum.IsDefined(typeof(Operation), operation)) throw new ArgumentOutOfRangeException(nameof(operation));

      return Hyper(left, right, (int)operation);
    }

    static int Hyper(int a, int b, int n)
    {
      if (n == 0) return b + 1;
      if (b == 0) return n == 1 ? a : n == 2 ? 0 : 1;

      return Hyper(a, Hyper(a, b - 1, n), n - 1);
    }
  }

More edge/test cases?

BtW Hyper() stack overflows relatively quickly: for instance for a == 8 and b == 5 for Exponentation.

An alternative algorithm could be the below "semi-recurs-iterative":

It has a recursive depth of max 3:

public static int HyperIter(int a, int b, int n)
{
  if (n == 1)
  {
    while (b > 0)
    {
      a++;
      b--;
    }

    return a;
  }
  else
  {
    int res = n - 1;
    res--;
    while (b > 0)
    {
      res = HyperIter(res, a, n - 1);
      b--;
    }

    return res;
  }
}

I'm though not sure if it completely satisfies the criteria of only using + 1, because it uses a local variable (res) and -- - but the original also uses - 1 in the recursive calls, so...?


Reading configuration variables in a Python project

Add a declarative format for the config file, possibly. If you encounter errors, the output will look messy today (KeyError is never fun for an end user)
I would say init is a good time, but unclear if it's the right place. It's looking messy. I would either (1) split out parsing the config file into a helper method or (2) consolodate some lines. (1) is better if you expect to add more config.
I would consider making the chrome driver at the start of 'parse', as this is more of a "can fail" type operation--it will make writing tests easier.
Consolidating:

'builder' is used only once, don't declare it
don't assign to self.wanted_organizations_dict, or self.output_path, and self.start_urls twice. just initialize them once, correctly, in one line each.
self.job_highlight_dict is not initialized. i don't know what this is, but are you sure you want to declare it here?
self.CHROME_WEB_DRIVER does not appear to be used outside this, change it to a local variable or inline it, unless you move driver init to parse time
declare self.wanted_organisations_dict in a single-line dict comprehension, not 3 lines.
Initialize chrome_options in a single line, not 4.


Couting numbers greater than given - using binary search

First, the algorithm you're using strikes me as fairly inefficient. At least if I've understood the code, your intent is to have one array of items in original order, and another in sorted order. When you get a query, you find the number at the specified position in the original array, then do a binary search to find the same item in the sorted array.

I guess if the intent is specifically to write a binary search, that's all right, but if your intent is really to carry out such queries quickly, this doesn't seem like the best approach. Instead, I'd create a more direct mapping from input position to result.

For one possible way to do this, you could create an array of pairs of input values and the position at which that value was entered:

typedef std::pair<int, size_t> input;

std::vector<input> inputs;

int temp;
size_t i = 0;

while (std::cin >> temp)
    inputs.emplace_back(temp, i++);

Then we can sort the inputs (preferably in descending order) based on the input number:

std::sort(inputs.begin(), inputs.end(),
    [](input a, input b) {
        return a.first > b.first;
    });

Then (the interesting part) we create our lookup table to give the result for a query directly:

std::vector<size_t> query_table(inputs.size());

for (int i=0; i<inputs.size(); i++)
   query_table[inputs[i].second] = i;

Then handling a query is something like:

size_t query(size_t input_pos) {
    return query_table[pos];
}

Looking at the code in your question, the first thing that sticks out is indentation (or lack thereof). In binSearch, you seem to have no indentation at all. In main, you have a little indentation, but most of your loops and such have the controlled statement on the same line as the loop header, which most C and C++ programmers find distasteful (to put it mildly).

You're also depending on using a variable length array (your int a[n]; andint a_sorted[n];`) which isn't part of C++ (though some compilers include it as an extension).

Looking specifically at the algorithm you're using for your binary search, it appears that it'll potentially give incorrect answers whenever your input contains duplicate values. It simply looks for any instance of the correct value in the sorted array, but since you only want the number of inputs that were large, it should be looking for the position of the last entry with that value. For example: if your input were [1, 2, 1, 1, 1, 1, 1, 2], the sorted array would be: [1, 1, 1, 1, 1, 1, 2, 2]. Since that has 8 elements, and the first element it looks at is the fourth, it would find the fourth, and you'd then conclude that all the other numbers were larger, so it would say there were four larger numbers. What you really want to find is the last instance of that value, so (in this case) you'd find there are really only two larger values.


Populating two lists, each from their respective with user input field

Create a function with the common code:

function redundantSee() {

  var optionSet1 = $('.wrapper:eq(0)'),
      optionSet2 = $('.wrapper:eq(1)');

    function addImage(correspond, item) {
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $(correspond).append(item);
      item.append(imageElement);
    }

    optionSet1.find('.options').each(function() {addImage('div.corresponding1', nameListItem);})
    optionSet1.find('.options').each(function() {addImage('div.corresponding2', listItem);})
}

Here's a further reduced version that is also a little more efficient:

function redundantSee() {
    function processSet(set, correspond, item) {
        set.find('.options').each(function() {addImage(correspond, item);})
    }

    function addImage(correspond, item) {
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $(correspond).append(item);
      item.append(imageElement);
    }

    var wrappers = $('.wrapper');
    processSet(wrappers.eq(0), 'div.corresponding1', nameListItem);
    processSet(wrappers.eq(1), 'div.corresponding2', listItem);
}


Project Euler Problem 52: Permuted multiples

Python lacks C-style techniques like side-effect assignments (while (++x) { … }) and counting for-loops (for (int x = 125874; ; x++) { … }).  When you find yourself needing a counting loop in Python, a better formulation is nearly always available using either xrange(), itertools, or a generator.  In this case, I recommend itertools.count().

There's nothing in the problem statement that implies that the answer exceeds 125874.  The only logical limit I can see is that the answer needs to have at least six digits.  (The problem is probably designed to make you think about the decimal representation of \$\frac{1}{7}\$.)

Furthermore, manually writing all of the tests for 2, 3, 4, 5, and 6 is poor style.

There is no need to transform each set into a sorted list.  Skipping that transformation nearly doubles the speed of the code.

from itertools import count

for n in count(100000):
    digits = set(str(n))
    if all(set(str(mult * n)) == digits for mult in xrange(2, 7)):
        print n
        break


Your quicksort has a bug
Your midpoint calculation can overflow for large arrays:
mid=(left+right)/2;

Consider the following example code (C++ but it applies to C as well):
int x = std::numeric_limits<int>::max()/2 + 1;
unsigned int y = (x + x)/2;
cout<<"x:"<<x<<" y:"<<y<<endl; // x:1073741824 y:3221225472

The correct way to calculate this is like this:
mid = left + (right - left)/2;

which will not overflow if right>left for any right and left.


PHP OOP registration with User class and singleton Database class

For reasons laid out in this stackoverflow question  the singleton design pattern is not good match for PHP!

Clone Prevention

The advice from the accepted answer to the above stackoverflow question gives is to stop callers from cloning your object by adding a magic method like so:

public function __clone() {
    throw new Exception("Can't clone a singleton");
}

Your code will return false. false can be ignored / overlooked by programmers quite easily so I would stick to throwing an exception which is more explicit!

The Database Class

According to the php manual

  The intended use of __wakeup() is to reestablish any database
  connections that may have been lost during serialization and perform
  other reinitialization tasks.

Seeing as your class doesn't do that I can't see the value in the __wakeup method at all. There is a quote that is something along the lines of "don't write code you don't need now, because you won't in the future".

Chaining methods

As your getInstance method just returns an instance of the Database class and the method getConnection is public you can chain the calls like so:

$this->db = Database::getInstance()->getConnection();

PDO Exceptions

Make sure when setting up your PDO error mode to throw exceptions; this will prevent instances of trying to chain functions based on objects that fail to setup correctly.

Conclusion

If its not impractical too I would recommend (based on personal biases) that you drop the singleton pattern and move towards dependency injection simply because its easier to test and easier to get your head around!