Specific suggestions:

It is idiomatic to wrap the stuff after if __name__ == "__main__": in a main function.
Rather than the generic data I would suggest figuring out exactly which information you want to attach to each Tree and creating fields for each of them rather than a fully generic list of stuff. This will make it much less painful to work with actual Trees because you can use for example tree.name or tree.counter instead of tree.data[0] and tree.data[1].
You can enumerate a list to loop over it without maintaining a separate index variable, as in for index, child in enumerate(root.children):

In general it'll be much easier to see how to improve this code once it's wired into a production use case rather than example code. The problem with writing code to an example "spec" is that the example inevitably doesn't completely fit the production use case - some crucial features will be missing and others will be superfluous. For example, storing the count of children separately. This information is already encoded in the length of the children list, so you are duplicating the information for no obvious reason. This could conceivably be useful if you're dealing with giant amounts of data, but if your application is sufficiently optimized that this is a real concern you probably should look into other languages or frameworks like numpy or pandas.

General suggestions:

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

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

(The max complexity limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place. Conversely, on an ugly old piece of code I wrote without static analysis support I recently found the complexity reaches 87!)
I would then recommend adding type hints everywhere and validating them using a strict mypy configuration:

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


Implementing `dropJ` to Drop `JoinList` Elements

It's fine, but you have a bug in the Append case, as you completely disregard the right part of the tree:

dropJ i (Append _ left right)
  | i >= leftHt               = dropJ (i-leftHt) right
  | otherwise                 = dropJ i left              -- where is right?
    where leftHt = (getSize. size . tag) left

You can fix this if you use +++ here again:

dropJ i (Append _ left right)
  | i >= leftHt               = dropJ (i-leftHt) right
  | otherwise                 = dropJ i left +++ right
    where leftHt = (getSize. size . tag) left

Other than that we could argue about formatting, but your code is fine. It works. Note that you should add more test cases though. A Arbitrary a => Gen (JoinList m a) generator might come in handy for QuickCheck, but that's left as an exercise.


Querying .NET DataSet and ignore rows that contain NULL

What you have is fine. You could restructure it to eliminate one of the selects, but then you would repeat yourself with the row.

var altIds = myDataSet.Tables[0].AsEnumerable()
                 .Where(row => row.Field<Guid?>("AltId").HasValue)
                 .Select(row => row.Field<Guid?>("AltId").Value)
                 .ToArray();

You could rewrite it in query expression syntax, but that's only less complicated if you find fluent syntax more so.

var altIds = (from row in myDataSet.Tables[0].AsEnumerable()
             let x = row.Field<Guid?>("AltId")
             where x.HasValue
             select x.Value).ToArray();

Either way, it's six in one hand, half a dozen in the other. I find your code readable, and it passes the "does what it is supposed to" test, so I wouldn't worry about this snippet.


Making a scroll function more efficient in jQuery

I don't know if you mean general performance, but one thing I've heard helps a lot is to put all of your different selectors in variables outside of the function as it is apparently pretty expensive to make the selector calls again and again. I mean something like this (and I do mean "something like this" because I haven't tested even the basics, but the general idea is described here: http://www.artzstudio.com/2009/04/jquery-performance-rules/#cache-jquery-objects)

var scroll = {
     primary  : $("#primary-nav-wrapper"),
     front    : $("#primary-nav-wrapper li.front"),
     search_w : $("#primary-nav-wrapper .search-wrapper"),
     search_f : $("#primary-nav-wrapper .search-field"),
     to_top   : $("a#to-top-link")
}
$(window).scroll(function() {
    var scrollT = $(document).scrollTop();
    if (scrollT >= 180) {
        scroll.primary.addClass("scroll");
        scroll.front.addClass("active");

        scroll.search_w.removeClass("active");
        scroll.search_f.blur();
    }
    else {
        scroll.primary.removeClass("scroll");
        scroll.front.removeClass("active");

        scroll.search_f.blur();
    }
    if (scrollT >= 400) {scroll.to_top.addClass("active");}
    else {scroll.to_top.removeClass("active");}
});


BingWallpapers: Fetches and applies the image of the day from Bing as the wallpaper

Pattern matching instead of !!, inlining of single-use names where straightforward.

import Data.List.Split

main = do
  (_:picurl:_):(_:title:_):_ <- map (wordsBy (=='>')) . lines . L8.unpack
    <$> get "http://cdn.muzzammil.xyz/bing/bing.php?format=text&cc=IN"
  putStrLn title
  L8.writeFile "/dev/shm/Bing-Wallpaper" =<< get picurl
  print =<< setWallpaper "/dev/shm/Bing-Wallpaper"


Ruby Beginner - Fuzzy matching / string manipulation

You could consider using Regex to speed up the search. The cleanest way to do so would be to change your full_search.txt to be Regex expressions. For example A?9?AAA would need to be changed to A.9.AAA (in Regex the . means any single character).

Then you could change your full_search method to look like this:

def full_search(offensive_list)
  vrm_list = $all_vehicles.keys.sort
  offensive_examples = offensive_list.map(&:strip)

  offensive_examples.each do |offensive_example|
    vrm_list.grep(/^#{offensive_example}$/).each do |offensive_vrm|
      offensive_found(offensive_vrm, offensive_example)
    end
  end
end

In the Regex the ^ means start of string and the $ means end of string; this basically ensures that substrings are not matched e.g.) abcd matches with the regex .c but not with ^.c$

If you don't want to modify your list, you could so something that dynamically creates the regex in Ruby. For example: offensive_example.gsub("?", ".") this would replace all ? with ..

A couple unrelated pointers...

Ruby has a String#chars method that is (arguably) more readable and might have some minor performance improvements over string.split("").
Instead of assigning an initial empty value and building it in an each, consider using Array#map to reduce the amount of variable reassignments.

# before
vrm_array = []
vrm_list.each do |vrm|
  vrm_array << vrm.split("")
end
vrm_array.each do |vrm|
    # do stuff
end

# after
vrm_array = vrm_list.map { |vrm| vrm.split("") } # this calls `split` on each element in `vrm_list`
vrm_array.each do |vrm|
    # do stuff
end

If you need to take an array of characters and join them together into a single string, consider using Array#join.

irb(main):001:0> ['a', 'b', 'c'].join
=> "abc"

If you have a Hash and you want an empty array if a key doesn't exist, consider using a default value (but be careful with some gotchas related to mutable defaults)

$bad_vrms = Hash.new { |h, k| h[k] = [] } # the argument is the default value which in this case is a block that initializes the key's value to a new instance of an empty array

# now we don't need to check if a key exists and can simply push to it
$bad_vrms[example] << vrm


Cycle detection in undirected graphs with recursive DFS

The code looks clean and organized, but there is an issue with the implementation.
Undirected graph
Consider an undirected graph A - B:

B is neighbor of A
A is neighbor of B

Using the current implementation I would create the graph like this:
Node a = new Node(1);
Node b = new Node(2);

a.add(b);
b.add(a);

Such graph is not cyclic, but the method hasCycleDfs returns true.

unlike other implementations I found on the internet, I used just one
set for the visited nodes (instead of having a set for the visited
nodes and another one for the ancestors)

The reason for the set of ancestors is to handle this case.
Testing

Is good practice to have one method for test case, instead of a single method with all the tests. It will help you pinpoint the failing test quicker without having to look at the code.
Once you have multiple @Test methods, you can clean the state in a method annotated with @Before (@BeforeEach in Junit5) or simply recreate the graph from scratch every time.

Minor improvements

The methods of Node are public unlike the class and instance variables. Use the access modifiers consistently.
In a non‐academic context, the method hasCycleDfs should be private as it needs to be called with and empty set:
boolean hasCycleDfs(Node current) {
    return hasCycleDfs(Node current, new HashSet<>());
}
private boolean hasCycleDfs(Node current, Set<Node> visited) {
    //...
}

Rewrite
Actually, there is no need for a set of ancestors, a pointer to the parent is enough:
boolean hasCycleDfs(Node current, Set<Node> visited, Node parent) {
    visited.add(current);
    for (Node neighbour : current.neighbors) {
        if (!visited.contains(neighbour)) {
            if (hasCycleDfs(neighbour, visited, current)) {
                return true;
            }
        } else if (!neighbour.equals(parent)) {
            // If the node is visited and not parent of
            // the current node, then there is a cycle
            return true;
        }
    }
    return false;
}

And you can use it like:
hasCycleDfs(n1, new HashSet<>(), null);


I would personally write the attribute class as such:

[AttributeUsage(AttributeTargets.Field)]
public sealed class LinkedValueAttribute : Attribute
{
    private readonly Type typeOfValue;

    private readonly Enum value;

    public LinkedValueAttribute(object value)
    {
        this.typeOfValue = value.GetType();
        this.value = (Enum)value;
    }

    public Type TypeOfValue
    {
        get
        {
            return this.typeOfValue;
        }
    }

    public Enum Value
    {
        get
        {
            return this.value;
        }
    }
}

Reasons:

1: the AttributeUsage attribute limits it to going on fields, which, in this case, is the same as an enum member. Without it, the attribute can go onto anything anywhere, and while harmless from the point of the extension method, it is just a bit weird. Signify intent and don't let your users shoot themselves in the foot if you have the means.

2: sealed class. If you see no more functionality being added by subclasses in the future, seal it up. Compiler and JIT can do some optimizations knowing there are no descendants.

3: readonly fields instead of automatically implemented properties. First, signifies intent. Those fields will not be modified after the constructor assigns them. Don't let any future methods in that class noodle them unknowingly. Second, the compiler and JIT may do some optimizations based on knowing the fields will be unmolested after construction.

Now, in your extension method, since you already use LINQ, there's a couple more extensions you can use:

public static class AttributeHelper
{
    public static T GetLinkedValue<T>(this Enum enumValue) where T : struct
    {
        if (!typeof(Enum).IsAssignableFrom(typeof(T)))
        {
            throw new InvalidOperationException("Generic type must be a System.Enum");
        }

        // Look for LinkedValueAttributes on the enum value.
        var attributes = enumValue.GetType()
            .GetField(enumValue.ToString())
            .GetCustomAttributes(typeof(LinkedValueAttribute), false)
            .OfType<LinkedValueAttribute>()
            .Where(a => a.TypeOfValue == typeof(T));

        // A DescriptionAttribute exists; use it.
        if (attributes.Any())
        {
            return (T)(object)attributes.Single().Value;
        }

        throw new InvalidOperationException("No cross-reference LinkedValueAttribute was found for the given value");
    }
}

1: Removed .ToArray() since the LINQ extensions I use don't need an array to work on.

2: Changed attributes.Length > 0 to attributes.Any(). This is primarily to signify intent. You want to know if there are any attributes returned, not particularly interested in the length of the array (that's no longer needed).

3: Changed attributes[0].Value to attributes.Single().Value. Because the default for AttributeUsage is Multiple = false and that's a good thing for the semantics of how it's used - we'll only get either zero or one back.

4: Added the exception throw I mentioned in my comment.

Now, as for the box/unbox... I'm still noodling on that one. I'll update this if/when I get something.

UPDATE I'm still not finding any way around the box/unbox issue. Reflection tricks and casting sorcery is still requiring the object bit.


Reading from file and storing as Linked List

I think you can simplify this. You test for EOF twice.

island* fileReader(FILE *file){
    island *i = malloc(sizeof(island));
    char islandName[20];
    int fileRead = fscanf(file,"%s",islandName);
    if(fileRead != EOF){
        i->name = strdup(islandName);
        i->nextIsland = fileReader(file);
    }
    if(fileRead == EOF) {
        return NULL;
    }
    return i;
}

If you re-arrange this so you only test once:

island* fileReader(FILE *file){

    island *i = malloc(sizeof(island));
    char islandName[20];
    int fileRead = fscanf(file,"%s",islandName);

    if(fileRead == EOF) {
        return NULL;
    }

    i->name = strdup(islandName);
    i->nextIsland = fileReader(file);
    return i;
}

Now that we have re-arranged it. It becomes more obvious that you are leaking i. You create i in the first half but don't use it till the second half (and there is an early return in there).

island* fileReader(FILE *file){

    char islandName[20];
    int fileRead = fscanf(file,"%s",islandName);

    if(fileRead == EOF) {
        return NULL;
    }

    island *i = malloc(sizeof(island));
    i->name = strdup(islandName);
    i->nextIsland = fileReader(file);

    return i;
}

After this re-arrange. Two things stick out.

islandName[20] has a max of 19 characters. This may be OK but you may want to consider not makeing this a limitation. But you should also change your scan statement to make sure you don't exceed this limit.
You don't check the return value of malloc

Code

island* fileReader(FILE *file){

    char islandName[20] = {};

    // Note: %*c is there to read the first space character
    //       after the island name. If the island name is
    //       too long then the read is abandoned (because we
    //       limit it to 19 characters) and only the %19s will
    //       have input and thus the returned value will be 1
    //       (rather than 2 on a successful read)
    int fileRead = fscanf(file,"%19s%*c",islandName);

    // If file name exceeds 20 characters then read (but ignore)
    // any remaining characters in the island name
    if (fileRead == 1) {
        fscanf(file,"%*s");  // Reads upto the next space
    }                        // The * means ignore the input.

    if(fileRead == EOF) {
        return NULL;
    }

    island *i = malloc(sizeof(island));
    // Check to make sure we allocated space.
    if (i != NULL) {
        i->name = strdup(islandName);
        if (i->name != NULL) {
            i->nextIsland = fileReader(file);
        }
        else {
            // If the strdup() failed.
            // Then your object is invalid so release and
            // set i to NULL so it becomes the last one.
            free(i);
            i = NULL;
        }
    }

    return i;
}

The other thing you need to watch out for is the recursion here. This may work well for your test cases. But a huge list of millions of islands is going to eat up your memory. Look to using a loop instead of recursion.

island* fileReader(FILE *file){

    island* head = getNextIsland(file);
    island* last = head;

    while(last != NULL) {
        last->next = getNextIsland(file);
        last = last->next;
    }
    return head;
}

Don't assume that the list is not empty!

void printIslands(island *i){
    printf("%s\n",i->name);          // breaks id i is NULL on first call
    if(i->nextIsland != NULL){
        printIslands(i->nextIsland);
    }
}

When writing recursive routines it is usual to check if you have reached the end as the first thing in the recursive function. Then do the body of the action. You don't need to check the next one as soon as you recurse the next call will then check.

void printIslands(island *i){

    if (i == NULL) {
        return;
    }
    printf("%s\n",i->name);
    printIslands(i->nextIsland);
}

Again do not be lulled into false sense of security by recursion prefer to use a loop.

void printIslands(island *i){

    for(;i != NULL; i = i->next) {
        printf("%s\n",i->name);
    }
}


Speed performance of picking unique value from binary matrix file

Try using seek() instead of a loop that reads 1 value at a time.

import io
import struct

#convert x,y indexes of 2D array into index i of 1D array
#x: index for cols in the 2D
#y: index for rows in the 2D
def to1D(y,x,width):
    i = x + width*y
    return i

def readBinary_as(filename,x,y,file_type,width=3601):
    with open(filename,'rb') as file_data:

        #initialize, how many bytes to be read
        nbByte = 0
        #data type of the file, uint, int, float, etc...
        coding = ''
        if file_type == "signed int":
            nbByte = 2
            coding = '>h'  #2B Signed Int - BE

        if file_type == "unsigned int":
            nbByte = 2
            coding = '>H' #2B Unsigned Int - BE

        if file_type == "unsigned byte":
            nbByte = 1
            coding = '>B' #1B Unsigned Byte - BE

        if file_type == "float":
            nbByte = 4
            coding = '>f' #4B float32 - BE

        #index of my value in 1D array
        i = to1D(y,x,width)
        offset = i * nbByte

        # seek to byte offset of desired data
        file_data.seek(offset)

        #read and save the picked value
        my_value_pos = file_data.read(nbByte)
        val = struct.unpack(coding,my_value_pos)[0]
    return val


You correctly identified that you need to count the number of lowercase c and d. But using a set to do so is not the right tool. Instead, I suggest using collections.Counter:

from collections import Counter

def color(genotype):
    assert len(genotype) == 4

    count = Counter(genotype)
    blue = count['d'] == 2
    chocolate = count['c'] == 2

    if blue and chocolate:
        return 'lilac'
    if blue:
        return 'blue'
    if chocolate:
        return 'chocolate'
    return 'seal'

I also added a debug check to ensure that the length of the input sequence is always four.

Given the mini debate that occured in the comments, pertaining to variable names, you may consider this slight variation:

from collections import Counter

def color(genotype):
    assert len(genotype) == 4

    count = Counter(genotype)
    recessive_traits = [count[gene] == 2 for gene in 'cd']

    if all(recessive_traits):
        return 'lilac'
    if recessive_traits[0]:
        return 'blue'
    if recessive_traits[1]:
        return 'chocolate'
    return 'seal'

It may be more expressive as to what you're testing, and why.


T-SQL Hmac (Rfc2104 SHA2_256) Implementation

Looks OK to me, without knowing Transact SQL anyway. Some things to consider:

obviously this implements just HMAC-SHA256, so the function should be named that way;
the key parameters is 8000 varbinary max value. That seems largish to me (although it might not matter much as the size is variable anyway);
there is no way to perform a hash over multiple fields in the DB which might be a use case (no incremental update possibility);
similarly, often it is required to reuse the key for multiple calculations, in that case you can cache the Pads.i and Pads.o values.

I'm also missing some constants being introduced but that might be due to the nature of TSQL.

Don't forget to test against NIST test vectors, just to be sure.


I am not sure which framework you are using, but this is how you could do it using Scala´s native XML library:

 { for (row <- months grouped 3) yield (
 { for (month <- row) yield ( {month} 	) }
) }

Rendered slightly more prettily, the code looks like this:

for (row <- months grouped 3) yield {

  { for (month <- row) yield ( {month} 	) }

}

Which hopefully makes the structure clear.

If your framework works with yield, all you need to do is add @ in the appropriate places.  If it does not, you might have to do something like this:

for (row <- @months grouped 3) {

  for (month <- @row) {
     @month
  }

}

Your code is structured only around months, so has to use conditional logic to create your rows.  My code is structured around rows (and within that around months), so needs no conditionals.  My code also only has the value for the number of months in one place, which is less error prone and makes it easier to change the number of months in a row.

You don't have to use a list comprehension, though.  The important thing is simply to slice the list up into groups of 3 (or n, where n is the number of months you want in each row) and iterate over those.


Bugs.

The loop printing the histogram lines for numbers,

for(int i = 0; i <= 10; ++i)

lets i become 10, which accesses num[10]. It does not exist. Undefined behavior it is.

A c idiom is to use < in a loop termination condition. There are cases which require <=, but they are very rare.

The loop printing the histogram lines for letters,

for(int i = 0; i <= 10; ++i)

only reports counters for a to k inclusive. All other letters are not reported.
The second bug tells why magic numbers are bad. You want to report all counters in the lett array. There are sizeof(lett) / sizeof(lett[0]) of them:

    for(int i = 0; i < sizeof(lett) / sizeof(lett[0]); ++i)

Ditto for num.
It is very unclear why you split handling letters into three cases. A simple

    else if (isalpha(ch)) {
        ch = tolower(ch); // No need to test for `isupper`
        ++lett[ch - `a`];
    }

is enough.
There are more whitespaces than ' ', '\n', '\t'. The ctypes.h has isspace function. Use it.
Testing for nwhite - i > 0 is yet another manifestation of why <= loop condition is wrong.

    for(int i = 0; i < nwhite; ++i) {
        putchar('*');
    }

is all you need.
Once you fix the last two loops, all the loops doing an actual printing become identical. Factor them out into a function

void print_stars(int n)
{
    for (int i = 0; i < n; i++) {
        putchar('*');
    }
    putchar('\n');
}


Grade of Service Probability Function Python

Pure Python

You should use a for loop rather than a while loop.
You can use a generator comprehension to build all prob's.
You can use sum to get the sum.

def grade_of_service(n, p, c):
    return sum(binom(n, k)*(p**k)*((1-p)**(n-k)) for k in range(c+1, n+1))

Numpy and friends

Use numpy.arange rather than range.
Write out the equation same as above, just not in a comprehension.
Change sum to numpy.sum.

import numpy

def grade_of_service(n, p, c):
    k = numpy.arange(c+1, n+1)
    return numpy.sum(binom(n, k)*(p**k)*((1-p)**(n-k)))

This has a problem with numbers that exceed a certain size, as numpy numbers are finite.


Since you are repeatedly using $(date +\%F-\%T), you can store that as a variable (unless you want to also know how long it took the script to jump between statements). Use that variable instead.

Similarly, set a basepath, which in your case, is /var/www/html. In case it changes in the future, it'll be just enough to change it in one place.

At the end, you have

rm -rf db-$(date +\%F-\%T).zip html-$(date +\%F-\%T).zip

which will try to delete those files from CWD, which might not be the same as /var/www/html.

mysqldump has options such as --compact and --compress. Making use of them will result in smaller sql files, resulting in even smaller zips; saving you some disk space.


Paper-scissors-stick-stone game in Python

So instead of this part of your code

    else:
        if mychoice == 1:
            return 'paper'
        elif mychoice == 2:
            return 'scissor'
        elif mychoice == 3:
            return 'stick'
        elif mychoice == 4:
            return 'stone'
        else:
            print('Invalid choice. Enter again.')

you may first create that recommended dictionary

allowed_choices = {1: "paper", 2: "scissors", 3: "stick", r: "stone"}

and then replace you code with

    else:
        if mychoice in allowed_choices:
            return allowed_choices[mychoice]
        else:
            print('Invalid choice. Enter again.')

The part mychoice in allowed_choices checks only in keys of the allowed_choices dictionary (so it checks if it is 1, 2, 3, or 4).

The part return allowed_choices[mychoice] returns the value of mychoice key (e. g. "stick" for the key 3).


So, about all those globals. They make your code really hard to read, I have almost no idea what is going on (after having read it twice). The general recommendation is to only use global objects if you really have to. Otherwise pass the objects either as arguments to the function, or write a class which has the relevant variables as attributes and keep the state like this.

Another thing that makes your code a lot easier to understand (both for other people and for yourself in two months time), are docstrings, which document what each function does, the parameters it takes and what it returns or modifies.


While working on the stack you are using stack.extend. You can also use this in the part where you add the immediate subclasses.
There is no need to check if a list is empty before using extend, if it is empty it will just do nothing.
If you don't need the exception, just don't catch it with as _.
Not sure if you should be doing if cls is type instead of if cls == type.

def all_subclasses(cls):

    if cls == type:
        raise ValueError("Invalid class - 'type' is not a class")

    subclasses = set()

    stack = []
    try:
        stack.extend(cls.__subclasses__())
    except (TypeError, AttributeError) as ex:
        raise ValueError("Invalid class" + repr(cls)) from ex

    while stack:
        sub = stack.pop()
        subclasses.add(sub)
        try:
            stack.extend(sub.__subclasses__())
        except (TypeError, AttributeError):
           continue

    return list(subclasses)

One way to optimize this further is to make sure you don't visit a class multiple times:

    while stack:
        sub = stack.pop()
        subclasses.add(sub)
        try:
            stack.extend(s for s in sub.__subclasses__() if s not in subclasses)
        except (TypeError, AttributeError):
           continue

This should prevent having to visit (almost) every class twice with convoluted hierarchies like this:

    A
  /   \
 B     C
  \   /
    D
 / | | \
E  F G ...


You may see a performance increase by adding multithreading support. For each row, create an instance of a custom Runable that takes the five values and add it to a ThreadPoolExecutor. You can futz around with the size of the pool. As with all performance enhancements, you'll need to test, test, test to make sure you're seeing a real benefit, and you'll really need to test on a production clone for it to have any meaning. It may not make a difference on your local machine but be a big help on production, or vice versa.

Your use of the StringBuilder as opposed to just concatenation is probably not doing you any good. Compilers will do that work, and the code is harder to read as-is. There are other things to pick at, but none of them are performance-related.


I'm going to be bold and review my own code having spent the last hour refactoring it.

The original implementation had bugs. Sometimes less than 10 ladders were placed. This is because the algorithm did not check to see if there was a ladder already present at the current insertion point.

# Tough luck if start_point is 10 and there's already a ladder there
begin
  start_point = rand(ladder_habitable_range)
end while snakes.keys.include?(start_point)

The best way to ensure a bullet proof implementation is to avoid having a square contain more than one object. For example, there's an edge case where a square can contain a ladder's head and a tail, causing you to progress even further.

To do that, the placement should be delegated to a method that checks if the square is occupied. This requires tweaking the initialize method, but it's worth it:

  def place_point(range = habitable_range)
    begin
      point = rand(range)
    end while occupied?(point)
  end

  def occupied?(number)
    [snakes.keys, snakes.values, ladders.keys, ladders.values].flatten.include?(number)
  end

Doing so means the placement methods for ladders and snakes only have to worry about working out the range and populating their respective hashes, which are the only two differences between them. This reduces duplication.

  def place_snakes(count)
    count.times do
      start_point = place_point
      end_point_range = habitable_range.begin..(start_point - 1)

      snakes[start_point] = place_point(end_point_range)
    end
  end

Finally The habitable range for ladders and snakes is the same, so this can be replaced with a single range 1..(size - 1):

def snake_habitable_range
  2..(size - 1)
end

def ladder_habitable_range
  1..(size - 1)
end

Behold! My new implementation.

class World
  attr_reader :size, :snakes, :ladders

  def initialize(size, snakes = 10, ladders = 10)
    @size = size
    @snakes, @ladders = {}, {}
    place_snakes(snakes)
    place_ladders(ladders)
  end

  def place_snakes(count)
    count.times do
      start_point = place_point
      end_point_range = habitable_range.begin..(start_point - 1)

      snakes[start_point] = place_point(end_point_range)
    end
  end

  def place_ladders(count)
    count.times do
      start_point = place_point
      end_point_range = (start_point + 1)..habitable_range.end

      ladders[start_point] = place_point(end_point_range)
    end
  end

private

  def place_point(range = habitable_range)
    begin
      point = rand(range)
    end while occupied?(point)
  end

  def occupied?(number)
    [snakes.keys, snakes.values, ladders.keys, ladders.values].flatten.include?(number)
  end

  def habitable_range
    1..(size - 1)
  end
end


A class that uses a few other classes to generate an email

I find it weird that you wrote this as a module rather than as a class.

How is this code going to be called?  Mail.new(user_id).send, I assume?  It doesn't seem to make much sense to call #send twice on the same object.  So, really, there isn't any point to make an object at all.  You could just as well define a function.

def send_mail_to_user(user_id)
  user = User.find(user_id)
  client = user.mailchimp
  campaign_id = client.create_campaign(user.detail.create_campaign_params)
  client.create_campaign_content(campaign_id, user.detail.create_content_params)
  client.send_campaign(campaign_id)
end


Is this the best way to check sorting (in recursion) without loops?

Based on the naming guidelines methods should be named using PascalCase casing.

If you evaluate two conditions connected by && you should always evaluate the faster one first. You can return the result of the condition directly.

This can be reached if you forget the temp variable and rearange the condition like

static bool isSortedArray (int[] ar, int length)
{
    if (length == 0)
    {
        return true;
    }

    return ar[length - 1] <= ar[length] && isSortedArray(ar, length - 1);
}

You should also take care of the posibility that ar will be null or that the number of elements is smaller than length.

Using braces {} for single if..else statements will make your code less error prone.

ar as a parametername is not well choosen. You shouldn't shorten parameter names.

isSortedArray should be better named IsArraySorted.

A construct like

if (condition)
{
    return true;
}
else
{
    // more code here
}

will always make the else redundant because if the condition is true it will never be reached.


Parsing Oracle errors with a ksh function

It seems like you might find this clause helpful:

WHENEVER SQLERROR EXIT SQL.SQLCODE


Your functions shouldn't depend on variables but use specified
parameters. You always specified variables before calling your function instead of just specifying them as parameters, e.g:

DIR=Box1
Host=192.168.1.100
mnt

but you can easily write it as

mnt Box1 192.168.1.100

I would also only parse your command line arguments in one place and create
a dedicated function for determine the appropriate ip address for your hosts.

I would also remove the ls call from your mnt function as mnt doesn't do what the name suggests. But this is a rather minor issue and I didn't change it in my code.

#!/bin/sh
# mount boxes by SSHFS

usage () {
    cat <<EOF
sshmnt -[c,s,u,h]
      -c Box1
      -s Box2
      -u unmount
      -h print this message

EOF
}

mnt(){

    if [ $# -ne 3 ] ; then
       echo "Wrong parameters for mnt - host dir port" >&2
       return 1
    fi

    host="$1"
    dir="$2"
    port="$3"
    sshfs jason@"$host":/home/jason /media/"$dir" \
    -C -p "$port" \
    -o reconnect,IdentityFile=/home/jason/.ssh/id_rsa \
    && ls /media/"$dir"
}

umnt(){
    dir="$1"
    fusermount -u /media/"$dir"
}

get_host(){
    # check if on LAN
    lan="$(ip addr | grep .102/)"

    if [ -z "$lan" ] ; then
        echo XXX.XXX.XXX.XXX
        return 0
    fi

    case "$1" in
        Box1) echo 192.168.1.100 ;;
        Box2) echo 192.168.1.200 ;;
        *) echo "Unknown Parameter" >&2 && return 1 ;;
    esac
}

case "$1" in
    -c) mnt $(get_host Box1) Box1 port ;;
    -s) mnt $(get_host Box2) Box2 port ;;
    -u)
        mount | grep Box1 && umnt Box1
        mount | grep Box2 && umnt Box2
        ;;
     *) usage && exit 1;;
esac

Another suggestion is to get rid of all your hard coded paths and texts like, /media/, /home/jason/ and jason and replace them with variables, e.g:

MOUNT_PREFIX=/media/
SSH_KEY=/home/jason/.ssh/id_rsa
MOUNT_SOURCE=/home/jason

and just specify the user for your hosts in ~/.ssh/config


Adding file name information to CSV file columns

Assuming you commented out the second file generation of these two:

GET-CONTENT (GET-CHILDITEM "E:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\*.out") | out-file -encoding "UTF8" "C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\CBM-FS3.txt"

GET-CONTENT (GET-CHILDITEM "C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS56\*.out") | out-file -encoding "UTF8" "C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS04\CBM-FS04.txt"

You can combine the above lines using the -LiteralPath parameter to Get-ChildItem, like so:

GET-CONTENT (GET-CHILDITEM -LiteralPath 'E:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\*.out', 'C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS56\*.out') | out-file -encoding "UTF8" "C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\CBM-FS3.txt"

If that's not what you're looking for or you need more input, just let me know and I'll update my answer accordingly.


Beautify your regex
Say No to Pattern.compile and instead of

 Pattern.compile("^((?!(\\{.*\\})).)*$")

use scalish way:
 "^((?!(\\{.*\\})).)*$".r

Say No to \\ in regex and instead of

"^((?!(\\{.*\\})).)*$"

use """ way:
"""^((?!(\{.*\})).)*$"""

Return values without val/var
You can simply write your containsTag without val and result of last line will return from function - it will return your's matches:
def containsTag(text: String): Boolean = {
  ! """^((?!(\{.*\})).)*$""".r.matches(text)
}

Choose your destiny
Sometimes it is good to use if/else but more readable match/case:
containsTag(text) match {
  case true =>
    val randomPosition = Random.nextInt(allCharacters.length - 1)
    text.replace("}", allCharacters(randomPosition).toString)
  case _ =>
    text
}

Feel the power
Collect it all together:
  val allCharacters = "qwertyuiopasdfghjklzxcvbnmQWERTY" +
    "UIOPASDFGHJKLZXCVBNM1234567890!@#%*()_+-=[]{x}|?.;:`"

  def removeTags(text: String): String = {

    def containsTag(text: String): Boolean = {
      ! """^((?!(\{.*\})).)*$""".r.matches(text)
    }

    containsTag(text) match {
      case true =>
        val randomPosition = Random.nextInt(allCharacters.length - 1)
        text.replace("}", allCharacters(randomPosition).toString)
      case _ =>
        text
    }
  }

  val res = removeTags("my friendly {name} is $userNickname$")

For random chars
According to answer in Replacing characters in a String in Scala you can use construction without while loop but with map + lambda like in code below:
  val allCharacters = "+=-?"

  def removeTags(text: String): String = {

    def containsTag(text: String): Boolean = {
      ! """^((?!(\{.*\})).)*$""".r.matches(text)
      true
    }

    containsTag(text) match {
      case true =>
        text.map(
          (c) => c match {
            case '{' =>
              val randomPosition = Random.nextInt(allCharacters.length - 1)
              allCharacters(randomPosition)
            case c => c // for another char which is not == {
          }
        )
      case _ =>
        text
    }
  }

Then it will be good to divide functionality and create new Char => Char transformer function from anonymous (c) => c match {..} which we lay in text.map(...):
//...
def replaceRandom(c: Char): Char = {
  c match {
    case '{' =>
      val randomPosition = Random.nextInt(allCharacters.length - 1)
      allCharacters(randomPosition)
    case c => c
  }
}

containsTag(text) match {
  case true => text.map((c) => {replaceRandom(c)})
  case _ => text
}
//...

Simplify code in two parts.
Part 1: simplify match/case in replaceRandom(c: Char): Char :
def replaceRandom(c: Char): Char = {
  c match {
    case '{' =>
      val randomPosition = Random.nextInt(allCharacters.length - 1)
      allCharacters(randomPosition)
    case c => c
  }
}

// remove unneeded "{" and "}"
def replaceRandom2(c: Char): Char = c match {
  case '{' =>
    val randomPosition = Random.nextInt(allCharacters.length - 1)
    allCharacters(randomPosition)
  case c => c
}

Then part 2: simplify map((c) => {replaceRandom(c)}):
containsTag(text) match {
  case true => text.map((c) => {replaceRandom(c)})
  case _ => text
}

//remove unneeded "{" and "}"
containsTag(text) match {
  case true => text.map((c) => replaceRandom(c))
  case _ => text
}

//remove unneeded "(c)" to wildcard "_"
containsTag(text) match {
  case true => text.map(replaceRandom(_))
  case _ => text
}

//remove unneeded wildcard "_"
containsTag(text) match {
  case true => text.map(replaceRandom)
  case _ => text
}

Feel the power again
So for your task i will chose that variant: all functions are divided, logic placed is simple if/else and now good readable (as you see now it good readable also with if/else as i wrote to you above). After, when logic will grow you can use instead if/else match/case.
  def removeTags(text: String): String = {

    def containsTag(text: String): Boolean = {
      ! """^((?!(\{.*\})).)*$""".r.matches(text)
      true
    }

    def replaceRandom(c: Char): Char = c match {
      case '{' =>
        val randomPosition = Random.nextInt(allCharacters.length - 1)
        allCharacters(randomPosition)
      case c => c
    }

    if (containsTag(text))
      text.map(replaceRandom)
    else text

  }

  val allCharacters = "+=-?"
  val e = "my fr{{{iend{{{ly {{name} is $userNickname$"
  println(removeTags(e))

P.S. or place to think

Maybe your regex not working? Check it at: Regex101
Why you need to replace } symbol with another random from allCharacters  which can be also }?
The bad, the good and the !: maybe try to rewrite your !noTagsRegex to noTagsRegex? It can be more readable for another people.

Also i want to see additions to my review too, that code is too verbose, so welcome!


Looking quickly over your code here are a couple of the changes I would make:

First, I would add a class to your application (probably within the levelbuilder.scala file) that encapsulates the (Int, Int) tuple you are using throughout this code snippet. E.g.

    case class Pos(x: Int, y: Int) {
      def neighborhood: List[Pos] = {
        Pos(x + 1, y) :: Pos(x - 1, y) :: Pos(x, y - 1) :: Pos(x, y + 1) :: Nil
      }
    }

When building this class I also took the chance to rewrite the method called around(pos: (Int, Int)) from the LevelBuilder class to a more concise method which I've called neighborhood just to differentiate it.

Also, if you haven't had a chance to read-up on case classes in Scala, now would be a good time to do so :) They provide a lot of functionality with just a few lines of code.

Now you may declare the LevelBuilder fields rooms and possibilities like so:

    val rooms = scala.collection.mutable.HashMap[Pos, Room]()
    var possibilities = List[Pos]()

One place that these changes drastically add to readability in your code is in the debug() method:

    def debug(): Unit = {
      val possibilePos = rooms.keys ++ possibilities

      val minY = possiblePos.minBy(_.y).y
      val maxY = possiblePos.maxBy(_.y).y
      val minX = possiblePos.maxBy(_.x).x
      val maxX = possiblePos.maxBy(_.x).x

      // print map
    }

Notice also that I changed miny to minY etc.


Travelling salesman using brute-force and heuristics

I enjoyed the first look at the code as it's very clean, you have
extensive docstrings and great, expressive function names.  Now you know
the deal with PEP8, but except for the one 200 character long line I
don't think it matters much really.

There're a few typo with the wrong spelling "algoritmh".

The coordinates should be immutable 2-tuples.  The reason being the
safety of immutable data-structures.  YMMV, but that makes it really
obvious that those are coordinates as well.

optimized_travelling_salesman should make a defensive copy of
points, or you should otherwise indicate that it's destructive on that
argument.

Instead of if start is None: start = points[0] you could also use
start = start or points[0] to save some space while still being
relatively readable.

For the algorithms the only thing I'd is not to use square root if you
don't have to.  You can basically create a distance_squared and use that
instead of distance because the relationship
between a smaller and bigger distance will stay the same regardless.
That doesn't apply for the final output of course. Edit: And, as mentioned below by @JanneKarila, you can't use that for the brute-force version.


Reverse Groups challenge at CodeEval.com

It's pretty simple task and I think code does its job well. I would point couple minor style issues:

You don't need to use objectAtIndex method to access elements inside an array. elementsArray[i] is enough and it's more readable.
You can access count property using dot-notation - array.count. Again, it's more readable.
Combining result string from array looks cumbersome and complicated. And rely on description property. Why don't you create result string as you go without having to create temp array first?
You are dividing line into lineArray. Then you're accessing first and last element using lastObject and objectAtIndex:0. I would prefer to use either [0] and [1] or lastObject and firstObject.
Pass the code through standard Xcode formatter to clean up spacing and indentation.


Is there a way to avoid calling the document with jQuery on click?

I'm not sure this question really fits into the site but I'm going to answer it anyway.

Since the elements don't exist when the page is loaded you can't add a click event to it (yet).  If you try to attach the event handler directly to the elements at this time it won't do anything since the elements don't exist.  So instead you attach the click element to the document element (which does exist) and then when the click handler is fired (with a click anywhere on the document) it looks to see if the click event was done on an object that matched the selector you entered at that point.  If it was then the click handler is fired.

That was confusing even to me.  Let me try a different way.

Option 1

Attempt to attach the event handler to the actual element on page load using the selector.

$('.class-name').on('click', function(){})

The element does not exist yet so this does nothing.

Option 2

Attach the event handler to a static element and provide a delegated selector to test for when the item is clicked.

$(document).on('click','.class-name', function(){})

This event handler is successfully added to the document object.  Now when any click happens within the document, the selector is tested and if a match the function is fired.
No, but you need to use a static element.  I used the document but it could be any static element as long as all dynamic elements will be contained within.  In your case it might be something like $('.header-shopping-cart-items').on('click', '.item a', function() {}) provided the .header-shopping-cart-items container were static (always there).

Another option, although much more difficult and probably not worth the effort would be to attach the event handler directly to the item row when you inject it.  I wouldn't recommend that approach.
You could look into putting this into a module and calling that module when needed.  But I don't know that you would be gaining anything by putting this into a IIFE.   And I wouldn't say that IIFEs are preferred over the jQuery.ready function.  That said, this whole code could probably be put into a IIFE without any changes.  You would just need to put it at the bottom of the document.


Given a shape, return all triangles that can be formed

No, it doesn't mean \$O(n!)\$ complexity.  The \$(n-r)\$ in the denominator cancels most of the terms in the numerator.  For choosing three points to make a triangle, \$r\$ = 3, and so your actual expression is \$\frac{(n)(n-1)(n-2)}{3!}\$ => \$\frac{(n^3-3n^2+2n)}{3!}\$ => \$O(n^3)\$.

So you should expect \$O(n^3)\$ time, and \$O(3*n^3)\$ => \$O(n^3)\$ space.

Next thought - if you are going to be working with triangles, you need to know where the points are (so that you can check whether or not the points are co-linear).  What your code currently does is seek out every 3-tuple combination of vertices; so you are (possibly) missing part of the problem.

That said, breaking the triangle problem into two distinct pieces is a good idea; because you do need to enumerate the vertices anyway, and treating them as ordered tuples gives you a good way to avoid extra work.

But trying to enumerate the tuples using recursion... that's a bad idea.  Better would be to simply enumerate the combinations using squashed ordering.  Thomas Andrews has a nice illustration of that technique on a more complicated problem.


Web API should not be bound to a particular UI

API calls should not bound to a user interface requirement, so that it could be used in multiple places without any addition requirement. In the above code, it is returning a list of dropdownlist values rather than a list of entities.

Your controller code may look like this:

public class ConstantsController : ApiController
{
    private readonly IConstantRepository _constantRepository;

    public ConstantsController(IConstantRepository constantRepository)
    {
        _constantRepository = constantRepository;
    }

    [Route("Constants/City")]
    [HttpGet]
    public IEnumerable<City> GetCity()
    {
        return _constantRepository.GetCity();
    }

    [Route("Constants/Country")]
    [HttpGet]
    public IEnumerable<Country> Country()
    {
        return _constantRepository.GetCountry();
    }
}

Note: I am using Web API 2 for this code.

This code can be used by any kind of application like this:

  http://yoururl/Constants/Country

Use a DI container to inject dependencies into your controller

Use Unity or a simple injector to inject dependencies. It will help you to isolate components.

public interface IConstantRepository
{
    IEnumerable<City> GetCity();

    IEnumerable<Country> GetCountry();
}

Also, include unit tests in your applications.


Enormous Input Test - reducing program runtime

The main reasons are

Scanner is pretty slow
System.in is unbuffered

By using a BufferedReader instead of the Scanner you get it to barely acceptable levels. The following approach runs in roughly 8.2 seconds and get's accepted.

public class Main {
    public static void main(String args[]) throws java.io.IOException {
        java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in);
        java.io.BufferedReader br = new java.io.BufferedReader(isr, 16 * 1024);
        String[] line0 = br.readLine().split(" ");
        int n, k, m = 0;
        n = Integer.parseInt(line0[0]);
        k = Integer.parseInt(line0[1]);
        for (int c = 0; c < n; c++) {
            if (Integer.parseInt(br.readLine()) % k == 0)
                m++;
        }

        System.out.println(m);
    }
}

But it's still really slow compared to the top scoring solutions that run in under 2 seconds.

I've got it down to a bit over 2 seconds by reading into a byte[] buffer and doing custom number parsing based on that buffer roughly like the following incomplete piece (which just prints the parsed numbers)

public class Main {
    public static void main(String args[]) throws java.io.IOException {
        byte[] buffer = new byte[16 * 1024];
        int currentNumber = 0;
        boolean inNumber = false;
        int read;
        while((read = System.in.read(buffer)) >= 0) {
            for (int i = 0; i < read; i++) {
                char c = (char) buffer[i];
                if (c >= '0' && c <= '9') {
                    inNumber = true;
                    currentNumber = currentNumber * 10 + (c - '0');
                } else if (inNumber) {
                    inNumber = false;
                    System.out.println("I've read number: " + currentNumber);
                    currentNumber = 0;
                }
            }
        }
    }
}

See http://ideone.com/lQ4ImB for above code with input

The reason why this is so much faster is basically that there is almost 0 overhead in reading & parsing the input into numbers. BufferedReader in comparison is transforming each line into a String (thus creating a new Object), then parses that String. Above approach allocates no new Objects besides the single byte[] buffer.


Find unique characters and count non unique characters

A simple and pythonic way to accomplish this is using collections.Counter. It's an easy way to count elements in an iterable. Have a look:

from collections import Counter

def unique_letters(string: str) -> str:
    """
    Finds all the unique/non unique letters in the string
    """
    letters = Counter(string)

    unique = [key for key in letters if letters[key] == 1]
    non_unique = {key: letters[key] for key in letters if letters[key] > 1}
    return f"Unique: {unique} | Not Unique: {non_unique}"

This also takes advantage of f-strings, allowing you to directly implement variables into your strings. It's a personal preference, but to me it looks a lot nicer than using .format().


Don't repeat yourself

Your method has the same code duplicated twice in it. You should always try to eliminate this kind of duplication, for example like this:

def addlists(LL1, LL2):
    return sumlist(LL1) + sumlist(LL2)

def sumlist(LL1):
    storage = []
    multiplier = 1
    total = 0
    while LL1 != None:
        storage.append(LL1.data)
        LL1 = LL1.next
    for i in storage[::-1]:
        total += i*multiplier
        multiplier *= 10
    return total

Simplify

The logic can be simplified, a lot:

def sumlist(ll):
    total = 0
    while ll:
        total *= 10
        total += ll.data
        ll = ll.next
    return total

I also simplified the None comparison, instead of if ll != None you can write simply if ll

Naming

The convention is to use lowercase variable names, so it would be better to change LL1 and LL2.


It's still closer to C than C++ IMO.
First of two non C++ issues:

You don't encapsulate your classes. Your whole interface is public. Thus you are now doomed to forever maintain this interface for eternity. Additionally it allows other people to accidentally modify your structure. Use the C++ class system to encapsulate your objects and at least protect your objects from accidental miss use.

Your tree-traversal actually depends on the node object to track traversal. Now that's a bad design thing. You are basically binding yourself to an implementation and limiting the usability of your code. You should most defiantly look up the Visitor Pattern.

The rest are C++ issues:
You are doing resource management manually:
nodes = new GraphNode[numNodes];
// STUFF
nodes[i].adjList = new int[nodes[i].degree];

It would be better to use a std::vector at least that would be exception safe in controlling the resource:
std::vector<GraphNode>   nodes(numNodes);

You are manually loading nodes. Should a node not know how to stream itself onto and off a stream?
    digraph >> nodes[i].nodeName >> ignore >> nodes[i].degree >> ignore;

I would expect it to look like this:
    digraph >> nodes[i];

Or even better create items and push them into the vector:
Since the only thing that seems to be in the file "digraph.data" seem to be GraphNodes then you could do something like this:
std::copy(std::istream_iterator<GraphNode>(digraph),
          std::istream_iterator<GraphNode>(),
          std::back_inserter(nodes)  // Assuming nodes is a vector described above.
         );

This is not C++
    printf("%d (%d): ", nodes[i].nodeName, nodes[i].degree);

The problem with the printf style is that it is not type safe. The main advantage C++ has over C is the exceptional type safety of the language. Use this to your advantage.
This is so bad I nearly swallowed my tounge.:
                swap(int, nodes[i].adjList[j], nodes[i].adjList[k]);

You have #defined swap.

Use all caps for macros.
The reason is to make sure macros do not clash with any other identifiers.
Macros are not type safe.
If there was a conversion from this object to int the compiler will now happily do it.
There is already a type safe macro as part of the standard library.
If you want to override the default swap behavior you just need to rewrite your type specific version and Koenig lookup will automatically find it.

Not a big deal but prefer pre-increment. The reason is it does not matter for POD types but for user defined types it does (or potentially does) matter. If a maintainer at a latter stage changes the type of the loop variable then you don't have to go and change any of the code the pre-increment is already the correct type.
 for (int i = 0; i < 30; ++i)
                      // ^^^^ Prefer pre-increment here

Don't declare multiple variables on the same line:
int nextNode, dfLabels[numNodes], nextToVisit[numNodes], parents[numNodes], lastDFLabel = 0;

Every coding standard is going to tell you not to do it. So get used to it. Technically there are a few corner cases that will come and hit you and putting each variable on its own line makes it easier to read. Also note it looks like you are initializing all values to zero. That's not happening so all of these (apart from the last one) are undefined.
Also defining arrays with a non cost type is not technically allowed.
dfLabels[numNodes],

Some compilers allow it because it is C90 extension. But its not really portable. Use std::vector (or std::array) instead.
Don't put code on the same line as the close braces.
I dobt anybody is going to like that style even the people that want to save vertical line space.
} for (int i = 0; i < 30; i++) printf("-");

And I prefer to put the statement the for loop is going to run on the next line so it is obvious what is happening (but I am not going to care that much about it).
typedefing a structure is not needed in C++
typedef struct {
   // BLAH
} GraphNode;

This is just
struct GraphNode
{
   // BLAH
};

When you loop over your containers you are using a C style (ie you are using an index). It is usually more conventionally to use an iterator style to index over a container (even a simple array). Thus if you ever choose to move to another style of container the code itself does not need to be changed. The iterator style makes the code container agnostic.
Personally I don't think it is a big deal. In this limited context.
    for (int j = 0; j < nodes[i].degree; j++)

You implement (badly) a sort function:
    for (int j = 0; j < nodes[i].degree; j++)
        for (int k = 0; k < j; k++)
            if (nodes[i].adjList[j] < nodes[i].adjList[k])
                swap(int, nodes[i].adjList[j], nodes[i].adjList[k]);

Lets just say in both C/C++ you should probably use the built-in sorting algorithms:
std::sort(&nodes[i].adjList[0], &nodes[i].adjList[nodes[i].degree]);

Or am I reading your intention here incorrectly? Is it some sort of randomizing feature? Either way you should have probably documented this to explain what you are trying to achieve!
Here is a more C++ like version
#include <vector>
#include <map>
#include <iterator>
#include <stdexcept>
#include <fstream>
#include <iostream>

class GraphVisitor; // We will implement the `Visitor Pattern`
class Graph
{
    public:
    class GraphNode
    {
        public:
            // Allows us to visit each node.
            // Don't need to track progress via modifying the node
            void accept(GraphVisitor& visitor);
        private:
        // The streaming operators are defined so we can freeze and thaw data to a stream
        friend std::istream& operator>>(std::istream& stream, Graph::GraphNode& node);
        friend std::ostream& operator<<(std::ostream& stream, Graph::GraphNode const& node);

        // The data is private nobody actually needs to see this
        int                 nodeName;
        std::vector<int>    link;
    };

    // Graph knows how to implement depth first traversal.
    // External entities can't do this because that requires knowledge of the implementation
    void DepthFirstTraversal(size_t startNode);

    private:
        // The streaming operators are defined so we can freeze and thaw data to a stream
        friend std::istream& operator>>(std::istream& stream, Graph& node);
        friend std::ostream& operator<<(std::ostream& stream, Graph const & node);

        // The data is just the nodes
        std::vector<GraphNode>  nodes;

};
// A visitor is easy
// When you only have one node type.
// So we just have one visit method.
class GraphVisitor
{
    public:
        virtual ~GraphVisitor() {}
        virtual void visit(Graph::GraphNode& node, int name, std::vector<int> const& links)    = 0;
};

// All the node does with the visitor is tell it that it can visit.
void Graph::GraphNode::accept(GraphVisitor& visitor)
{
    visitor.visit(*this, nodeName, link);
}

// Stream Nodes
std::ostream& operator<<(std::ostream& stream, Graph::GraphNode const& node)
{
    stream << node.nodeName << ":" << node.link.size() << ":";
    std::copy(node.link.begin(), node.link.end(), std::ostream_iterator<int>(stream, " "));
    return stream;
}
std::istream& operator>>(std::istream& stream, Graph::GraphNode& node)
{
    char ignore;
    int  count;

    stream >> node.nodeName >> ignore >> count >> ignore;

    for(std::istream_iterator<int> loop(stream); count != 0; --count, ++loop)
    {   node.link.push_back(*loop);
    }
    // For some reason you sort your nodes so I am sorting them here.
    // Or I am reading your original code incorrectly.
    std::sort(node.link.begin(), node.link.end());
    return stream;
}
// Stream the whole graph.
// This is simply the number of nodes followed by a list of nodes.
std::ostream& operator<<(std::ostream& stream, Graph const & graph)
{
    stream << graph.nodes.size() << " ";
    std::copy(graph.nodes.begin(), graph.nodes.end(), std::ostream_iterator<Graph::GraphNode>(stream, " "));
    return stream;
}
std::istream& operator>>(std::istream& stream, Graph& graph)
{
    int nodeCount;
    stream >> nodeCount;

    // We could implement it like this.
    // As this would match your current file format nicely and if their
    // is anything after the nodes it still works.
    /*
    for(int loop=0;loop < nodeCount; ++loop)    // I implemented it like this becuase
    {
        Graph::GraphNode    node;
        stream >> node;
        graph.nodes.push_back(node);
    }
    */
    // But if there is nothing after the nodes it could be implemented like this:
    std::copy(std::istream_iterator<Graph::GraphNode>(stream),
              std::istream_iterator<Graph::GraphNode>(),
              std::back_inserter(graph.nodes)
             );
}

// A visitor object used by Graph::DepthFirstTraversal
// It tracks which nodes it has already seen.
// So you do not need to visit them again.
// When a node says it can visit then just visit all the linked nodes.
// If you get a call from a node that has already visited then just exit.
class DepthFirstVisitor: public GraphVisitor
{
    public:
        DepthFirstVisitor(std::vector<Graph::GraphNode>& n)
            : nodes(n)
        {}
    private:
    virtual void visit(Graph::GraphNode& node, int name, std::vector<int> const& links)
    {
        if (visited[&node])
        {   return;
        }

        visited[&node]  = true;
        std::cout << "Visiting Node: " << name << "\n";

        for(std::vector<int>::const_iterator loop = links.begin();loop != links.end();++loop)
        {
            nodes[*loop].accept(*this);
        }
    }
    std::map<Graph::GraphNode const*, bool>     visited;
    std::vector<Graph::GraphNode>&              nodes;
};

// Implementing the Depth First traversal is easy as calling the first node with the
// the correct visitor object
void Graph::DepthFirstTraversal(size_t startNode)
{
    if (startNode >= nodes.size())
    {   throw std::runtime_error("Failed");
    }
    DepthFirstVisitor   visitor(nodes);
    nodes[startNode].accept(visitor);
};

int main()
{
    Graph   graph;

    std::ifstream digraph("digraph.data");
    digraph >> graph;                   // Very easy to load a graph.
    std::cout << graph << "\n\n\n";     // Printing it out is also easy

    graph.DepthFirstTraversal(1); // start at node one instead of zero for some reason!!!!!.
}


Format double to 3 decimal places without decimal separator to a certain length

To truncate a double to 3 decimal places and remove the decimal separator, is I think more easily done by multiplying by 1000 and casting to an int.  Padding the result to 9 digits is easily done with a format specifier in the ToString method.  It could look something like this:

static string FormatNum(double num) => ((int)(num * 1000)).ToString("D9");

Note I've also put it in a method with an expression body.

I just noticed that you wanted the padding with spaces not zeros here's a version that does that:

static string FormatNum(double num) => string.Format("{0,9:D}",((int)(num * 1000)));

As was pointed out, your solution produced a rounded off number.  If that is required here's one way:

static string FormatNum(double num) => string.Format("{0,9:D}",((int)(Math.Round(num * 1000))));


Can this PHP code to settle up payments be improved?

Well if you want to split hairs, you could do a couple of minor changes (commented below)

Honestly, I can't see any advantage in making it recursive, it works fine as it is

function settleUp($owings){
    $reimbursments = array();

// $i is never used
 //   $payment = 0.11; $i = 1;

// by using a do/while loop you don't need to assign $payment to a random value to being the loop
    do {
        $min = 0;
        $max = 0;
        foreach ($owings as $id => $owing){
            if ($owing < $min) {
                $min = $owing;
                $min_id = $id;
            }
            if ($owing > $max) {
                $max = $owing;
                $max_id = $id;
            }
        }
        $payment = -$min > $max ? -$max : $min;

        if ($payment !== 0) {
            $reimbursments[] = array(
                'from'      => $max_id,
                'to'        => $min_id,
                'payment'   => -$payment,
            );

            $owings[$max_id] += $payment;
            $owings[$min_id] -= $payment;
        }
  //      $i++;
    } while ( $payment > 0.1 || $payment < -0.1 );

    return $reimbursments;
}


PHP script that returns an error message based on what $_POST parameters are missing

if (empty($_POST[$item]) || !array_key_exists($item, $_POST)) { is literally checking if $_POST[$item] is not declared or is falsey THEN checking if $_POST[$item] is not declared.

// Check for nulls or non existent payload

The comment associated with the step indicates that you want to check if $_POST elements are not declared or are null.  In this case, you should only use: if (!isset($_POST[$item])) {.
If you want to check that elements are not declared or empty/falsey, then use:if (empty($_POST[$item])) {.

if ($missingCount > 0) { can be safely reduced to if ($missingCount) { which checks if the count is "truthy" (in other words, not zero).

else if is one word in php, please always type elseif to comply with PSR guidelines.

Don't bother declaring $missingString = ''; if you are unconditionally going to overwrite it anyhow.

You can combine the if and first else if because if the array only has one element, then no glue will be used while producing the output string.
if ($missingCount < 3) {
     $missingString = implode(' and ', $missing);
}

The "smart-implode" as I've seen it referred to at least once on StackOverflow is fine enough.  There are a few other ways to do it -- I'll show another one below.

The whole chunk of code that crafts the OutputResponse might look like this: (Demo).  The advantages are: fewest declared variables (specifically no single-use variables), not repeated function calls, and the elegance of sprintf() when injecting variables into a string.
$missingCount = count($missing);
if ($missingCount) {
    if ($missingCount < 3) {
         $glue = ' and ';
    } else {
         $glue = ', ';
         $missing[] = 'and ' . array_pop($missing);
    }
    OutputResponse::sendResponse(
        400,
        sprintf(
            'Incomplete information received. The %s %s missing. Please check your inputs and try again.',
            implode($glue, $missing),
            $missingCount === 1 ? 'field is' : 'fields are'
        )
    );
}

[EDITED] After reading the other reviews and learning that my recommended lookup array was incomplete, flawed, and frankly suboptimal, I now find myself agreeing with YourCommonSense's advice to use http_response_code() for setting the HTTP response code.  See this Stack Overflow page for additional considerations and fringe cases around the native function which was available since PHP5.4. Also,  Now I suppose my new code for the sendResponse() method would look like this:
 http_response_code($statusCode);
 header('Content-Type: application/json');
 exit(
     json_encode([
         'code' => $statusCode,
         'data' => $messageBody
     ])
 );


Send / receive wrapper for System.Net.Sockets - follow-up

Events can be cleared much simpler:

public void Clear() {
    foreach (Delegate d in DataReceived.GetInvocationList())
        DataReceived -= (EventHandler<NetworkReceiveEventArgs>)d;
    foreach (Delegate d in Disconnected.GetInvocationList())
        Disconnected -= (EventHandler)d;
}

public void Clear() {
    DataReceived = null;
    Disconnected = null;
}

This is by no means a full review of your code, but I would like to explain a couple of things to you.

You are using seperate locks for sending, checking connection status, initializing and disconnecting. Think about the implications by using a seperate lock for operations that all require a common thread-aware resource Connected. Since they all take a different lock, they can simultaniously change the state and corrupt the other ongoing operation. This is why you should use a single lock for all these operations.

private object syncRoot = new object();

But even then, since you check the condition before the lock, data integrity might still be breached by an unfortunate flow of events.

public void Send(NetworkHeader header, byte[] data) {
    if (!Connected) // ..      // <- outside lock
    lock (syncRoot) {          // <- inside lock, but condition might no longer be true
        // ..
    }
}

As an example, suppose two threads simultaniously call respectively Send and Disconnect. A possible flow is:

- thread A: call Send                    // thread A is first
- thread A: check IsConnected: true
- thread B: call Disconnect              // thread B starts a fraction later
- thread B: check IsConnected: true
- thread B: take lock
- thread B: set IsConnected: false
- thread B: release lock
- thread A: take lock                    // thread A reaches a point where it
             // expected its state to still be valid, but thread B changed it
- thread A: connection.Send(..)          // <- null-reference exception

There used to be a recommedation about double-checked locking. But here is a good reason not to use it. So we will have to take the condition inside the lock.

public void Send(NetworkHeader header, byte[] data) {
    lock (syncRoot) {
        if (!Connected) // ..
        // ..
    }
}

Moving on, we can change Connected to take a volatile boolean, so we don't require additional locking when just getting its value. Just make sure to set its value when connection is established and reset on Disconnect. The volatile field is read as an atomic operation. You get the actual value, rather than a cached value (which might be done to optimize state in a non-concurrent context).

private volatile bool _connected = false;

public bool Connected => _connected;   // <- no locking required

I hope this explains some basic concepts of locks and thread-safety.


2D Vector: Loading values from .txt file

Your code has a bug. When the very last value cannot be read, it won't detect it. Example:

2 2
1 2
3 invalid

Instead of checking for eof, check whether mapFile >> current returns true.


Verifying if two numbers are equal using ArrayLists

First thing I noticed don't count how many digits are equal, soon as 1 digit is unequal return false, if the loop finishes return true.  Also it seems to me if the sizes are unequal the proper response would be false not an error.


Fetch nearby chat users using Firebase and nested completion handlers

Nesting
In general, I find it harder to read nested closures. I think it's even worse when calling APIs that run the closures asynchronously because it makes it harder to understand what's happening when. That said, these 3 aren't that bad. (And despite my dislike of nesting them, I've done it myself!)
You can use the various shorthands to make this slightly easier to read by inferring types and using the rules for trailing closures. I think your code could be rewritten like this:
func fetchNearbyUsers(for user: User, completionHandler: userCompletionHandler?) {
    fetchAllUsers() { users in
        ChatProvider.sharedInstance.fetchAllChatrooms() { chatrooms in
            validateNewUsers(currentUser:user, users:users, chatrooms:chatrooms) { validUsers in
                guard validUsers.isEmpty == false else {
                    completionHandler?([])
                    return
                }
                completionHandler?(validUsers)
            }
        }
    }
}

I've used type inference on users, chatrooms and validUsers to shorten the closures' code. And I used trailing closure notation to further reduce the number of characters needed. Whether it's more or less readable is a judgement call, but it looks cleaner to me without being too sparse.
Naming
If it were me, I'd change the name of the function to fetchUsers(nearby user: User, completionHandler: usersCompletionHandler?). I say that because for is a keyword, and even if the compiler doesn't mind it, it looks weird to me to have it there naked. If it was forUser: it would be less weird to me. Also, I think fetchUsers(nearby:, completionHandler:) flows better.
Is That guard Needed?
Why guard if validUsers.isEmpty? Inside of it you simply call the completionHandler with an empty array. But if validUsers.isEmpty is true and the guard isn't there, you'd still just be calling the completionHandler with an empty array. So you might be able to further shorten it to:
func fetchNearbyUsers(for user: User, completionHandler: userCompletionHandler?) {
    fetchAllUsers() { users in
        ChatProvider.sharedInstance.fetchAllChatrooms() { chatrooms in
            validateNewUsers(currentUser:user, users:users, chatrooms:chatrooms) { validUsers in
                completionHandler?(validUsers)
            }
        }
    }
}


Remove every occurence of the number 13 and the next number from a list, then sum the result

Your output is simply a sum of certain numbers. You don't need to build intermediary lists at all here, just select the numbers you want to sum, by looping. Your criteria are that the current number should not be 13, and the preceding number should not be 13.

To achieve this, you could just use a loop that remembers the preceding number:

initialize a preceding variable to a value you can easily test for. Here, any value other than 13 would do, and None is probably a good sentinel value.
In a loop over the numbers, if the current number is not 13 and the preceding number is not 13, add it to the running total.
At the end of the loop, set preceding to the current number. That way, when you go back to the top of the loop body, preceding will still contain the number from the preceding iteration.

So, given an input of [17, 13, 3, 9], you'd want to sum the first and the last number. We start with preceding set to None, result is set to 0 and we iterate 4 times:

preceding = None, set current to the first value 17.

preceding != 13 and current != 13 is true, so add the current value to the result -> result = 0 + 17 = 17.
set preceding = current, so 17

preceding = 17, set current to the second value 13.

preceding != 13 and current != 13 is false (current is set to 13), so skip this value.
set preceding = current, so 13

preceding = 13, set current to the third value 3.

preceding != 13 and current != 13 is false (preceding is set to 13), so skip this value.
set preceding = current, so 3

preceding = 3, set current to the forth value 9.

preceding != 13 and current != 13 is true, so add the current value to the result -> result = 17 + 9 = 26.
set preceding = current, so 9

and you end up with result = 26.

Generally speaking, when you find yourself wanting to look ahead in a for loop, turn the problem around and look behind instead. It is much simpler, as your loop will already have processed the items behind.

Translating those steps above to Python code looks like this:

def sum_without_13s(nums):
    """Sum all values that are not equal to 13 or directly follow 13"""

    # the running total of qualifying numbers
    result = 0
    # the preceding value in the loop, set at the end of the loop body
    preceding = None  # any value that is not 13 would do

    for value in nums:
        # only add to the sum if this value and the preceding value are both
        # *not* equal to 13.
        if value != 13 and preceding != 13:
            result += value

        # for the next iteration, remember the current value so we can
        # skip any values that followed 13.
        preceding = value

    return result

That's the most readable method of implementing your algorithm. The function produces the sum of integers not 13, and not directly following 13:

>>> sum_without_13s([13, 99, 3])  # only 3 fits criteria, so should produce 3
3
>>> sum_without_13s([99, 3])  # no 13s, so sum should be 102
102
>>> sum_without_13s([1, 2, 13, 13, 3, 4])  # only 1, 2, and 4 should be summed == 7
7

Note that the function also returns the result, rather than print the result to the console. If you want to see the output of your function, you can always print the returned value:

>>> theanswer = sum_without_13s([17, 13, 19, 18, 13, 13, 3, 7])
>>> print(theanswer)
42

Other looping constructs that give you access to the preceding value

You could in principle make use of itertools.chain() and zip() to produce an iterator of (preceding, current) tuples to loop over, and so make it possible to filter and sum in a generator expression.

The above 'preceding value' approach is a variant of the pairwise() function from the itertools recipes section. But where pairwise() starts with (nums[0], nums[1]) and ends at (nums[-2], nums[-1]),  we really need to be starting with (None, nums[0]) first because we wouldn't want to skip either the first or the last value in your input from consideration.

So here's a with_preceding() function, with a configurable default value for that first element of the first tuple:

from itertools import chain, tee

def with_preceding(iterable, default=None):
    "s -> (default, s0), (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    return zip(chain((default,), a), b)

which then can be used in an alternate implementation using a generator expression, like this:

def sum_without_13s_iter(nums):
    """Sum all values that are not equal to 13 or directly follow 13"""
    return sum(
        current
        for preceding, current in with_preceding(nums)
        if preceding != 13 and current != 13
    )

However, readability suffers, in my eyes, and for little gain as the above is actually slower than the first version. See the small benchmark at the very end.

Performance considerations

I tried to construct what I hoped would be a faster function using iterators, the itertools and operator modules and the sum(), map() and zip() functions to try and avoid the Python interpreter loop altogether, but this was simply not any faster; at best I could get it to be about 5-10% slower than the above first version of the function.

If performance is a concern, then you should really be using numpy arrays anyway. With a numpy array of integers as the input, the function can be expressed as:

import numpy as np

def array_sum_without_13s(numarray):
    """Sum all values in an array that are not equal to 13 or directly follow 13"""
    # boolean array with True where the input array has 13
    is13 = numarray == 13
    # boolean array with True where the input array is preceded by 13
    follows13 = np.concatenate(([False], is13[:-1]))
    # sum of all values that don't fit either of the above criteria
    return np.sum(numarray[~(is13 | follows13)])

As stated, this function expects a numpy array as the input:

>>> import numpy as np
>>> array_sum_without_13s(np.array([13, 99, 3]))
3
>>> array_sum_without_13s(np.array([99, 3]))
102
>>> array_sum_without_13s(np.array([1, 2, 13, 13, 3, 4]))
7
>>> array_sum_without_13s(np.array([17, 13, 19, 18, 13, 13, 3, 7]))
42

Given an input of 1 million integers, the numpy version takes ~3.5 milliseconds versus the pure-Python version taking ~89 milliseconds. Numpy is the numeric processing champion, hands down:

In [1]: import random
   ...: import numpy as np
   ...: from codereview237899 import sum_without_13s, array_sum_without_13s
   ...: testdata = random.choices(range(1_000), k=1_000_000)
   ...: testarray = np.array(testdata)
   ...:

In [2]: %timeit sum_without_13s(testdata)
88.7 ms ± 2.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [3]: %timeit array_sum_without_13s(testarray)
3.55 ms ± 81.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [4]: %timeit sum_without_13s_iter(testdata)
119 ms ± 13.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

The last test there is for the with_preceding() and generator expression variant above; it's a disappointing 35% slower.


Transferring data from one file stream to another

Work with top level classes

Currently, your code only works for file related operations, as seen by the signature of transferBytesFrom.

transferBytesFrom(FileInputStream input, FileOutputStream output)

However, such an operation ought to work for every InputStream and every OutputStream, not just for file streams.

As such, it would be preferable to make all of your methods as generic as possible and let them take Input/OutputStream as arguments, or let them return Input/OutputStream:

private static void transferBytesFrom(InputStream input, OutputStream output)

private static void writeByteTo(OutputStream output, int singleByte)

private static int readByteFrom(InputStream input)

private static InputStream getNewFileOutputStream()

// ... the same for the other methods

The important goal here is that a code as generic as possible is a code that can be reused, and also a code that can evolve more simply. If you were to change your requirement and make your class handle other types of streams (and not files), you would have to rewrite everything.

try-with-resources

Starting with Java 7, you can use the try-with-resources statement to handle the automatic closing of the resources. This will prevent you from any tricky bugs, like this one:

private static void closeStreams(FileInputStream input, FileOutputStream output) {
    try {
        input.close();  // <--- imagine this throws an exception
        output.close();
    } catch (IOException e) {
        e.printStackTrace();  // <--- we go here. Ooops! output was never closed!
    }
}

Using this statement, you can have

public static void copyBytes() {
    try (
        InputStream input = getNewFileOutputStream();
        OutputStream output = getNewFileInputStream();
    ) {
        transferBytesFrom(input, output);
    } catch (IOException e) {
        // do something meaningful here
    }
}

This will ensure that whatever happens inside the try block, each stream is properly closed.

This also means that your closeStreams isn't really needed, because it will be done automatically.

Separation of concern

Let's look at your 2 methods getNewFileOutputStream and getNewFileInputStream. Their goal, as stated by their (good!) name is to retrieve a FileOutputStream and a FileInputStream. However, they currently do more than that. They currently handle the exceptions that can happen, and return null in that case.

Returning null when there is an exception is generally a code-smell: it indicates that something wrong happened, the method where this went wrong doesn't know what to do so it returns null. This creates bugs and, in fact, you have one in that case: if the files can't be opened for reading / writing, you will throw a NullPointerException later on. This is a problem: you want to fail as fast as possible and not let your code crash a couple of methods down with an unrelated and sometimes hard to debug exception, when it could have handled it before that.

So in this case, do not return null when there is an exception. In fact, I would let the method throw the checked exception. Its concern was "get me a InputStream; if it can't do that, it should throw.

In light of that, you can refactor your method to:

private static InputStream getInputStream() throws IOException {
    return new FileInputStream("xanadu.txt");
}

There are important comments here:

The method was renamed getInputStream: the global goal here is to copy bytes between streams and this goes in-line with the first point; we don't need to restrict ourselves to files. Let's go all the way and be as generic as possible.
The method returns the generic InputStream instead of the specific FileInputStream for the same reason.
The method declares to throws IOException: it isn't its purpose to decide what to do when an input stream can't be retrieved so it lets this condition be handled by whoever is calling it. Note that in this case, it will be handled automatically by the try-with-resources introduced earlier.

Essentially, the same comments apply for your other methods, so you could have:

private static void writeByteTo(OutputStream output, int singleByte) throws IOException {
    output.write(singleByte);
}

private static int readByteFrom(InputStream input) throws IOException {
    return input.read();
}

Putting it all together

With all those modifications, you would have:

public static void copyBytes() {
    try (
        InputStream input = getInputStream();
        OutputStream output = getOutputStream();
    ) {
        transferBytesFrom(input, output);
    } catch (IOException e) {
        // do something meaningful here
    }
}

private static void transferBytesFrom(InputStream input, OutputStream output) throws IOException {
    int singleByte;
    while ((singleByte = readByteFrom(input)) != -1) {
        writeByteTo(output, singleByte);
    }
}

private static void writeByteTo(OutputStream output, int singleByte) throws IOException {
    output.write(singleByte);
}

private static int readByteFrom(InputStream input) throws IOException {
    return input.read();
}

private static OutputStream getOutputStream() throws IOException {
    return new FileOutputStream("output.txt");
}

private static InputStream getInputStream() throws IOException {
    return new FileInputStream("xanadu.txt");
}

Each method now has a clear goal and doesn't handle unnecessary exceptions. All potentials exceptions are left for the main method copyBytes to handle. Arguably, this is where it should be: this is the method responsible for organizing the work. A user calling that method shouldn't have to handle an IOException: the streams were opened and closed by this method alone, so it should be the one handling the exceptional circumstances; a caller shouldn't have to handle an exception for a scenario it didn't create in the first place.

There's still the question of what this method should do in the case of an exception. This answer really depends on your requirement then:

it could rethrow a custom exception like CopyFailedException and have as cause the IOException. The advantage is that this exception isn't coupled with the fact we're doing IO here. A caller doesn't know that we're doing IO, but it knows that we're copying something, so it makes sense to tell the caller that the copy operation failed with a custom exception.
it could log the error and do nothing else. The logging ensures that the exception is properly traced somewhere.

As a side-note, when you will reach the NIO.2 API in the Java tutorials, you will find that all of this code can be replaced with a simple call to Files.copy(source, target)

Files.copy(Paths.get("xanadu.txt"), Paths.get("output.txt"));

This method will directly copy the path "xanadu.txt" into "output.txt". It also takes a 3rd argument as a vararg that corresponds to CopyOptions. A useful one could be StandardCopyOption.REPLACE_EXISTING that tells the method to replace the target file if it already exists.


Private methods and properties in jQuery "lightweight start" pattern

You could use a closure to create your own proxy.

Plugin.prototype.init = function() {
    var self = this;
    rows.each(function (groupIndex, group) {
        self.initGroup(groupIndex, group);
    });
    this.container.on("click", this.options.addBtnId, function (ev) {
        self.addGroup(ev);
    });
};

Why are initGroup and addGroup using $.proxy? They are already being called with the correct this context, and rebinding to the same context changes nothing.

Edit: Instead of using plain functions to implement "private methods", promote them to proper object methods and mark them private using JSDoc. This will save you those extra calls to $.proxy.

/** @private */
Plugin.prototype.initGroup = function(groupIndex, group) {
    this.addFieldIds(groupIndex, group);
};

/** @private */
Plugin.prototype.addGroup = function(ev) {
    this.initGroup(this.maxGroupIndex, newGroup);
};

In my opinion, forcing developers to jump through hoops just to hide private methods is a net loss.


Personally, I don't like the first two lines of code, but I'm aware that you're only concerned with this function and I wouldn't know how to improve those two lines without seeing the calling function. However:

Do the checkbox and rows share a common (and close) parent?

Example markup:

        <input type="checkbox" value="some value">

In this case, the img and input share the same tr. Meaning you could have this instead:

var $row = $('tr img[src="../_layouts/15/images/' + img + '.png"]').closest('tr');
var show = $('#' + checkBox, $row).prop('checked');

Specifically looking at this code: $('#' + checkBox, $row). Here we are looking for an element with the id specified within the context of $row. The advantage of this is that jQuery doesn't traverse the whole DOM looking for that input, it only looks within the tr. This won't make much of a difference in this case - but it's important to have this approach with performance in mind on client side. You may have also noticed that I renamed rows to $row? A lot of people will prefix a variable with a $ if the variable is a jQuery selector, this gives other developers a bit more visibility.

Ternary operator

Instead of your if/else here you could use a ternary operator to reduce the lines of code:

show ? rows.show() : rows.hide();

Naming variables

The function variable names are a bit ambiguous in my opinion. To me checkBox suggests I'm actually receiving a checkbox not the ID property. The same with img applies here. More suitable ones might be:

function toggleRows(checkboxId, imgName)


First, there are some code naming and formatting standards in C# that you should follow:

Interfaces begin with I
Method names are Pascal-cased

And here are a small smattering of my personal standards:

Specify access modifiers at all times (source code are for humans to read)
Declare non-changing fields with readonly (primarily for intent,
but there is supposed performance advantages)
Declare non-inheritable classes with sealed (again, for intent, but there could be
performance advantages)
Use this. as a prefix for class members

Simple matters:

Test for null where you would not want to have null objects (i.e. in the constructor)
Instead of returning a new Int(0) each time in D(), have it be a pre-initialized static member.
I'm thinking the same for new Int(1)? Your mileage may vary.

All in all, I really like your approach as loosely-coupled OOP using injection.

Given those, I would lightly refactor as such:

namespace SymbolicDerivative
{
    using System;

    public interface IExpr
    {
        IExpr D(string x);
    }

    public sealed class Int : IExpr
    {
        private static readonly IExpr intZero = new Int(0);

        private static readonly IExpr intOne = new Int(1);

        private readonly int n;

        public Int(int m)
        {
            this.n = m;
        }

        public static IExpr IntZero
        {
            get { return intZero; }
        }

        public static IExpr IntOne
        {
            get { return intOne; }
        }

        public int Value
        {
            get { return this.n; }
        }

        public IExpr D(string x)
        {
            return intZero;
        }

        public override string ToString()
        {
            return "Int " + this.n;
        }
    }

    public sealed class Var : IExpr
    {
        private readonly string x;

        public Var(string y)
        {
            if (y == null)
            {
                throw new ArgumentNullException("y");
            }

            this.x = y;
        }

        public string Value
        {
            get { return this.x; }
        }

        public IExpr D(string y)
        {
            return this.x == y ? Int.IntOne : Int.IntZero;
        }

        public override string ToString()
        {
            return "Var \"" + this.x + "\"";
        }
    }

    public sealed class Add : IExpr
    {
        private readonly IExpr f;

        private readonly IExpr g;

        public Add(IExpr a, IExpr b)
        {
            if (a == null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == null)
            {
                throw new ArgumentNullException("b");
            }

            this.f = a;
            this.g = b;
        }

        public Tuple<IExpr, IExpr> Value
        {
            get { return Tuple.Create(this.f, this.g); }
        }

        public IExpr D(string y)
        {
            return new Add(this.f.D(y), this.g.D(y));
        }

        public override string ToString()
        {
            return "Add(" + this.f + ", " + this.g + ")";
        }
    }

    public sealed class Mul : IExpr
    {
        private readonly IExpr f;

        private readonly IExpr g;

        public Mul(IExpr a, IExpr b)
        {
            if (a == null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == null)
            {
                throw new ArgumentNullException("b");
            }

            this.f = a;
            this.g = b;
        }

        public Tuple<IExpr, IExpr> Value
        {
            get { return Tuple.Create(this.f, this.g); }
        }

        public IExpr D(string y)
        {
            return new Add(new Mul(this.f, this.g.D(y)), new Mul(this.g, this.f.D(y)));
        }

        public override string ToString()
        {
            return "Mul(" + this.f + ", " + this.g + ")";
        }
    }

    internal static class SymbolicDerivative
    {
        private static void Main()
        {
            var x = new Var("x");
            var f = new Add(new Add(new Mul(x, new Mul(x, x)), new Mul(new Int(-1), x)), new Int(-1));

            Console.WriteLine("{0}", f.D("x"));
            Console.ReadLine();
        }
    }
}


First of all don't create variables for those keys, store them in a list.

keys = ["ElemNo", "Node1", "Node2", "Length", "Area", "Inertia",
        "Fnode1", "Fnode2", "SigmaMin", "SigmaMax"]

You can use collections.defaultdict here, so no need to initialize the dictionary with those keys and empty list.

from collections import defaultdict
var = defaultdict(list)

Now, instead of storing the data in a list, you can populate the dictionary during iteration over File itself.

for line in File:
    for i, (k, v) in enumerate(zip(keys, line.split())):
        if i == 5:
            var[k].append(float(v)*10**6)
        else:
            var[k].append(float(v))


Implementation

The query is quite well written for what it does.  I just have a few minor nitpicks about its implementation.

The FROM, GROUP BY, and ORDER BY clauses are all subsidiary to the SELECT clause.  Therefore, I would indent them by one level.  (Indenting your INNER JOIN clauses so that they are part of the FROM clause was good.)

You're getting the disadvantages of the comma-first convention without reaping the benefits.  The advantage of putting commas first is that it makes it foolproof to add or remove columns in the SELECT: you should be able to delete an entire line of text without having to worry about fixing commas on neighbouring lines.  However, to take advantage of that property, you should put the first column on the same line as the SELECT keyword:

SELECT Users.Id as [User Link]
     , Users.DisplayName
     , COUNT (Badges.Id) AS Number_of_Tag_Badges
    FROM …

Remove the space before the parenthesis in the COUNT (…) call.

The joins would be better if the tables were listed linearly:

$$ \fbox{Users} \overset{\texttt{UserId}}{\longleftrightarrow}
   \fbox{Badges} \overset{\texttt{Name}}{\longleftrightarrow} \fbox{Tags}$$

Since the displayed results are user-centric, I would suggest listing the tables as Users, Badges, Tags rather than any other order.

Concept

It would be handy if you added a rank column.

The query doesn't distinguish between gold, silver, and bronze badges.  You should be able to report the breakdown.  The convention used by the International Olympic Committee is to sort by the gold medal count first, rather than by the total.  Perhaps you should do the same.

WITH EarnedTagBadges AS (
    SELECT Users.DisplayName
         , Badges.UserId
         , Badges.Name
         , RANK() OVER (PARTITION BY Users.Id, Badges.Name ORDER BY Date) AS Level
        FROM Users
            INNER JOIN Badges ON Users.Id = Badges.UserId
            INNER JOIN Tags ON Badges.Name = Tags.TagName
), UserTagBadges AS (
    SELECT UserId
         , DisplayName
         , COUNT(CASE WHEN Level = 3 THEN 1 END) AS Gold
         , COUNT(CASE WHEN Level = 2 THEN 1 END) AS Silver
         , COUNT(CASE WHEN Level = 1 THEN 1 END) AS Bronze
         , COUNT(Level) AS Total
        FROM EarnedTagBadges
    GROUP BY UserId, DisplayName
)
SELECT RANK() OVER (ORDER BY Gold DESC, Silver DESC, Bronze DESC) AS Rank
     , UserId AS [User Link]
     , DisplayName
     , Gold
     , Silver
     , Bronze
     , Total
    FROM UserTagBadges
    ORDER BY Gold DESC, Silver DESC, Bronze DESC;


Print first element of the last line of files when the second element does not match a pattern

That second grep (grep -v 'fitness') is there to filter out the filenames that tail spits out, right? That can be removed by using the -q option for tail.

Personally, I'd try to avoid that paste command, but that might just be because I'm not used to it. If you don't need spaces after the commas, tr works just fine.

tail -qn 1 *fitness* | grep -v '100000' | awk '{print $1}' | grep -v '^$' | tr '\n' ','

Now, since you're already using awk, why not do a bit more with it (actually, the whole thing could probably be made into an awk program with either more time or more experience than I have available)?

This uses a single awk statement to choose only lines that don't contain the word '100000' and also have a non-empty first field, and also to print that first field. What it does for readability depends on personal preference, but it certainly reduces the number of programs that need to be chained together:

tail -qn 1 *fitness* | awk '(! /\<100000\>/) && $1 !~ /^$/ {print $1}' | tr '\n' ','