Overall it looks good to me.
A few points though:

int.Parse will throw if Console.ReadLine returns a non integer. Perhaps an int.TryParse and display some help (position: 0 - 8)
It's a small app but since for the whole lifetime of your application, in each iteration you'll call WeHaveWinner. I'd initialize that array as a field to that class on object construction.
On WeHaveWinner you'll (possibly) be enumerating the return of .Select() twice. Consider calling ToList() on it.
The main method, could be:

      do
        {
            var i = int.Parse(Console.ReadLine());
            board.MakeMove(i);
            Console.WriteLine(board.DrawBoard());
        } while (!board.GameOver());

This way you won't be checking for winnings before the first input

Your string replace at the end on Empty could lead to a issue if the Enum Empty was renamed. Consider replacing (SquareType.Empty, " ")
You could consider replacing the Enum with a class, that would give you ability to use polymorphism. There you could override ToString to display (X or Y or empty) which would help you get rid of that String.Replace altogether.
Something along the lines of: https://stackoverflow.com/questions/1376312/whats-the-equivalent-of-javas-enum-in-c

+1 for the verbatin + interpolation


Pivot pandas DataFrame while removing index duplicates

I would use the built-in drop_duplicates() functionality.

x.drop_duplicates(['Loc', 'Change', 'Chrom'], keep='first', inplace=True)
x = x.pivot(index='newindex', columns='Individual', values='VAF')


I think you can lean on a class-variable to create your base paths, and then define the functions to use that variable:
import os
from sys import platform

class GetAllPaths:
    """
    Return file and paths directions
    """

    if platform == "win32":
        root = 'C:\\Users'
    elif platform == 'linux':
        root = '/home'
    else:
        # Probably raise an exception here
        raise Exception(f"Platform {platform} not supported")

    def test(self):
        return os.path.join(self.root, "test.py")

    def test2(self):
        return os.path.join(self.root, "test2.py")

    def test_flag(self):
        # new_manual_url.flag
        return os.path.join(self.root, "*test.flag")

    def kill_flag(self):
        # kill_*.txt
        return os.path.join(self.root, "*kill_*.flag")

    def restart(self):
        # start_*.txt
        return os.path.join(self.root, "*start_*.flag")

Furthermore, you'll notice that I'm using os.path.join, this way you don't have to worry about hard-coding the path separators.
Even more DRY would be to use a decorator on each of these functions which cuts down on repeated code:
import os
from functools import wraps
from sys import platform

class GetAllPaths:
    if platform == "win32":
        root = 'C:\\Users'
    elif platform == 'linux':
        root = '/home'
    else:
        # Probably raise an exception here
        raise Exception(f"Platform {platform} not supported")

    def _add_platform(f):
        @wraps(f)
        def wrapper(self):
            path = f(self)
            return os.path.join(self.root, path)
        return wrapper

    @_add_platform
    def test(self):
        return "test.py"

    @_add_platform
    def test2(self):
        return "test2.py"

    @_add_platform
    def test_flag(self):
        # new_manual_url.flag
        return "*test.flag"

    @_add_platform
    def kill_flag(self):
        # kill_*.txt
        return "*kill_*.flag"

    @_add_platform
    def restart(self):
        # start_*.txt
        return "*start_*.flag"

Ditch the class
Realistically, you don't need the class here. You can identify this by looking at how your functions are utilized. There's not any class or instance specific information being passed to your functions (decorator notwithstanding). This means that your class and a module are fairly indistinguishable. To see this without a class, you might put all of this code into a new file, say get_all_paths.py:
# get_all_paths.py
import os
from functools import wraps
from sys import platform

if platform == "win32":
    root = 'C:\\Users'
elif platform == 'linux':
    root = '/home'
else:
    # Probably raise an exception here
    raise Exception(f"Platform {platform} not supported")

def add_platform(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        path = f(*args, **kwargs)
        return os.path.join(root, path)
    return wrapper

@add_platform
def test():
    return "test.py"

@add_platform
def test2():
    return "test2.py"

@add_platform
def test_flag():
    # new_manual_url.flag
    return "*test.flag"

@add_platform
def kill_flag():
    # kill_*.txt
    return "*kill_*.flag"

@add_platform
def restart():
    # start_*.txt
    return "*start_*.flag"

Where now, you can use your functions through a global import:
import get_all_paths as g

g.test()
'/home/test.py'
```


Why you shouldn't parse ls.
Let's consider ls bad practice, and allow me to introduce a different method to solve your issue all together. Find every file in the directory, /home/user/Pictures/Wallpapers, perform a random sort on it and then grab the first result.
find /home/user/Pictures/Wallpapers -type f | sort -R | head -1
Sort man page
       -R, --random-sort
              shuffle, but group identical keys.  See shuf(1)


Time complexity

Let's have a look at the time complexity of your algorithm.

The bound is: \$N<2\cdot 10^6\$ and we want to compute: \$\left(\sum_{i=1}^N i^i\right)\mod(10^{10})\$.

Naively computing \$i^i\$ like you are doing will require \$\mathcal{O}(i)\$ operations. Computing the sum \$\sum_{i=1}^N i^i\$ will cost you \$\sum_{i=1}^N \mathcal{O}(i) = \mathcal{O}(N^2)\$ operations. Or in other words you're looking at the order of \$N^2 = 10^{12}\$ iterations of your inner loop. Or if every iteration of your inner loop take 10 ns (i.e. about 10 clock cycles on a 1GHz CPU), you're looking at \$10\cdot 10^{-9}\cdot 10^{12}=10^4\$ (\$10\$ cycles, \$10^{-9}\$ seconds per cycle) seconds which is about 3 hours.

However by using Exponentiation by Squaring you can reduce the time to calculate \$i^i\$ from \$\mathcal{O}(i)\$ to roughly \$\mathcal{O}(\log_2(i))\$ meaning that your expected complexity to calculate the sum: \$\sum_{i=1}^N i^i\$ is \$\mathcal{O}(N\log_2(N))\$. For \$N=10^6\$ you're looking at about \$2\cdot 10^7\$ iterations (\$\log_2(10^6)\approx 20\$) which should take our hypothetical computer about \$2\cdot 10^7\cdot 10\cdot 10^{-9}=0.2\$ seconds to compute.

So to fix your performance you need to use a better exponential computation, there are plenty of examples on the web.

Your code

Now to look at your loop:

    if(ii%10==0)
    {
        continue;
    }
    Temp=1;
    for( int jj=1 ; jj<=ii ; jj++ )
    {
        Temp*=ii;
        Temp=Temp%Mod;
    }
    Sum+=Temp;
    Sum=Sum%Mod;

The ii%10 == 0 optimization gives you maybe 10% speed gain which isn't much. And I say maybe, it depends on if your CPU correctly predicts the branch so it's probably a bit less than 10%. These kind of problems very rarely depend on how you optimize your code, but rather that you have the correct time complexity, see the above.


Computing the correlation of an analyzed stock ticker

private void firstPartTickers() {
        for(int i = 0; i< tickersWithOutOneAnalysed.size()/2; i++) {
            calculateCorrelation(i);
        };
    }

    private void secondPartTickers() {
        for(int i = tickersWithOutOneAnalysed.size()/2; i< tickersWithOutOneAnalysed.size(); i++) {
            calculateCorrelation(i);
        };
    }

You have two almost identical methods.  Is this really necessary?  Consider the following method:

    private void calculateTickers(int start, int increment) {
        for (int i = start; i < tickersWithOutOneAnalysed.size(); i += increment) {
            calculateCorrelation(i);
        }
    }

Note that I also removed the unnecessary ; after the for loop.

Now you can just call

                calculateTickers(0, 2);
                calculateTickers(1, 2);

instead of

                firstPartTickers();
                secondPartTickers();

And if you later wanted to do a third thread, you could say

                calculateTickers(0, 3);
                calculateTickers(1, 3);
                calculateTickers(2, 3);


Sorting is hard.

console.log( sortArray([ '123', '9' , '1' , '11' ]) ); returns ["1", "9", "11", "123"], that does not sound good. After removing the numeric test I get ["11", "123", "1", "9"] which is better but not intuitive, I would have expected the 1 up front. This shows that you cannot just write the code, you need to build a set of tests to validate your code. Especially during interviews.
String.prototype.getFirstCase is very cute, but it needs commenting for lesser readers.
You are mixing var and let, I am not too excited about that
If you remove the numeric test, then you no longer need isNumeric as well
compareCaseSenitiveStrings should be compareCaseSensitiveStrings
I would convert 2 line comments to 1 line comment for readability, and an overall review of what comments really add value
Other than the code was very readable


Because the class is sealed, your IDisposable implementation is over-complicated. The whole entire point of the disposing flag is to make sure unmanaged resources get cleaned up correctly even if a class inherits this type and overrides Dispose... but your method isn't virtual, so it's only ever called/callable with Dispose(true).

Scrap that, keep it simple:

public void Dispose()
{
    _ignores.Clear();
    _ignores = null;
}

Actually, if you're using that type correctly, then you gain nothing from explicitly clearing the internal list and nulling it up - the instance is [in theory] about to get collected anyway; IDisposable is making your class much more complex than it needs to be.

Typically you'd make a class implement IDisposable when it's holding on at instance level to a reference that implements IDisposable itself, which does not appear to be the case here (unless PlayerConnection has implications that aren't in your post) - disposing a List<int> is pure overkill.

Moreover, calling Dispose twice should have no ill effect on the calling code, but in your case it throws a rather surprising NullReferenceException, and then you could very well call InitializeComponent again... without getting an expected ObjectDisposedException (you get another NullReferenceException instead).

The IComponent interface seems uncalled for, given how the callers seem to only be calling the concrete types' implementations of the InitializeComponent method.

The implementation is tightly coupled with some static/global-scope database-interacting service, which makes it untestable.

If all "components" load things from a database, it seems you need to look into the repository pattern, and possibly the unit of work as well. Consider using dependency injection to decouple your implementation from its dependencies, and avoid static / global-scope objects in OOP as a general rule of thumb.


I've got a couple quick notes. Overall it looks like this method will work.

Validating args[0]

The only validation that you do on args[0] is to check if there are any images in that directory, but you don't check other possible failure conditions, such as if the directory provided doesn't exist.  For a user, no images being found and the directory itself not being found would have different actions required to fix the problem.  It would be helpful to perform better validation here and providing meaningful feedback, and perhaps a different return code.

Duplicate Calls to Get Path

There are a couple instances that call Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).  This could be factored out to a variable.

Use TimeSpan Formatting

TimeSpan provides functionality for converting to a string in a particular format (see https://msdn.microsoft.com/en-us/library/ee372286(v=vs.110).aspx)  In this case, I think you'd want the "g" format.

Return Codes

You return -1 in the event of no files being found, but you don't handle returning a different value if collection.Write(filename) fails.  If this was being called from a script, I'd expect any failure to return a failed return code.

Catching Exceptions

While the exceptions thrown by collection.Write(filename) are likely all IO related, it would be helpful to catch at least some of the individual errors and displaying helpful information where possible.  For example, if an exception was thrown because of a write permission issue, it would be helpful to let the user know that they need to correct their permissions, as opposed to hoping that the library you use provides a helpful description.

There are also some instances that I bet could throw an exception that you don't handle.  For example, I would expect collection.Add(image) to throw an exception in some circumstances.  If some exceptions are handles and displayed in a user-friendly way, I'd expect all of them to.

Commenting

Some of the comments are helpful, such as the reference to documentation for a method from StackOverflow.  However, there are also some trivial comments (stopWatch.Elapsed is pretty clearly going to get the elapsed time). But there are also instances where comments would be helpful, such as what the values you set on the MagickImage are (what does image.Sharpen(0, 3) do?)


What you are doing here is Kadane's algorithm. Wikipedia presents an implementation in Python which should not be hard to rewrite in Ruby.


TL;DR: Read about MVC and understand the basics and then learn laravel

This is not about object oriented approach but more like a separation of concerns thing. You have two concerns for the moment:

You're collecting some data
You're displaying it

so what you have to do is to separate them, start by using a template system like twig or smarty. Collect the data in some php and pass it to the template file and render it so the html code and php code will be separated.

The template will be responsible of "how" you display the data and your php file will be responsible of "preparing the data" for the template.

Second step is to separate the code that is "dealing with the data" from the code that is "setting up the template". You can move the data related code to some class so that you'll have smt. like this in the end:

<?php

// Require classes, setup things etc.

$obj = new Events;
$events = $obj->getAllEvents();

echo $tpl->render('events/index.tpl', array('events' => $events));

Third step may be about the // Require classes, setup things etc. part in the example above. You can use a front-controller to deal with that...

... and the list goes on...

After some struggling you'll start to realize that you need some helper classes to deal with the http requests, responses, sessions etc.

...and you'll need more and more "concerns" to "separate" in the future and in the end you'll understand why people are using mature frameworks these days.

I was writing like this in 1997-1998 (no kidding) because I had to, but you don't :)


Text replacement with Räubersprache ("Røversprog")

I probably would reach directly for Parsec or another parsing library writing this from scratch, but I think even with a more direct recursive solution you've drastically overcomplicated this!
Separate your problem into constituent pieces which you find easier to handle on their own terms. In this case, I would start by writing a function phoneme :: [Multigraph] -> String -> (Phoneme, String) to consume only a single n-graph off of a given word.
import Data.List (isPrefixOf, stripPrefix)

type Phoneme = String
type Multigraph = Phoneme

phoneme :: [Multigraph] -> String -> Maybe (Phoneme, String)
phoneme multigraphs word@(letter:rest) = -- The use of @ is an example of an 'as-pattern'
    case filter (`isPrefixOf` word) multigraphs of
      (multigraph:_) -> Just (multigraph, fromJust $ stripPrefix multigraph word)
      []             -> Just ([letter], rest)
phoneme _multigraphs [] = Nothing        -- Prefixing an arg with _ says to the compiler
                                         -- that you meant not to use it in the definition
                                         -- i.e. you won't get a warning when compiling
                                         -- with -Wall (specifically --Wunused-matches)

This version achieves multigraph detection by testing the passed multigraphs against the remaining portion of the string, \$O(m)\$ in the number of multigraphs. Your original version tests every multigraph against every prefix of the string, making it \$O(mn)\$.
Now the next obvious step is to use this function in breaking an entire string into its constituent phonemes.
import Data.List (unfoldr)

phonemes :: [Multigraph] -> String -> [Phoneme]
phonemes multigraphs = unfoldr (phoneme multigraphs)

Sometimes you either know about a common Haskell concept or you don't. In this case, if you're unfamiliar, unfoldr :: (b -> Maybe (a, b)) -> b -> [a] repeatedly applies a function that returns a desired output and some state to itself, collecting the output into a list and terminating once the function reaches the “end” and has returned Nothing.
Now before anything else we have to be able to robber an individual phoneme.
robberPhoneme :: [Multigraph] -> [Multigraph] -> Phoneme -> String
robberPhoneme _mconsonants mvowels p
  | p `elem` mvowels = p
  | p `elem` vowels  = p
  | otherwise        = p ++ "o" ++ p
  where vowels = map pure "aeiouy"

You could obviously leave out the consonants argument, but I think it's helpful to remind callers not to just pass all of the multigraphs they have on hand, vowels being treated differently from consonants.
And now we're ready to tie it together.
robber :: [Multigraph] -> [Multigraph] -> String -> String
robber mconsonants mvowels = concatMap (robberPhoneme mconsonants mvowels)
                           . phonemes (mconsonants ++ mvowels)

And there you go! Much less bookkeeping, parsed strictly left to right, and by relying entirely on standard functions for all of the recursion anyone reading my code (including me, later) can quickly understand how control flows through the program without having to mentally grapple with primitive recursion.
This doesn't sit wholly perfectly with me (I'd probably create a datatype to represent all the different kinds of phonemes in a language and pass that around instead, I didn't feel good just throwing the monophthongs in there but it was expedient, couple other nits) but it's enough of a solution that I'd ship it.


Your solution is a bit wasteful by generating and testing all integers in the desired range while you actually only need a handful of them.

A big improvement in terms of performance is to avoid modulo arithmetic and increase the step-size tenfold whenever you finished iterating a sub-range 1-9, 10-99, 100-999 and so on:

let max = 7322;
let step = 1;
let next = 10;

while (step < 1000 && next < max) {
  for (let i = step; i < next; i += step) {
    console.log(i);
  }
  step = next;
  next *= 10;
}

for (let i = step; i < max; i += step) {
  console.log(i);
}

Of course, you might want to encapsulate above code in a function or even more versatile, a generator function and replace console.log(i); with yield i;.

However, since you only have four different step-sizes of 1, 10, 100, and 1000 you can encode them manually and come up with an even simpler generator function as follows:

// Generate logarithmic range from 1 to max (excluded):
function* logRange(max) {
  for (let i = 1; i < max && i < 10; i += 1) yield i;
  for (let i = 10; i < max && i < 100; i += 10) yield i;
  for (let i = 100; i < max && i < 1000; i += 100) yield i;
  for (let i = 1000; i < max; i += 1000) yield i;
}

// Example:
for (let i of logRange(7322)) console.log(i);

This avoids modulo arithmetic, computes only the desired numbers and is pretty easy to understand.


Yes, I believe that will accomplish what you are trying to do.  However, I think it can also be streamlined pretty substantially.  Some general pointers:

Looping through the directory to get all files on all page requests is going to be pretty inefficient in the long-run.  File operations are relatively expensive, because they require disk-seeks.  Obviously this is less critical for a low-traffic system with a small number of files.
You are returning the default page if an invalid page is requested.  I think it would be better to either show an access-denied error (as such a request might signify someone trying to circumvent restrictions in your system) or at least a 404 (which would be more friendly towards legitimate users).  Either way, you should stop executing when an invalid page is found.
You could fix the first issues if you have a database in your system. Instead of directly checking the file path, you could record the list of allowed pages in your database, check against the DB, and then load the page in much the same way you currently are.  The advantage of such a solution is that you could separate your public paths from your filenames: the database could record the "url" of the file which you lookup against, and then fetch the actual filename out of the database.  Of course if you do that, you pretty much just made a basic routing system.
Is there anything that prevents users from going directly to the pages?  From the looks of it your pages are just a sub-directory of your public system.  That may suggest room for possible security vulnerabilities.

As an alternate way of accomplishing exactly what you are doing without reading the full directory, you can use realpath.  It returns the normalized absolute URL to a file, or nothing if the file doesn't exist.  You can then check and see if what is returned by realpath actually lives in your application directory.  That will make for fewer disk seeks and will allow your performance to remain (relatively) constant even if the number of files grows.  Here is a quick example:

if(isset($_GET)){
    $pages_dir='/path/to/pages/folder/pages/';
    $requested=reset($_GET);
    $path=realpath($pages_dir . $requested);
    if(!$path || substr($path, 0, strlen($pages_dir)) != $pages_dir){
        show_404();
        exit;
    }
}

include($path);

To reiterate, you build the path assuming the file lives in the destination directory.  realpath will then resolve the path, accounting for directory traversals.  I.e. if $_GET contained ../../../../../../../etc/passwd then you would pass this to realpath: /path/to/pages/dir/pages/../../../../../../../etc.passwd and realpath would return simply /etc/passwd.  You then check what realpath returned to see if your results are still in the proper directory.  If it is, then you're good.


Can this recursive binary search in C be made more concise?

Things you did well

Declaring your parameters as void when you don't take in any arguments.
Keeping your dependencies to a minimum.

Things you could improve

Bugs:

You sorted your array for your program.

int values[] = {2,4,5,12,23,34};

Your program fails to find your value if your array is not sorted initially.

int values[] = {9,4,3,12,69,34};

Let the computer do the hard work by using qsort().

Efficiency:

Recursion is slowing you down in your re_search() method.  Use iteration instead.  The conversion isn't too hard, there are a lot of similarities.

int binarySearch(int a[], int low, int high, int target)
{
    while (low <= high)
    {
        int middle = low + (high - low)/2;
        if (target < a[middle]) high = middle - 1;
        else if (target > a[middle]) low = middle + 1;
        else return middle;
    }
    return -1;
}

Variables/Initialization:

You shouldn't use global variables.

int value = 5;
int values[] = {2,4,5,12,23,34};
int n = 6;

The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).

If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.

So instead of using global variables, initialize the variables in main(), and pass them as arguments to functions if necessary.
Right now your n variable is hard coded.

int n = 6;

Since this is just the number of elements in your array, we can make this a bit more dynamic, so that you don't have to change it if you add a few more elements to your array.

int n = sizeof(values)/sizeof(values[0]);

Right now you are hard coding the number you are looking for.

int value = 5;

I would either let the user enter it, or determine a random number to search for.

srand((unsigned int) time(NULL)); // seeding
int val = values[rand() % n];

Syntax/Styling:

You print out items to the console within your re_search() method.

printf("Found it!\n");
...
printf("Did not find it\n");

I would have it so your function only evaluates if the number exists in the array and returns whether it could find it or not.  Then let main() do all the printing to the console based on that information.

printf("%s\n", (re_search(value, values, n)) ? "Found it!" : "Didn't find it.");

Final Code

I've rewritten your code so that it is bug free, and so that it is a bit more dynamic.  I also rewrote some bits so you could see what was going on, and so the program was more transparent.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int binarySearch(int a[], int low, int high, int target)
{
    while (low <= high)
    {
        int middle = low + (high - low)/2;
        if (target < a[middle]) high = middle - 1;
        else if (target > a[middle]) low = middle + 1;
        else return middle;
    }
    return -1;
}

int compare(const void *a, const void *b)
{
    return (*(int*)a - *(int*)b);
}

void printArray(int arr[], int size)
{
    printf("{ ");
    for (int i = 0; i < size; i++) printf("%d, ", arr[i]);
    puts("}");
}

int main(void)
{
    int values[] = {16, 7, 5, 94, 24, 34};
    int n = sizeof(values)/sizeof(values[0]); // find the number of elements in the array
    qsort(values, n, sizeof(values[0]), compare);
    srand((unsigned int) time(NULL)); // seeding
    int val = values[rand() % n]; // fetch a random value in the array
    int found = binarySearch(values, 0, n - 1, val);

    printArray(values, n); // just so we can see the sorted array
    if (found >= 0) printf("Found %d at index %d\n", val, found);
    else printf("Didn't find %d\n", val);
    return 0;
}


Representing and Parsing an Open or Closed Range

I would check the result of range

range = _RemoveSpaces.Replace(range, string.Empty);

against string.Empty because that is one of the cases where the code reaches this.

// No idea what we were given, give a completely open range.
return new Range<T>(null, null);

Returning early will get you some performance here. Doing a null check on range before that call isn't necessary because Regex.Replace() throws a ArgumentNullException for the case that range == null.

Speaking about Regex.Replace I would prefer string.Replace() over Regex.Replace because it seems faster. See: comparing regex replace string replace and stringbuilder replace which has better performance

One should not always do what can be done.

public override string ToString()
{
    return (this._Minimum == null) && (this._Maximum == null)
        ? string.Empty
        : (this._Minimum == null
            ? string.Format("-{0}", this._Maximum)
            : (this._Maximum == null
                ? string.Format("{0}+", this._Minimum)
                : string.Format("{0} - {1}", this._Minimum, this._Maximum)));
}

IMO this isn't readable at first glance so maybe some good old if..else would be better. Having underscore prefixed membervariables and using this is too much.

public override string ToString()
{
    if ((_Minimum == null) && (_Maximum == null)) { return string.Empty; }

    if (_Minimum == null) { return string.Format("-{0}", _Maximum); }

    if (_Maximum == null) { return string.Format("{0}+", _Minimum); }

    return string.Format("{0} - {1}", _Minimum, _Maximum)));
}

If you are using C# 6 you could use the string-interpolation operator $ instead of string.Format().

About Interval vs Range I would prefer Range because Interval IMO suits only with dates and times but e.g don't suits with int.

__

Inside the Parse() method I would check the found minimum and maximum before calling the constructor. IMO throwing an exception in a constructor should be avoided if possible.

In general you code looks tidy and clean.

You are using good variables- and methodnames.
You are using braces although they are optional.
Your code is easy to read.


Python command-line Tic Tac Toe for two humans

Avoid too much code in try blocks

The try ... except ValueError in the take_turn function wraps too many statements that it shouldn't need. Only the int(...) statement may raise a ValueError there, so it would be better to wrap only that in the try. When you wrap a large block of code, it can lead to masked errors or make defect localization harder.

Magic values

Instead of referring to the player symbols by their literals like '0' and 'X', it would be better to give them names.

Iterate over elements when possible

In this code you iterate over indexes of elements:

   for x in range(len(winning_combos)):
        score = 0
        for y in range(len(winning_combos[x])):
            if boxes[winning_combos[x][y]] == player:
                score += 1
            if score == 3:
                win = True

It would be more natural, simpler and safer to iterate over elements:

for combo in winning_combos:
    score = 0
    for index in combo:
        if boxes[index] == player:
            # ...


Any problems with this prime checker script?

There is lots of room for improvement here. Let me give some broad guidelines:

First, Your function checking if its input is prime should return a boolean and probably be called something like isPrime or is_prime. The string you are returning is nice for being human readible, but the goal should be to build components that can be used elsewhere, and the function as written isn't really something you can build on. And given the boolean function, you can easily build your version on top of that:

def prime_checker(n):
    if is_prime(n):
        return "%d is prime" % n
    else:
        return "%d is not prime" % n

Second, there is some improper use of Booleans (and lack thereof).  You have isinstance(x,float) == True. The isinstance function already returns a boolean, there's no need to compare against True. That clause can just be if x <= 1 or isinstance(x, float):. But then, does it make sense that 2.7 is not prime? Maybe that should raise an Exception. You are also building up a list of size x consisting of values that are intended to indicate whether or not the value at that index divides x. You chose:

div.append("d") #d denotes divisible

Which you realized was cryptic because you had to comment what that meant. Rather than relying on a comment to explain what you're doing, it's much better for the code to comment itself. In this case, what should we append to indicate that a number is a true divisor? How about:

div.append(True)

Third, you're building up a long list of things that should be Booleans but are instead strings. But that is a whole lot of extra work for what we actually want to count: the number of factors. The simplest explanation for why it's extra work is that first you're walking through all potential divisors, and then you're walking through it again to count how many were actual divisors. Instead, you can do this in one go:

divisors = 0
for divisor in range(1, x+1):
    if x % divisor == 0:
        ++divisors
return divisors == 2 #because a number prime iff it has exactly 2 divisors, 1 and itself

Once you write it that way, this has lots of room for simple optimizations. For instance, obviously every integer is divisible by 1 and itself, so you can exclude those two:

for divisor in range(2, x):
    if x % divisor == 0:
        return False # because we have a divisor other than 1 or x
return True

After that, things get more interesting. For instance, let's say we're checking a number like 5077 for primality. If it is NOT prime, then there are two numbers, a and b, such that 1 < a <= b < n and a*b == n. What is the largest possible value for a as a function for n? I'll leave that as an exercise, but the last algorithm I proposed assumes the maximum possible value is x - 1, and we can do much better.


Rails method to match users according to language fluency level

This is a somewhat shorter more concise version of your code. Taking advantages of some or Rails's magic and conventions.

def email_matches(current_user)
  fluent_ids = current_user.languages.where("level > 4").pluck(:language_id)
  nonfluent_ids = current_user.languages.where("level < 5").pluck(:language_id)

  fluent_user_ids = LanguagesUser.where(language_id: fluent_ids, level: 1..4)
    .pluck(:user_id)
  nonfluent_user_ids = LanguagesUser.where(language_id: nonfluent_ids, level: 5)
    .pluck(:user_id)

  matches = fluent_user_ids & nonfluent_user_ids

  new_matches = User.where(id: matches, status: "Active").order(last_seen: :desc).limit(10)
  new_matches.each do |user|
      UserMailer.new_match(user, current_user).deliver_later
  end
end

This takes advantage of the has_many :languages in your User model. Also uses the pluck method which returns an array of language_ids

current_user.languages.where.where("level > 4").pluck(:language_id)

There is however a way to do this all in maybe 1-2 lines of SQL, maybe someone else will provide that magic here.


Find an ideal speed to cross all traffic lights when they are green

I wanted to use List.tail for the recursion, but I couldn't find how to get the whole list back when I needed to restart the recursion.

Easy! You can pass the whole list as an additional parameter.

My Scala is a bit rusty, but I think you can write like this using pattern matching:

def computeIdealSpeed(currentSpeed: Float, lights: List[TrafficLight], allLights: List[TrafficLight]): Float = {
    lights match {
        case light::tail => {
            val newSpeed = light.getIdealSpeed(currentSpeed)
            if (newSpeed != currentSpeed) {
                computeIdealSpeed(newSpeed, allLights, allLights)
            } else {
                computeIdealSpeed(newSpeed, tail, allLights)
            }
        }
        case nil => currentSpeed
    }
}

And then call the method with:

val idealSpeed = computeIdealSpeed(speed, lights, lights)

I'm not sure this is any better though. I would nitpick on the placement of braces and spacing around conditional statements, and the lack of indentation of the body of App.


Is this good c++ code for a pin/socket for a node editor?

Input and output count
enum InputOutputCount {
    NOTHING = 0, //Is this redundant?
    ONE = 1,
    MULTIPLE = -1
};

Yes, I think a pin that does not allow anything to connect to it is redundant. This could be replaced with a simple bool that indicates whether multiple connections are allowed or not.
Note that it doesn't make sense to restrict the number of connections to an output pin, there is nothing ambiguous about that. However, for input pins there is ambiguity: what should you do if there are multiple, different values on the input? Do you pick one, sum them, average them, multiply them? So there it does make sense to restrict the input to just one connection.
Make Pin::Value a reference
Does it make sense for Value to be a null pointer? After setting the pointer, can the pointer change? If the answer to both of these questions is no, then it is better to make it a reference, like so:
template <class T>
struct Pin: PinAbstract {
    ...
    T &value;
    ...
};

You should add a constructor that initializes the reference, so that it is not possible to construct a concrete Pin without a correct reference. You can also use this to ensure the title is always set to something useful, like so:
template <class T>
struct Pin: PinAbstract {
    const std::string Title;
    T &value;
    std::vector<Pin> Connections;

    Pin(T &value, const std::string &title): Value(value), Title(title) {}
};

Return an error if a connection cannot be made
Your function ConnectPins() silently ignores errors when trying to connect two incompatible pins together. Consider adding some way of reporting an error. It can be as simple as returning a bool indicating success, or you could throw an exception. This could then be used by the UI to display an error message.
Pass pins by reference to ConnectPins()
Similar to why you might want to use a reference instead of a pointer for Pin::Value, since you should never pass a NULL pointer to ConnectPins(), it is better to pass them by reference:
template <class T>
bool ConnectPins(Pin<T> &pin1, Pin<T> &pin2) {
    if (pin1.Type != pin2.Type)
        return false;
    ...

    pin1.Connections.push_back(&pin2);
    pin2.Connections.push_back(&pin1);
    return true;
}


I think your class is pretty much useless. If you have a class that represents a fraction, you should be able to do operations with it that you can do with a fraction, like addition, subtraction, multiplication and division (possibly using operator overloading). Another possible operation is fraction simplification.

Also, you shouldn't throw Exception, you should instead a custom type that inherits from Exception (called something like ZeroDenominatorException) and throw that.

And your Main() isn't very realistic. In real code, you wouldn't write code that you know will always throw an exception. So I think that your try should be around both of your new Fraction() statements.

Also, if you're going to have all the operations I have mentioned above, a better application to show that would be a very simple fraction calculator.

Something like:

Enter numerator:
1
Enter denominator:
4
Enter operation:
+
Enter numerator:
3
Enter denominator:
4
Result: 4/4
Simplifies result: 1/1


Issues

public void Push(T item)
{
    _stackList.Insert(0, item);
}

The hurts the stack list.

It would be much easier if you just added new items at the end of the list. The Insert needs to rebuild the entire list:

  This method is an O(n) operation, where n is Count.

For an addition this is a real bottleneck.

The same applies to the Pop method which internally uses List.Remove:

  This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

With these features the StackList<T> is unusable - as far as performance is concerned.

I saw this comment of you:

  I've made it the way it is because I wanted to be able visually see how the stack is sorted while debugging but I guess that will do.

There is a much simpler solution for debug helpers without sacrificing performance.

You can decorate your class with the DebuggerDisplay attribute and build what you need to see in debug.

Here's the pattern I use:

[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class StackList<T> : IEnumerable<T>
{
    private string DebuggerDisplay => $"[{string.Join(", ", this)}]";
}

It's not a mistake that the property is private. The debugger will find it anyway and by being private it doesn't pollute the public API.

Challenging the purpose of the StackList<T>

Finally I'd like to undermine the purpose of the StackList<T>.

You write:

  I needed a structure that works really similar to the predefined Stack but with a few extra functionalities for example getting the index of value in the collection and being able to index the structure itself.

I doubt you need a new type for this. With a few extensions you can achieve the same with less effort and based on the original Stack.

Let's try...

  getting the index of value in the collection

We can build a new extension for this by utilizing two other extensions:

static class StackExtension
{
    public static int IndexOf<T>(this Stack<T> stack, T value)
    {
        var result = stack.Select((x, i) => new { x, i }).FirstOrDefault(y => y.x.Equals(value));
        return result == null ? -1 : result.i;
    }
}

or with C# 6

public static int IndexOf<T>(this Stack<T> stack, T value)
    => stack.Select((x, i) => new { x, i }).FirstOrDefault(y => y.x.Equals(value))?.i ?? -1;

Example:

var s = new Stack<int>();
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);

s.Dump();

s.IndexOf(2).Dump(); // 2
s.IndexOf(4).Dump(); // 0
s.IndexOf(5).Dump(); // -1

  being able to index the structure itself

For this you don't even need to write an extension because there is already one: ElementAt and its safe equivalent ElementAtOrDefault.


Time limit exceeded for Sherlock and Queries Hackerrank challenge

The time complexity of your solution is
\$ O(NM) \$. It is too slow. You need a more efficient algorithm. Here is a pseudo code of a better one:

// Reads the input.
n = read_input()
m = read_input()
a = read_input()
b = read_input()
c = read_input()
// Creates an auxilary array to remove duplicates from b
totalProduct = an array of n + 1 elements filled with 1
for (i = 1; i <= m; i++)
    if (b[i] <= n)
        totalProduct[b[i]] = totalProduct[b[i]] * c[i] % MOD
for (divisor = 1; divisor <= n; divisor++)
    // Iterates over all number that are divisible by the divisor
    for (number = divisor; number <= n; number += divisor)
        a[number] = a[number] * totalProduct[divisor] % MOD
print(a)

The correctness of this algorithm is obvious (it simply does what is written in the problem statement). So why is it efficient? It is fast because its time complexity is $$ O\big(M + { N \over 1 } + { N \over 2 } + { N \over 3 } + \dotsb + { N \over N }\big) = O(M + N \log N). $$
Why do we need to remove duplicates from b? If we don't do it, the time complexity will be \$ O(M + N^2) \$ if all elements of b are equal to 1.


ASP.NET and code-behind

One of the main advantages of ASP.NET is the code-behind model. This ensures that the logic and the markup are separated in different files. The markup's goal is to display data, not to determine whether controls should be visible or not. So, your code is in violation with that principle.

The Evil of Eval

I suggest your read following article: The Evil of Eval() in ASP.NET. Here's one of the many reasons:

  Eval takes about 1/20th of a second per call, and the other way takes about 1/1000th of a second per call. On a grid with 5 columns and 8 rows, Eval would take 2 seconds and the other would take under 1 second. Nobody would notice the difference. However, change that grid to 10 columns and 50 rows. You now have a difference of 25 seconds. It is the kind of thing that might not matter very much, most of the time but when it does, it makes a big difference.

The article contains more information and links to other resources.

Solution

Make the tr server-side by adding runat="server" to to the tag and give it an ID. Now you can access the tr-tag from the code-behind and set it's visibility property. Example:

Markup

    This is not visible

Code-behind

Dim isVisible As Boolean = False
'apply logic to determine whether "isVisible" should be true or false
myRow.Visible = isVisible

Solution for the Repeater - ItemTemplate

Here's a solution that works when your data resides in an ASP.NET Repeater control. Following is a sample markup:

<asp:Repeater ID="PeopleRepeater" runat="server">
    <HeaderTemplate>

    </HeaderTemplate>
    <ItemTemplate>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

And here's the code that does the magic:

Sub PeopleRepeater_Bind(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
    Handles PeopleRepeater.ItemDataBound

    If e.Item.ItemType = ListItemType.Item Or
       e.Item.ItemType = ListItemType.AlternatingItem Then

        Dim isRowVisible As Boolean = False 'Your condition here
        CType(e.Item.FindControl("UserRow"), HtmlTableRow).Visible = isRowVisible

    End If

End Sub

The code checks if the current bound item is an item or an alternating item. This is necessary because the binding of the header and footer will also trigger this event. If this is the case, prepare your boolean variable to set the row visible or not. Lastly, get the table row tag using the FindControl method and set its visibility to the variable.


Generating vertices of the rectified hypercube

Generally I'm quite fine with your original source, looks nice.

If you are pursuing absolutely top performance (what is the reason? This looks like a function, which should be used only few times trough life cycle of application) - you would have to dig into std::next_permutation first, to see if for your special case of various sets of {-1, 0, 1} values you can generate permutations "manually" in a faster way, then the general purpose permutation generator does. Maybe there is a way, but the source will become substantially longer and more complicated.

If you want to stay with std::next_permutation, there's little room for improvement, especially without losing some readability of the source.

For example with understanding how the set is modified by last next_permutation, you can cut out some initializations and sorting like this:

#include <array>
#include <vector>
#include <algorithm>

template <typename T, size_t N>
std::vector<std::array<T, N>> generate_rectified_hypercube()
{
    std::vector<std::array<T, N>> vertices;  // result data
    std::array<T, N> set; // set to permute upon
    // Initialize set to { 0, 1, ..., 1 }
    set[0] = T(0);
    for (size_t i = 1; i < N; ++i) set[i] = T(1);

    // Generate vertices

    // Add all possible permutations of initial set (unrolled loop for i=0)
    do {
        vertices.push_back(set);
    } while (std::next_permutation(set.begin(), set.end()));

    for (size_t i = 1; i < N; ++i) { // do the rest of them

        // Modify set to be seed for next group of permutations:
        // "abusing" the known state after last std::next_permutation call
        set[i-1] = T(-1);    // Here was zero previously
        set[i] = T(0);       // Here was first 1

        // Add all possible permutations of current set
        do {
            vertices.push_back(set);
        } while (std::next_permutation(set.begin(), set.end()));

    }
    return vertices;
}

int main()
{
    auto vertices = generate_rectified_hypercube<float, 5>();
}

As you can see, I removed the temp array (std::copy not needed) and I use the know state after last next_permutation to avoid std::sort. So this is certainly more efficient, but also harder to read and comprehend.

One note about your original code:

You don't clear the vertices input, which doesn't feel right to me. If the function is named generate_rectified_hypercube, it sounds quite functional to me, so calling it twice with the same vector I would expect it to contain only single copy of vertices (your code would add another set after the first one).

For your code probably some name along add_generated_rectified_hypercube would be more precise.

In my code I avoided this completely by creating new instance of vertices inside the function, and letting the C++11-post era compilers to optimize "return by value" situation.

And you can still do twice vertices.push_back(generate_rectified_hypercube<float, 5>()); to get two sets of vertices, to simulate behaviour of your original code (if desired). So the change in API is not limiting such usage, but it shouldn't happen by accident, reusing some non empty vertices.

Another edit:

Couldn't resist from showing off, how the function can be further cleaned up for better performance (unrolling the loop for i == 0 special case, getting rid of if (0 < i) in for loop).

The real world benefit is of course useless, as the loop is done only N-times (vs permuting N size array inside, which is much more complex).

So just for your fun ;). (BTW, OCD is evil thing, even partial ... hard to dismiss some things from head)


This may fit perfectly depending on the purposes, or you could use another approach to be more efficient, clean or consistent.

If you just need to set a few variables of a project, and you don't mind running opts.c every time you change opts.cnf
Well, your existing solution fits perfectly.

If you are using ops.cnf to set some variables or constants at compilation time.
In this case, you may have to use #include and #define

If you are planning to use configuration file(s) for different sort of things in your project.
In this case I would recommend libconfig. Maybe LUA  or even Javascript.

Depending on your needs.


Finding the right structure for my application

I would go somewhere in the lines of the following code:

abstract class ObjectImporter {

    protected $em;

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

    abstract public function import($object);
}

class TypeAImporter extends ObjectParser {

    public function __construct($em) {
        parent::__construct($em);
    }

    public function import($object) {
        #do your import magic
    }
}

class XmlImporter {

    private $importer;

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

    public function import($files) {
        foreach ( $files as $file ) {
            $obj = Parser::xmlToObject($file);
            $this->importer->import($obj);
        }
    }
}

switch ( $xmlType ) {

    case 'TypeA':
        $importer = new XmlImporter(new TypeAImporter(\App::getEm()));
    break;
}

$importer->import($files);

Some notes: the code is not ideal (names aren't that good imo) and I don't like the Parser::xmlToObject method. The Parser should be injected into the XmlImporter class aswel. This way its easier tested and you can also very easily change the xml Parser.

I hope the code is of any use.


Grab the first 4 items that meet the condition from a data set with an unknown size

So that would mean that very large datasets would increase computation time.

You should ask if very large datasets are possible.  Because if they're not, clean code takes precedence over what would be a premature optimization.  All the code inside your then block can be replaced with a single line:

json.data.filter(x => x.profile_path).slice(0, 4)

If performance is truly an issue, your basic thinking is correct, but I'd just use a for loop:

let result = [];
let data = json.data
for (var i = 0; i < data.length; i++) {
  if (data[i].profile_path) result.push(data[i])
  if (result.length == 4) return result
}
// ask interviewer what the behavior should be for incomplete results...

Note that returning inside a for loop will exit the function immediately.

Fwiw, it sounds like the problem you faced was mostly about communication with the interviewer. Next time, politely probe them about what they're looking for, what their assumptions are about the problem, and so on.


Interesting,

I actually really like your constructor, it is neat and shows in one place what the class does. I am not sure I would call it SignupDoctorPostRequest, since it is not a request at all but processes a request. I would consider DoctorSignupModel or since it seems to leverage several models DoctorSignupMetaModel.

As for your eager validation, I have to agree that it does not look very elegant. If you could work SignupDoctorPostSchema.validate( into this.validatePlanId (possibly call it then this.validate), you could rewrite your write to this:

router.post('/', function (rq, response) {

    var metaModel = new DoctorSignupMetaModel(rq.body);

    request.validate() //<- This will do all validation now
    .then(request.createUser)
    .then(request.subscribeUser)
    .then(
        function Success (authenticatedUser) {
          response.status(201).json({});
        }
    )
    .catch(
        function Fail (fail) {
          var statusCode = fail.type === 'Validation' ? 422 : 500;
          var responseStatus = fail.type === 'Validation' ? 'fail' : 'error';
          var responseData = fail.type === 'Validation' ? fail.details : fail.message;

          response.
            status(statusCode).
            json({
              status: responseStatus,
              data: responseData
            });
        }
    );
});


MySQL and caching

From the manual (emphasis added)

  The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. If an identical statement is received later, the server retrieves the results from the query cache rather than parsing and executing the statement again.

To test out, I recreated the table you posted in MySQL Workbench:

use test;
drop table if exists referrals;
create table referrals(
    id int not null primary key,
    user_id int,
    placement_id int
);
insert into referrals(id, user_id, placement_id)
values
(1,          2,         NULL),
(2,          3,          2),
(3,          4,          2),
(4,          5,          3),
(5,          6,          4),
(6,          7,          3),
(7,          8,          3),
(8,          9,          3),
(9,          10,         6),
(10,         11,         5),
(11,         12,         6),
(12,         13,         4),
(13,         14,         3),
(14,         15,         9),
(15,         16,        10);

I ran the following query 3 times:

SELECT placement_id FROM referrals WHERE user_id = 3;
-- 1st time 0.002 sec / 0.000 sec
-- 2nd time 0.000 sec / 0.000 sec
-- 3rd time 0.000 sec / 0.000 sec

As you can see, each time you run it with the same user_id it will get it from the cache. But if it's not the same user_id it will start a new query.

Stored statement

Assuming your actual table is much larger than the example provided, you would likely benefit from creating a stored statement, which will retain the execution plan along with the query. To create the statement, just pass this to MySQL once, either from Workbench or from PHP:

delimiter $$
    create procedure FindPlacementId (in param_user_id int)
    begin
    SELECT placement_id FROM referrals WHERE user_id = param_user_id;
    end$$
delimiter ;

Then this section:

$query = "SELECT placement_id FROM referrals WHERE user_id = $id";

Becomes:

$query = "CALL FindPlacementId ($id);";
-- a few tests:
-- 0.001 sec / 0.000 sec
-- 0.000 sec / 0.000 sec
-- 0.000 sec / 0.000 sec


Here are my comments:

The variable k was probably meant to keep track of size of the array list (number of duplicates).  However, it is redundant, since you use the list's size() method.
To convert a list to array you can use the stream API. while I am not certain if it provides any time/space benefits, it is probably the most optimized way to do it, and it saves you having to declare the return array. Since it is tricky to do the conversion with primitive types arrays, here it is: ans.stream().mapToInt(item -> item.intValue()).toArray(); and you can make it the return value of the method.
The while condition is using redundant parentheses that have the && between them . It can be argued as a matter of taste, but in my eyes, the condition is clearer without them. I add an additional space around the higher order operator: while(i < arr1.length  &&  j < arr2.length)


ViewController.h
First, this name isn't really descriptive at all, is it?  We need to know more about this view controller.  In fact, standard naming convention is to suffix all view controller subclasses with ViewController anyway, so this is basically an unnamed view controller.
Now, basically everything declared in your .h should be in the .m file.  Of the 6 property declarations, 5 of them are IBOutlet properties, and there's never really an excuse for a view controller to expose its subviews publicly.  A view controller should be in complete controller of its view.  If an outside class needs to do something that would effect one of these views, create a public method, and let that method internally handle the effects on those views.
As for the 4 IBAction method declarations, you don't even need to declare these.  The only reason to put a method in an @interface section is to expose it to another class.  And IBAction methods should never be exposed to another class for the same point as exposing IBOutlets to outside classes.  If you need to, create a public method and have that method call the IBAction method internally.
Finally, the MBFQuotes object.  Does this need public visibility?  Are you modifying it from outside classes?  Looks like probably not, and as such, we can get rid of the class declaration (@class MBFQuotes) and move the @property declaration in the the @interface section of the .m, which comes after the #import of that classes file, and eliminates the need for declaring the class.

ViewController.m
Seeing as we're not actually doing anything in didReceiveMemoryWarning, we can simply eliminate that entire method from this file.  All we're doing is calling the super method, and simply leaving the entire method out handles that.  I understand that didReceiveMemoryWarning's stub is generated automatically by Xcode when you create a new UIViewController subclass, but you should still take it out unless you intend to do something with it (and in most cases, you won't need this method).
Our four IBAction methods look quite similar, don't they?  Why don't we combine them into one method.
First, we need an enum for some readability, so at the top of this file, right after the #import statements, you'll want this code:
typedef NS_ENUM(NSInteger, QuoteTypes) {
    GeneralQuotes = 100,
    LifeQuotes = 101,
    PoliticalQuotes = 102,
    SmartQuotes = 103
};

Now, let's use the .tag property of UIButton.  You can set this on the storyboard or programmatically.  If you set it on the storyboard, set the tag for each button to match the appropriate number in the enum we just created.  Programmatically, you can set them as such:
self.generalButton.tag = GeneralQuotes;
self.lifeButton.tag = LifeQuotes;
self.politicalButton.tag = PoliticalQuotes;
self.smartButton.tag = SmartQuotes;

Now then, get rid of the 4 IBAction methods (be sure to unlink the buttons in storyboard), and create on method to handle all 4 buttons, link all of the buttons to that method.  The method should look something like this:
- (IBAction)quoteButtonPushed:(id)sender {
    switch(sender.tag) {
        case GeneralQuotes:
            self.quoteLabel.text = [self.quotes randomGeneral];
            self.quoteLabel.backgroundColor = [UIColor redColor];
            break;
        case LifeQuotes:
            self.quoteLabel.text = [self.quotes randomLife];
            self.quoteLabel.backgroundColor = [UIColor blueColor];
            break;
        case PoliticalQuotes:
            self.quoteLabel.text = [self.quotes randomPolitical];
            self.quoteLabel.backgroundColor = [UIColor blackColor];
            break;
        case SmartQuotes:
            self.quoteLabel.text = [self.quotes randomSmart];
            self.quoteLabel.backgroundColor = [UIColor orangeColor];
            break;
        default: break;
    }
}

And please notice that I've used self.quotes here rather than _quotes as you used.  If you're declaring a @property, you should be accessing that property through the accessor except in init, dealloc, and the accessor methods, should you choose to write custom accessor methods.  If you don't want to access the property through the accessors, then maybe you don't need a property and instead just need a regular instance variable.

MBFQuotes.h / MBFQuotes.m
As it stands, this is really incomplete as a class, and doesn't really justify being a class at all.  It could easily be simply a set of C-style functions.  Which way do you want to go?  Right now, you're in between.
If we're happy with the methods as they are and don't want to add anything, then let's change this to some C-style functions:
// MBFQuotes.h

#import <Foundation/Foundation.h>

NSString * randomGeneral();
NSString * randomLife();
NSString * randomPolitical();
NSString * randomSmart();

Notice the slightly different style and the elimination of @interface and @end.  This is no longer a class, but instead a header file with some C-style function declarations.
EDIT: All right, so you can't actually have const NSArray objects as far as I can tell.  The answer has been edited to the next best solution:
// MBFQuotes.m

#import "MBFQuotes.h"

NSString * randomGeneral() {
    static NSArray *generalQuotes = @[@"g1", @"g2", @"g3", @"g4"];
    int randomGeneral = arc4random_uniform([generalQuotes count]);
    return [generalQuotes objectAtIndex:randomGeneral];
}

NSString * randomLife() {
    static NSArray *lifeQuotes = @[@"l1", @"l2"];
    int randomLife = arc4random_uniform([lifeQuotes count]);
    return [lifeQuotes objectAtIndex:randomLife];
}

NSString * randomPolitical() {
    static NSArray *politicsQuotes = @[@"p1", @"p2"];
    int randomPolitical = arc4random_uniform([politicsQuotes count]);
    return [politicsQuotes objectAtIndex:randomPolitical];
}

NSString * randomSmart() {
    static NSArray *smartQuotes = @[@"s1", @"s2"];
    int randomSmart = arc4random_uniform([smartQuotes count]);
    return [smartQuotes objectAtIndex:randomSmart];
}

Notice moving the array declaration out of the functions/methods and declaring them as constants.  This makes the program a lot more efficient.
Anyway, if you don't want to go this route, there is certainly room to turn this into a class.  For starters, you'd still want to move the arrays out of the methods, but now you'll want them as private properties.  For this to be truly classworthy though, you'd want to include methods to be able to add and remove quotes, perhaps give the class a file-path and parse quotes out of a text file.
Realistically, since this is a class and we're instantiating it, we shouldn't have different categories of quotes.  Realistically, we should instantiate a different object of this class for each quote category.
UNLESS... we were to add a method to pick a random quote from ALL categories (single method, random category, random quote).

Finally, I think for the project to be really complete, instead of the MBHQuotes class simply holding an array of strings, completeness would say there should be a Quote class, which consists of a few properties.  The main property is the quote itself.  The other properties give some information about the quote, such as the author, the date of the quote's origin, the category of quote it fits into, etc.


Singleton implementation of a database connection

As per the docs

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.90).aspx

  Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

This means that while the Singleton instance can be technically correct, it is not correct in this specific context of the SqlConnection class if you plan to access instance members from different threads (and you possibly do).


Using Dictionary of int and list of tuple in C#

There might be a reason why you used a List<Tuple<string ,double, double>>. E.g. if you need to pass the data to an existing library or your UI needs to bind to a list. Otherwise I would recommend to create a dedicated class

public class RiskStatistics
{
    public double ArithmeticMeanMonthly { get; set; }
    public double ArithmeticMeanAnnual { get; set; }

    public double AverageGainMonthly { get; set; }
    public double AverageGainAnnual { get; set; }

    public double AverageLossMonthly { get; set; }
    public double AverageLossAnnual { get; set; }
}

Since the properties are named, there's no need for magic strings. This makes the creation and usage of the risk matrix less convoluted:

public Dictionary<int, RiskStatistics> RiskMatrixByFunds(
    Dictionary<int, IEnumerable<double>> returnsLists)
{
    var riskMatrixDict = new Dictionary<int, RiskStatistics>();

    foreach (KeyValuePair<int, IEnumerable<double>> entry in returnsLists) {
        var risk = new RiskStatistics();
        (risk.ArithmeticMeanMonthly, risk.ArithmeticMeanAnnual) = ArithmeticMean(entry.Value);
        (risk.AverageGainMonthly, risk.AverageGainAnnual) = AverageGain(entry.Value);
        (risk.AverageLossMonthly, risk.AverageLossAnnual) = AverageLoss(entry.Value);
        riskMatrixDict.Add(entry.Key, risk);
    }
    return riskMatrixDict;
}

You could also calculate the annual values on the fly. This would make the creation even easier. Here the adapted average gain properties as an example:

private static readonly double Sqrt12 = Math.Pow(12, 0.5);

public double ArithmeticMeanMonthly { get; set; }
public double ArithmeticMeanAnnual => ArithmeticMeanMonthly * Sqrt12;

With this adapted RiskStatistics class, you could directly assign from the extension methods and skip the methods returning tuples.

var risk = new RiskStatistics {
    ArithmeticMeanMonthly = entry.Value.Mean(),
    AverageGainMonthly = entry.Value.GainMean(),
    AverageLossMonthly = entry.Value.LossMean()
};
riskMatrixDict.Add(entry.Key, risk);

The annual values are read-only and need not to be assigned.


Bad support for fragmented tcp packets

StringBuilder sb = new StringBuilder();

mBuffer.clear();
int read = 0;
while ((read = ch.read(mBuffer)) > 0) {
    mBuffer.flip();
    byte[] bytes = new byte[mBuffer.limit()];
    mBuffer.get(bytes);
    sb.append(new String(bytes));
    mBuffer.clear();
}

The above implementation only works reliable with messages smaller than 567 (IPV4) or 1200 (ipv6) bytes, because larger messages can come in fragmented in multiple chunks with large intervals in case of packet loss. This will result is half send chat messages that are broadcasted

Using default charset

You are not specifying any charset when reading the messages, this will result in platform and even java dependent behaviour when reading special characters.

Manually using stringbuilder

String address = (new StringBuilder(sc.socket().getInetAddress()
                .toString())).append(":").append(sc.socket().getPort())
                .toString();

You don't need to use stringbuilder if you already have all the used arguments on 1 line, the compiler will automatically add a stringbuilder for you.

String address = sc.socket().getInetAddress() + ":" + sc.socket().getPort();


WPF async await TcpClient/TcpListener sample

The general issue with your code is that your client and server implementations reside in your control's code-behind. It is always a good idea to separate business logic from UI.
This is copy-paste:

if (anyIP.IsChecked == true)
{
    listener = new TcpListener(IPAddress.Any, Int32.Parse(serverPort.Text));
    Logger.Info("Ip Address : " + IPAddress.Any + " Port : " + serverPort.Text);
}
else
{
    listener = new TcpListener(IPAddress.Parse(serverIP.Text), Int32.Parse(serverPort.Text));
    Logger.Info("Ip Address : " + serverIP.Text + " Port : " + serverPort.Text);
}

can be refactored to:

var ip = anyIP.IsChecked == true ? IPAddress.Any : IPAddress.Parse(serverIP.Text);
var port = Int32.Parse(serverPort.Text);
listener = new TcpListener(ip, port);
Logger.Info(String.Format("Ip Address : {0} Port : {1}", ip, port));

Its a good style to prefix fields with underscore, so they can be distinguished from local variables. So it should be _listener instead of listener.
You should shut down your server on exit.
Yes, as long, as you await the call you can catch exceptions.


Generator iterator with push back function

This is to expand on Austin Hastings comment.

According to Python Standard Library documentation,

  The intention of the protocol is that once an iterator’s next() method raises StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.

It means that once the underlying iterator raises StopIteration, your object shall not accept any more push backs.

I would call the list lookahead rather than pushed_back, but it is a matter of taste.

Otherwise, LGTM.


Accessing Wi-Fi network interface details from Java using netsh

It looks like the solution you posted here was copy-pasted (with some cutting of irrelevant lines) from this SO answer and its original code is quite quick&dirty.

However, here are some observations about it:

This will work only on a Windows system.
Neither InputStreamReader nor BufferedReader are closed, which is a bad practice.
It's not clear how IOException is managed. I suppose that it is rethrown by the wrapping method?
while (true) is a bad pattern for loops.

A better choice would be:

String line = r.readLine();
while (line != null) {
  // logic
  line = r.readLine();
}

Using line.contains("SSID") seems to be enough to identify the line with the SSID, but it will fail if (accidentally) another line of the process output contains this substring. That should not occur normally, but who ever knows how the parameters are set on the host where it is run? I'd suggest here to split the line in two parts by ':' and check if the trimmed left side equals("SSID").


Click handlers that display the status of a submission

You can simply extract the common code into a function.  Arguably you could pass this rather than href and $target and derive ref and target in the function or pass $parent rather than $target, but the current arguments seem slightly clearer.

$(function() {

    var fetchUrl = function (href, $target, color) {
      $(".spinner").show();

      $.get(href)
          .done(function() {

              var $parent = $target.parent();

              $parent.children("spinner").show();

              $parent.children("a").remove();
              $parent.children("span").remove();
              $parent.attr("class", "");
              $parent.css("background-color", color);

              $(".spinner").hide();
          });
    };

    $(".manualSubmitComplete")
        .click(function() {
            fetchUrl(this.href, $(this), "#B0FFB0")
            return false;
        });

    $(".manualSubmitReject")
        .click(function() {
          fetchUrl(this.href, $(this), "#FF0000")
          return false;
        });
});


Is it a good practice to put an exception handler in every method?

Don't do that.

If you log your exceptions at every function, you'll print the same exception over and over and over again. Its only useful the first time, after that its a pain.

It will also make your code much harder to read and write.

You should log the exception when you would otherwise lose it. At some point, your exception has to be caught and not rethrown. This may happen in the default exception handler. That's where you should log. Don't log exceptions that you just rethrow. Trust whoever catches them to log them.


First of all, you should always run clippy:

error: this public function dereferences a raw pointer but is not marked `unsafe`
  --> src/lib.rs:20:29
   |
20 |         ffi::CStr::from_ptr(text)
   |                             ^^^^
   |
   = note: #[deny(clippy::not_unsafe_ptr_arg_deref)] on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#not_unsafe_ptr_arg_deref

error: calls to `std::mem::drop` with a value that implements Copy. Dropping a copy leaves the original intact.
  --> src/lib.rs:60:4
   |
60 |    mem::drop(data);
   |    ^^^^^^^^^^^^^^^
   |
   = note: #[deny(clippy::drop_copy)] on by default
note: argument has type *mut std::ffi::c_void
  --> src/lib.rs:60:14
   |
60 |    mem::drop(data);
   |              ^^^^
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#drop_copy

drop(data) is indeed totally useless here pointer don't have drop implementation, you must use Box::from_raw(data as *mut SomeData) (BTW you didn't check for null here hope this is what you want). I also advise you to mark these function as unsafe.

For the style there is two sides as you seem to require the pointer is no null:

You could assume the pointer is always no null, add only a debug panic
You could panic if the pointer is null

I'm in favor of the first option but it's as you like, if you take the second option I advice to use Option<&T> this will prevent you to forget to check if the pointer is null, it's guarantee by Rust that Option<&c_char> will be None for null pointer value.

Your get_number() and get_text() use Box::from_raw(data as *mut SomeData) for nothing, just use directly the pointer or transform it to reference.

I'm unsure void pointer is necessary.

  Do I need to provide a free_string function? Is there a way to just return a pointer into the Rust string?

yes of course you must use from_raw()

Final code:

use std::ffi;
use std::os::raw::{c_char, c_void};

#[derive(Debug)]
pub struct SomeData {
    text: String,
    number: usize,
}

#[no_mangle]
pub unsafe extern "C" fn make_some_data(text: Option<*const c_char>, number: usize) -> *mut c_void {
    ffi::CStr::from_ptr(text.unwrap())
        .to_str()
        .map(|str| {
            Box::into_raw(Box::new(SomeData {
                text: str.to_string(),
                number,
            }))
        })
        .unwrap() as *mut c_void
}

#[no_mangle]
pub unsafe extern "C" fn get_text(data: Option<&c_void>) -> *mut c_char {
    let data = my_real_data(data);
    ffi::CString::new(data.text.clone()).unwrap().into_raw()
}

#[no_mangle]
pub unsafe extern "C" fn get_number(data: Option<&c_void>) -> usize {
    let data = my_real_data(data);
    data.number
}

unsafe fn my_real_data(data: Option<&c_void>) -> &SomeData {
    &*(data.unwrap() as *const std::ffi::c_void as *const SomeData)
}

#[no_mangle]
pub unsafe extern "C" fn drop_data(data: Option<*mut c_void>) {
    Box::from_raw(data.unwrap() as *mut SomeData);
}

#[no_mangle]
pub unsafe extern "C" fn drop_text(data: Option<*mut c_char>) {
    ffi::CString::from_raw(data.unwrap());
}


Find number of neighbour pairs in the input tree

Readability counts

Overall, conventions are respected: case, spaces… But there are still some things missing to make your code feel readable:

vertical spacing: you should add blank lines before functions definition and important logical sections of the code so we can grasp the structure at a glance.
naming: one letter variable are not great, especially when conventions dictates an other use of that letter than the one you make (I’m looking at you for i in input_tree:).
namedtuples can help give meaning to your lines of input:

from collections import namedtuple

Node = namedtuple('Node', 'id key left_child right_child color')

def read_input(inputstring):
    …
    input_tree = [Node(*map(int, input().split())) for _ in range(nodes_number)]
    …
        for node in input_tree:
            node_label = node.id
            …
                l_node, r_node = node.left_child, node.right_child

and so on.
You don't need to define nested functions, you can pass them parameters. It will be easier to test (for correctness or speed). In fact, you should separate further the computation bits from the parsing of the input.

You also import defaultdict but never use it. Instead, your code contains a few setdefault(…, []) on regular dictionaries. You should declare tree = defaultdict(list) and result = defaultdict(list) instead.

Building the depth of nodes

For each node (technically each node id), you iterate over the whole input_tree and then recurse, iterating over the whole input_tree for the two children.

This is a huge waste of time. Instead of iterating over a list to find a node by its id, you should use a datastructure that let you access a node by its id directly. A simple dictionary where keys are ids and values are node should suffice.

Computing neighbour pairs

First of, you could start your last loop at i+1 so you don't need the if j > i: test. But still, you don't even need that second loop at all: by keeping track of the last white node and the last black node you could only iterate once for each depth.

Proposed improvements

from collections import defaultdict, namedtuple

Node = namedtuple('Node', 'id key left_child right_child color')

def read_nodes(nodes_count):
    for _ in range(nodes_count):
        yield Node(*map(int, input().split()))

def parse_input():
    nodes_count, root_node = map(int, input().split())
    tree = {node.id: node for node in read_nodes(nodes_count)}
    return root_node, tree

def build_depth(node_id, tree, storage, current_depth=0):
    node = tree[node_id]
    storage[current_depth].append(node)
    for child in (node.left_child, node.right_child):
        if child:
            build_depth(child, tree, storage, current_depth + 1)

def neighbour_pairs(layered_tree):
    neighbours_count = 0 # neighbours = defaultdict(list)
    for nodes in layered_tree.values():
        last_black = Node(0, None, 0, 0, 1)
        last_white = Node(0, None, 0, 0, 0)
        for node in nodes:
            if node.color == 1:
                last_node, last_black = last_black, node
            else:
                last_node, last_white = last_white, node
            if last_node.key == node.key:
                neighbours_count += 1 # neighbours[last_node.id] = node.id
    return neighbours_count # return neighbours

if __name__ == '__main__':
    root, tree = parse_input()
    nodes_by_depth = defaultdict(list)
    build_depth(root, tree, nodes_by_depth)
    neighbours = neighbour_pair(nodes_by_depth)
    print(neighbours) # print(len(neighbours))

You can see that I’m not storing the pairs of neighbours, it will help speed things up. But I left comments if you still want to be able to retrieve them to test for correctness.


Project Euler #49: Find 12-digit number concatenating a three terms sequence

There's a few things that can be improved here:

First, I'm not sure if you neglected it here or if you actually aren't using it, but every file should start with a call to ns. This sets the namespace that the code following it will be in so other files can require it properly. If the code resides in src/my_thing/my_file, you would have

(ns my-thing.my-file)

At the top.

Second, unfortunately, that gen-primes function that you took from SO isn't a good example a proper practice. Unless you have an extraordinarily good reason, don't use def (and by extension, defn) to create a locally bound symbol. def creates globals that exist even once the function has returned:

(take 0 (gen-primes)) ; Run the function just so the inner defn happens
=> ()

(type primes-step)
=> irrelevant.cr2_original$gen_primes$primes_step__4224

Note how using using primes-step doesn't lead to an error. It's in scope!

To fix this, you could either just use let and define the function like was done with reinsert:

(defn gen-primes []
  (let [reinsert (fn [table x prime]
                   (update-in table [(+ prime x)] conj prime))

        primes-step (fn primes-step [table d]
                      (if-let [factors (get table d)]
                        (recur (reduce #(reinsert %1 d %2) (dissoc table d) factors)
                               (inc d))
                        (lazy-seq (cons d (primes-step (assoc table (* d d) (list d))
                                                       (inc d))))))]

    (primes-step {} 2)))

or, since you're only defining local functions, this is a good use-case for letfn:

(defn gen-primes []
  (letfn [(reinsert [table x prime]
            (update-in table [(+ prime x)] conj prime))

          (primes-step [table d]
            (if-let [factors (get table d)]
              (recur (reduce #(reinsert %1 d %2) (dissoc table d) factors)
                     (inc d))
              (lazy-seq (cons d (primes-step (assoc table (* d d) (list d))
                                             (inc d))))))]

    (primes-step {} 2)))

The latter doesn't have as much indentation, which is always nice.

This can be greatly simplified though if you're willing to sacrifice some performance for readability. Here's a version I threw together:

(defn gen-primes []
  ; Quick helper predicate
  ; A number is prime if there is not some number which is a factor of the number
  (letfn [(prime? [n]
            (not (some #(zero? (rem n %))
                       (range 2 (int (inc (Math/sqrt n)))))))]

    ; Drop the first two numbers from the range (because we don't care about 0 and 1
    ; Then filter all the primes
    (filter prime? (drop 2 (range)))))

Rarely do you ever actually need to use lazy-seq explicitly. lazy-seq is the fundamental, low level building block for creating lazy sequences. Fortunately, many functions like filter already return a lazy sequence. In my function above, I'm just lazily filtering out all the non-primes from an infinite range of numbers, without ever explicitly using lazy-seq.

I realized after I posted this that this is actually a bit of an "apples and oranges" comparison. My version is a naïve brute-force approach which, while terse, is inefficient. Looking at the original code again, I'm assuming it's some kind of sieve that likely performs much better than my version.

get-digits can be greatly simplified as well if you just abuse strings here:

(defn my-get-digits [num]
  (->> num
       (str) ; Have str do most of the heavy lifting
       (map str) ; Then turn each character back into a string so they can be parsed
       (map #(Long/parseLong %))
       (into '())))

They even perform identically. I was expecting mine to be slower, but it ended up being 0.1 µs faster:

(cc/quick-bench
  (get-digits 192837465))
Evaluation count : 93972 in 6 samples of 15662 calls.
             Execution time mean : 5.665620 µs
    Execution time std-deviation : 872.894028 ns
   Execution time lower quantile : 4.709602 µs ( 2.5%)
   Execution time upper quantile : 6.504343 µs (97.5%)
                   Overhead used : 4.360719 ns
=> nil

(cc/quick-bench
  (my-get-digits 192837465))
Evaluation count : 130404 in 6 samples of 21734 calls.
             Execution time mean : 5.508682 µs
    Execution time std-deviation : 485.864725 ns
   Execution time lower quantile : 4.669716 µs ( 2.5%)
   Execution time upper quantile : 5.944096 µs (97.5%)
                   Overhead used : 4.360719 ns

Where cc is an alias for the Criterium core module; a great benchmarking library.

Again, try to reuse existing constructs unless you have a good reason to get your hands dirty, or you really want the practice (although practicing reusing existing constructs is important as well).

are-permutations-of-each-other? has a little duplication, but is simple enough that that's not a big deal. If you wanted, you could use map to reduce some of the duplication. I made a var-arg function so it can accept any number of numbers to check. It's highly unnecessary, but doing so works well with use of map anyways, and doesn't change its usage. There's two nearly identical versions to choose from, depending on whether or not you want to use functions composition via comp, or just lazily map twice:

(defn are-permutations-of-each-other? [& nums]
  (->> nums
       (map (comp sort get-digits))
       (apply =)))

(defn are-permutations-of-each-other? [& nums]
  (->> nums
       (map get-digits)
       (map sort)
       (apply =)))

This isn't a big deal, but in your main threading call that ties everything together, you have

(->> (for [i four-digit-primes
               j four-digit-primes]
           [i j])

     (remove #(apply = %))
     ...)

There's certainly nothing wrong with this. I'll just point out that an alternative is just to apply filter directly in the for:

(->> (for [i four-digit-primes
           j four-digit-primes
           :when (not= i j)] ; Here
       [i j])
     ...)

for can accept three kinds of keywords like that in its binding list. :when only adds to the list if the condition is true. It's like Python's if inside of list comprehensions.

Again in the main thread, you have:

(filter (fn [[n1 n2]]
          (let [mx (max n1 n2)
                mn (min n1 n2)
                diff (- mx mn)
                next (+ mx diff)]
            (and (< next 10000)
                 (four-digit-primes next)
                 (are-permutations-of-each-other? n1 next)))))

At some point, you need to look at your anonymous function and break it off into it's own function. Not only does that neaten up the threading calls, it names the function so it's clearer what the code is actually doing.

A little down, you have

(map #(map str %))
(map (partial apply str))

Now, it doesn't matter which you choose, but consistency is nice. In the first line, you're using #(), and in the second, you're using partial; even though both can be done using either. I prefer #() unless I'm already inside a function macro since I find partial adds a lot of noise. Which you use doesn't matter though; just try to apply the same idea everywhere and be consistent in your style.

Finally, I stuck the whole main thread call into a -main function. Having code executing on the top level like that sucks if you're developing using a REPL. Every time I tried to load the function into the REPL to reflect a change I had made, the whole thing would run, which forced me to wait a couple seconds extra. In most cases, I prefer to stick everything inside functions so stuff only runs when I want it to.

Taking all that into consideration, here's what I ended up with:

(ns irrelevant.cr2-fixed)

(defn- gen-primes []
  (let [prime? (fn [n] (not (some #(zero? (rem n %))
                                  (range 2 (int (inc (Math/sqrt n)))))))]

    ; Drop the first two numbers from the range (because we don't care about 0 and 1
    ; Then filter all the primes
    (filter prime? (drop 2 (range)))))

(defn- get-digits [num]
  (->> num
       (str) ; Have str do most of the heavy lifting
       (map str) ; Then turn each character back into a string so they can be parsed
       (map #(Long/parseLong %))
       (into '())))

(defn- are-permutations-of-each-other? [& nums]
  (->> nums
       (map get-digits)
       (map sort)
       (apply =)))

(defn -main []
  (let [four-digit-primes (->> (gen-primes)
                               (drop-while #(< % 1000))
                               (take-while #(< % 10000))
                               (apply sorted-set))

        ; Give this a better name. I have no idea what you'd want to call it.
        filter-helper (fn [[n1 n2]]
                        (let [mx (max n1 n2)
                              mn (min n1 n2)
                              diff (- mx mn)
                              next (+ mx diff)]
                          (and (< next 10000)
                               (four-digit-primes next)
                               (are-permutations-of-each-other? n1 next))))]

    (->> (for [i four-digit-primes
               j four-digit-primes
               :when (not= i j)]
           [i j])
         (filter #(apply are-permutations-of-each-other? %))
         (filter filter-helper)
         (map sort)
         (distinct)
         (map #(cons (+ (second %) (- (second %) (first %))) %))
         (map sort)
         (map #(map str %))
         (map #(apply str %))
         (second)
         (println))))

(-main)
296962999629
=> nil

Hopefully that helps you out. Your code is actually quite good for someone learning the language. Keep it up!


Vigenère Cipher problem in competitive programming

Comments

decrypted_msg is misleading. It's not decrypted but rather "not encrypted". But really just call it "plaintext", as the problem statement does.
Similarly, "enciphered" and "encrypted" are not just inconsistent (make up your mind), but go against the problem statement's term "ciphertext".
The end-signal string '0' can simply be checked as a string.
No need to check the plaintext against '0'.
Mapping str.strip over sys.stdin makes the code a bit nicer. We can even use a nice for statement then.
Better just zip the plaintext and key instead of iterating over indices.
Searching the letters in the alphabet string isn't super terrible, but it's apparently faster to look up letter pairs in a dictionary.
itertools.cycle is a nicer (and I think faster) way to cycle the key.
Repeatedly extending a string with += might degrade to quadratic time overall. Better use ''.join on an iterable.
A little time can be saved by storing string.ascii_uppercase.index in a variable instead of looking up the attributes ascii_uppercase and index over and over again.

Solution 1: My fastest[*], using a lookup-table mapping letter pairs to single letters
This gets accepted in 0.382 seconds here, where I believe you submitted yours (tried four times, impressively always got the exact same time).
[*] In my other answer benchmarking a worst case, actually my solution 3 is fastest.
import sys
from itertools import cycle
from string import ascii_uppercase as abc

table = {(abc[i], abc[j]): abc[(i + j + 1) % 26]
         for i in range(26)
         for j in range(26)}.get

lines = map(str.strip, sys.stdin)
for key in lines:
    if key == '0':
        break
    plaintext = next(lines)

    print(''.join(map(table, zip(plaintext, cycle(key)))))

I did get it down to 0.372 seconds by using sys.stdout.write, but meh, not worth it.
Solution 2: My fastest with str.index:
Here's the fastest I got with str.index, got accepted in 0.699 seconds. Note that my bcd is twice the alphabet and starts with "B", so I can use bcd[p + k] instead of the slower abc[(p + k + 1) % 26].
from string import ascii_uppercase as abc
import sys
from itertools import cycle

index = abc.index
bcd = abc[1:] + abc

lines = map(str.strip, sys.stdin)
for key in lines:
    if key == '0':
        break
    plaintext = next(lines)

    key = cycle(map(index, key))
    plaintext = map(index, plaintext)

    print(''.join([bcd[p + k] for p, k in zip(plaintext, key)]))

Solution 3: O(|key|) Python operations
Since the plaintext has up to 100,000 letters but the key has only up to 1,000 letters, and since Python operations are slow, I also tried doing just O(|key|) Python operations instead of O(|plaintext|) Python operations. By using str.translate. For example if the key is 'KEY', then the entire string slice plaintext[0::3] is translated with the key letter 'K'. And [1::3] and [2::3] get translated with 'E' and 'Y', respectively. Sadly, it was slower, got accepted in 0.985 seconds:
import sys
from string import ascii_uppercase as abc

tables = {c: str.maketrans(abc, abc[i:] + abc[:i])
          for i, c in enumerate(abc, 1)}

lines = map(str.strip, sys.stdin)
for key in lines:
    if key == '0':
        break
    plaintext = next(lines)

    ciphertext = [None] * len(plaintext)
    n = len(key)
    for i, k in enumerate(key):
        ciphertext[i::n] = plaintext[i::n].translate(tables[k])

    print(''.join(ciphertext))

Solution 3b: Using bytearray
Solution 3 but with bytes/bytearray instead of str. Accepted in 0.619 seconds. Not sure whether it's the input/output or the bytearray.translate that's responsible for the speed-up:
import sys
from string import ascii_uppercase as abc

abc = abc.encode()
tables = {c: bytearray.maketrans(abc, abc[i:] + abc[:i])
          for i, c in enumerate(abc, 1)}

lines = map(bytes.strip, sys.stdin.buffer)
write = sys.stdout.buffer.write
for key in lines:
    if key == b'0':
        break
    plaintext = next(lines)

    ciphertext = bytearray(plaintext)
    n = len(key)
    for i, k in enumerate(key):
        ciphertext[i::n] = ciphertext[i::n].translate(tables[k])

    write(ciphertext)
    write(b'\n')


Re-using this piece of code for different objects

How about creating an AddressCollection class that holds all the logic of determining the "visible" addresses:

public class AddressCollection
{
    private ArrayList<Address> items;

    public AddressCollection()
    {
        items = new ArrayList<Address>();
    }

    public AddressCollection(ArrayList<Address> addresses) {
        items = addresses;
    }

    public void add(Address address) {
        items.add(address);
    }

    public ArrayList<Address> getVisibleAddresses() {
        ArrayList<Address> visibleAddresses = new ArrayList<Address>();

        for (Address addr : items) {
            if (addr.getPrivacy().isShowForNonContacts()) {
                visibleAddresses.add(addr);
            }
        }

        return visibleAddresses;
    }

    public ArrayList<Address> getItems() {
        return items;
    }
}

Each model that needs this functionality is reduced to a little boiler plate code, but at least you aren't repeating the basic domain logic:

public class UserProfile
{
    private AddressCollection addresses;

    public UserProfile() {
        addresses = new AddressCollection();
    }

    public void setAddresses(ArrayList<Address> addresses) {
        this.addresses = new AddressCollection(addresses);
    }

    public ArrayList<Address> getAddresses() {
        return addresses.getItems();
    }

    public ArrayList<Address> getVisibleAddresses() {
        return addresses.getVisibleAddresses();
    }
}

public class SomethingElse
{
    private AddressCollection addresses;

    public UserProfile() {
        addresses = new AddressCollection();
    }

    public void setAddresses(ArrayList<Address> addresses) {
        this.addresses = new AddressCollection(addresses);
    }

    public ArrayList<Address> getAddresses() {
        return addresses.getItems();
    }

    public ArrayList<Address> getVisibleAddresses() {
        return addresses.getVisibleAddresses();
    }
}


Amplitude and Frequencies of sound Analyser

This is mostly correct. The reasoning for using delegates is that the class should inform its delegate, not instruct it. A symptom of this is that SoundAnalyser is formatting the text, which should be the responsibility of the view controller.

Consider the SoundAnalyzer to be filling the role of the model in the MVC pattern. The model is only responsible for providing data, and should not be concerned with reinterpreting the data for display.

You can use a helper class to encapsulate formatting if the functionality is needed in multiple places.

Examples

SoundAnalyserDelegate: The delegate methods are in the form of advisory notifications or events, instead of instructions. The delegate receives data, instead of pre-formatted text. This can be further improved by passing an aggregate object if the frequency and amplitude always change at the same time (which seems to be the case):

struct SoundAnalyserSample {
    let frequency: Double
    let amplitude: Double
}

protocol SoundAnalyserDelegate {
    func soundAnalyserSample(sample: SoundAnalyserSample)
    // ... and so on
}

SoundAnalyser: Notify the delegate passing a sample.

func tick(){
    let amp = tracker.amplitude
    let freq = tracker.frequency

    if amp > 0.05 && freq > minimum && freq < maximum {
        let readNote = notesArray![analyseCapturedSound()]
        let sample = SoundAnalyserSample(
            frequency: freq,
            amplitude: amp
        }
        delegate?.soundAnalyserSample(sample: sample)
    }
}

ViewController: The view controller responds to notifications from the sender (the sound analyser in this case), formats the data, and updates the UI. Note that you also need to ensure that the UI update occurs on the main queue, which is not necessarily guaranteed by the caller.

class ViewController: UIViewController, SoundAnalyserDelegate {

    func soundAnalyserSample(sample: SoundAnalyserSample) {
        DispatchQueue.main.async {
            let frequencyText = String(format:"%f", sample.frequency)
            let amplitudeText = String(format:"%f", sample.amplitude)
            frequencyLabel.text = frequencyText
            amplitudeLabel.text = amplitudeText
        }
    }