You posted this question with the objective-c tag, and made this comment:

  I had to convert the method to C to get it passed through the automated system.

As such, I'm going to assume you're perhaps more interested in a review of the Objective-C stuff, so that's what this'll be.  (Essentially, I'm ignoring the howManyBatsBetween function for this.)

As a start, the first problem I notice is that our method takes no arguments and returns nothing.  The problem statement gives sample inputs in the form of strings and expects an integer return.  Our method should be changed to reflect this:

- (NSInteger)batsOnWire:(NSString *)wire;

Now we can remove the hardcoded // input.

componentsSeparatedByString: is a good approach at breaking up the string, but we also need to make sure our input is in a good format.

NSArray *batPositions = [wire componentsSeparatedByString:@" "];

if (batPositions.count < 3) {
    return NSNotFound;
}

We'll use NSNotFound as a return result representing some sort of problem with the input.  Truly we should actually take an NSError ** as an argument, but I won't get into that mess.  I'll keep it simple for now.  The point here is, we're dealing with inputs, either typed by a user or read from a file... and inputs always have a chance of having errors, so we have to deal with that.

Grabbing lengthWire, distanceFromEachOther, and batsOnWire as you do is fine.

But again, we are dealing with user input.  The problem with calling intValue is that if the string in question can't be parsed as an int, the method just returns 0.  It's impossible to tell the difference between @"0" and @"Hello World" when looking at what they return intValue.

[@"0" intValue] == [@"Hello World" intValue]

Instead, we can convert these strings to NSNumber objects... which we'll want to do later for another reason which I'll address, but here's how we do it:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;

NSNumber lengthWire = [formatter numberFromString: batPositions[0]];
if (!lengthWire) {
    return NSNotFound;
}

NSNumberFormatter's numberFromString: method returns nil if the string cannot be parsed to a number.  Otherwise, it returns an NSNumber object representing the value.  Once we do the if(!lengthWire) check, we know we have a valid number.  We can always extract the raw int value by calling the same intValue on this NSNumber object.

But there's another reason we're going to want the entire array of strings converted into an array of NSNumber objects.

Given the following mutable array of strings:

@[@"1", @"2", @"40", @"10", @"300", @"100", @"9"];

If we sort if using sortedArrayUsingSelector:@selector(compare:)];, the result would be an array of this order:

@[@"1", @"10", @"100", @"2", @"300", @"40", @"9"];

And this isn't the right order.  The compare: method of NSString compares the strings character by character.

If we have to strings we want to compare individually, we can call another method:

[@"2" compare:@"100" options:NSNumericSearch];

And we'll get the correct numeric result (2 would be sorted before 100 correctly).

But when using sortedArrayUsingSelector:, we can't use a method that takes other arguments.  We can't specify that our strings our compared numerically.

However, if they are NSNumber objects, they'll of course be compared as numbers and sorted appropriately.  So if we turn our array of strings into an array of NSNumber objects, and then call the same:

[arrayOfNumberObjects sortedArrayUsingSelector:@selector(compare:)];

We'll get our array sorted in the proper order.

And once again, NSNumber responds to the intValue method in exactly the same way NSString does, so we can still use this to get a workable int out of the object.

#define CENTIMETERS_FROM_WALL 6

As one final note about Objective-C, we don't really care for #define variables.  I can't discourage it enough.  In fact, Apple agrees with me.  As evidence, you can't even use the #define functionality in their new language, Swift, at all.

Instead, we should opt for a typed constant:

static const int kCentimetersFromWall = 6;


Rewritten implementation of quadratic equation formula

Aside from re-computing discriminant(), a reasonable quadratic implementation.

When assessing the quality of floating-point computations, use "%e" rather than "%f".  I recommend using "%e" with enough precision too.  Like "%.17e", or use one of the DECIMAL_DIG family of constants.

Precision improvement when b*b near discriminant:

When |b| is about sqrt(discriminant), the computation of root1 or root2 will cancel many digits.  To avoid this, consider that a*root1*root2 = c

// calculate root1 and root2 together.
if (b < 0) {
  root1 = (-b + sqrt(discriminant))/(2*a);
  root2 = c/(root1*a);
} else {
  root2 = (-b - sqrt(discriminant))/(2*a);
  root1 = c/(root2*a);
}

Try a=1.0, b = -1e24-1, c = 1e24.  Roots should be 1e24, 1 as here.  OP's approach  results in 1e24, 0, total loss of precision.  Keep in mind, FP has overall logarithmic precision, not linear.

When b*b and discriminant greatly differ, this approach is not significantly weaker than OP's original.

Precision improvements are possible with b * b - 4 * a * c, yet tend to impact performance more.

Advanced concern:

root1(), root2() is on thin ice at it relies on a non-negative result from discriminant().

C is sneaky in that FP code is allowed to use higher than needed precision selectively.  See FLT_EVAL_METHOD.

With OP's code, this certainly will not happen as is, yet with a subtle change of in-lining b * b - 4 * a * c; instead of an explicit function call, may yield the following:

A test of b * b - 4 * a * c < 0 may be false yet the later (-b + sqrt(b * b - 4 * a * c)) may attempt a square root of a negative value due to different optimizations.

Solution: Use the same result rather than re-compute discriminant.  Do not rely on "same looking code" to generate the exact same FP result especially when near 0.0.

This also eliminates the wasteful re-computation of discriminant().

Check spelling on "coefficents": I'd expect "coefficients".

To meet OP's goal to split the functions into 3: discriminant, first root, other root consider:

double discriminant(double a, double b, double c);
double first_root(double discriminant, double a, double b);
double other_root(double root1, double a, double c);

...
doubled = discriminant(a, b, c);
if (d < 0) ...
else if (d == 0) ....
else {
  double root1 = first_root(discriminant, a, b);
  double root2 = other_root(root1, a, c);
  ...
}


Prettifying URLs for a PHP-based club website

You can combine these:

RewriteRule ^home\/$ /home.php [L]
RewriteRule ^home$ /home/ [L]

Into:

RewriteRule ^home\/?$ /home.php [L]

In addition, you should also map /home.php to /home.
So this will do all three:

RewriteRule ^home(?:\/|\.php)?$ /home.php [L]

Now your /home/1 rules. You've already got it, but you can make slight improvement:

RewriteRule ^home\/([^/]+)$ /home.php?data=$1 [L]

The + differentiates this rule from /home/.

If the data is alphanumerical you can improve this further:

RewriteRule ^home\/([\w-]+)$ /home.php?data=$1 [L]

You can replace home with other URLs
as well.


Your Code

Class method

You created the class method parse with this snippet:

class << self
  def parse str
    Grid.new str.split("\n").map { |row| row.split(" ").map { |val| val.to_i } }
  end
end

That works, but a more conventional definition is just:

def self.parse str
  Grid.new str.split("\n").map { |row| row.split(" ").map { |val| val.to_i } }
end

Further, since self equals Grid when this method is created, it is better to write:

def self.parse str
  new str.split("\n").map { |row| row.split(" ").map { |val| val.to_i } }
end

so that this code needn't be changed if you rename the class. (Note that new str.split... is the same as self.new str.split....)

However, you don't need a class method to create the instance. Instead, just write:

arr = str.split("\n").map { |row| row.split(" ").map { |val| val.to_i } }
grid = Grid.new(arr)

Consolidate all calculations in the class

You want to move:

def max_product lines
  lines.flat_map { |line| line.each_cons(4).to_a }.map { |cons| cons.inject {
   |prd, x| prd * x} }.max
end

and

[:horizontals, :verticals, :diagonals, :inv_diagonals].map { |method|
   max_product(grid.send(method)) }.max

into the class definition and make the latter a method:

def max_product_all_ways
  [:horizontals, :verticals, :diagonals, :inv_diagonals].map { |method|
    max_product(grid.send(method)) }.max
end

but I think it would be clearer to write:

def max_product_all_ways
  [max_product(horizontals),
   max_product(verticals),
   max_product(diagonals),
   max_product(inv_diagonals)].max
end

You would then invoke max_product_all_ways as follows:

arr = str.split("\n").map { |row| row.split(" ").map { |val| val.to_i } }
grid = Grid.new(arr)
grid.max_product_wall_ways

Diagonal detail

It's a small thing, but in diagonals you don't need to compute the diagonals of length less than four if only arrays of size four are to be considered. In fact, you should not, as it is conceivable that a diagonal of length less than four could have the greatest product!

Revised class definition

So this is what we now have (more or less):

class Grid

  def initialize arr
    @matrix = arr
    @dim = @matrix.size
  end

  def max_product_all_ways
    [max_product(horizontals),
     max_product(verticals),
     max_product(diagonals),
     # max_product(inv_diagonals)
     ].max
  end

  private

  def max_product lines
    lines.flat_map { |line| line.each_cons(4).to_a }.
          map { |cons| cons.inject { |prd, x| prd * x} }.max
  end

  def horizontals
    @matrix
  end

  def verticals
    @matrix.transpose
  end

  def diagonals
    (0..@dim-1).map { |i| diag(0, i) }.reverse +
    (1..@dim-1).map { |i| diag(i, 0) }
  end

  def inv_diagonals
    rev.diagonals
  end

  def diag x, y
    result = []
    while x < @dim && y < @dim
      result << @matrix[x][y]
      x += 1
      y += 1
    end
    result
  end

  def rev
    @matrix.map { |row| row.reverse }
  end
end

Well, this is still not quite right. The calculation of inv_diagonals is not correct, but it needs a fair bit of work to fix.  I've therefore commented it out in max_product_all_ways.  I also changed the name of the method reverse because it's easily confused with the built-in methods for reverse for strings and arrays.

I'll leave it to you to fix the rest and of course others may offer additional suggestions.

Alternative Solution

Here is one way you could write the program more compactly.

Code

class Grid

  def max_product(a, n)
    [array_max(a, n),
     array_max(a.transpose, n),
     array_max(diagonals(a, n), n),
     array_max(diagonals(rotate(a), n), n)
    ].max
  end

  def array_max(a,n)
    row_max(a.max_by { |r| row_max(r,n) }, n)
  end

  def row_max(r,n)
    r.each_cons(n).max_by { |e| e.reduce(:*) }.reduce(:*)
  end

  def diagonals(a, n)
    (0..a.size-n).each_with_object([]) do |i,b|
      b << (0...a.size-i).map { |j| a[i+j][j] }
      b << (0...a.size-i).map { |j| a[j][i+j] } if i > 0
    end
  end

  def rotate(a)
    a.transpose.reverse
  end
end

Examples

Given 20x20 array

a = str.lines.map { |l| l.split.map(&:to_i) }

g.max_product(a,4) #=>    51,267,216
g.max_product(a,3) #=>       776,776
g.max_product(a,5) #=> 3,143,734,308

3x3 array

a = [[1,2,3],
     [4,5,6],
     [7,8,9]]
g.max_product(a,1) #=>   9
g.max_product(a,2) #=>  72
g.max_product(a,3) #=> 504

a = [[1,2,3],
     [4,5,8],
     [7,6,9]]
g.max_product(a,2) #=> 72

a = [[1,7,3],
     [4,8,6],
     [5,2,9]]
g.max_product(a,2) #=> 72

a = [[1,2,3],
     [4,8,6],
     [9,5,7]]
g.max_product(a,2) #=> 72

In the last example, you can see the effects of rotate and diagonals:

b = rotate(a)
  #=> [[3, 6, 7],
  #    [2, 8, 5],
  #    [1, 4, 9]]

c = diagonals(b, 2)
  #=> [[3, 8, 9], [2, 4], [6, 5]]

array_max(c, 2)
  #=> [72, 8, 30].max => 72

Incidentally, I made the number of elements whose product is to be maximized a variable because it wasn't really any more difficult to do that and it facilitated debugging.


Handling related generic type parameters

You don't need the type parameter on IOrderable:

  public interface IOrderable
  {
    double Ordering();
  }

I don't like that you sort the source vector without notifying the client. In this way mysterious things are going on and the method does more than one thing. At least you should have a flag argument that lets the client determine if the source should be sorted or not before grouping:

public static IEnumerable<IGGrouping<T>> GroupBy<TG, T>(this IEnumerable<T> src, bool sortBeforeGrouping = false) where TG : IGGrouping<T>, new() where T : IOrderable
{
  var groups = new List<IGGrouping<T>>();

  ...
}

Alternatively you should rename the method to SortAndGroupBy(...). But I would let it total up to the client if the source should be sorted or not.

I think the inner of the internal Add(...) function can be simplified a bit:

  void Add(T aT)
  {
    var group = groups.FirstOrDefault(g => g.BelongsToGroup(aT));
    if (group == null)
    {
      group = new TG();
      groups.Add(group);
    }
    group.Add(aT);
  }

On way to get rid of the custom interfaces is to let the group type implement ICollection<T> and then inject the belongsToGroup function:

public static IEnumerable<TKey> GroupBy<TKey, TElement>(this IEnumerable<TElement> source, Func<TElement, TKey, bool> belongsToGroup) where TKey : ICollection<TElement>, new()
{
  return source.Aggregate(new List<TKey>(), (groups, e) =>
  {
    TKey group = groups.FirstOrDefault(g => belongsToGroup(e, g));
    if (group == null)
    {
      group = new TKey();
      groups.Add(group);
    }
    group.Add(e);
    return groups;
  });

}

Usage

  Func<Rectangle, RectangleGroup, bool> belongsToGroup = (r, gr) => gr.BelongsToGroup(r);
  var midPoints = list.OrderBy(r => r).GroupBy(belongsToGroup).Select(gr => gr.Middle());
  foreach (var middle in midPoints)
  {
    Console.WriteLine(middle);
  }

If that isn't good enough then you can inject the addToGroup function too:

public static IEnumerable<TKey> GroupBy<TKey, TElement>(this IEnumerable<TElement> source, Func<TElement, TKey, bool> belongsToGroup, Action<TElement, TKey> addToGroup) where TKey : new()
{
  List<TKey> groups = new List<TKey>();

  foreach (TElement element in source)
  {
    TKey group = groups.FirstOrDefault(g => belongsToGroup(element, g));
    if (group == null)
    {
      group = new TKey();
      groups.Add(group);
    }

    addToGroup(element, group);
  }

  return groups;
}

Usage

  Func<Rectangle, RectangleGroup, bool> belongsToGroup = (r, gr) => gr.BelongsToGroup(r);
  Action<Rectangle, RectangleGroup> adder = (r, gr) => gr.Add(r);
  var midPoints= list.OrderBy(r => r).GroupBy(belongsToGroup, adder).Select(gr => gr.Middle());
  foreach (var middle in midPoints)
  {
    Console.WriteLine(middle);
  }


You ask some unreasonable division questions.

That is answerable by the special string Infinity, but not infinity.

The expected answer is NaN, but responding with NaN will not work.

  10 / 3 = 3.33333333 is INCORRECT. The correct answer is 3.3333333333333335


Some suggestions:

I would usually inline single line functions unless what they do is hard to understand from just reading the command. filesize might be one such candidate.
I believe that not specifying the block size can be faster, by allowing Python to use whatever block size it thinks is appropriate. This would need some actual testing though.
Your function arguments are only partially typed. You might want to use a stricter mypy configuration, such as the following, in your setup.cfg:

[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

MD5 was optimized for cryptographic use, not for speed. Another Q&A explores options for fast non-cryptographic hashing.
I would avoid converting digests to strings - it might be slightly easier for debugging purposes, but data type conversions are in general very costly.
Optional parameters mean you have to test at least two things rather than one. Your code only ever calls the hash_* functions without optional parameters, so you might as well either inline them.
On a related note, static values which are used in multiple places are perfect for pulling out as constants. The hashing function and block size would be obvious candidates for this.
Mutable default parameter values are an accident waiting to happen. The default pattern for this is to use a default of None and to assign a default if foo is None.
r-strings like r"./testdata" are meant for regular expressions. Since pic_dir is not used as such it should probably be a regular string.
duplicates is at first a list of potential duplicates and later is trimmed in stages. This makes the code hard to follow.
Things like the directory/directories to include should be arguments. argparse can deal with this easily.
To make this more scriptable I would print the result on standard output. It's trivial to then redirect it to a file.


Finding Largest Integer Palindrome within a Set

First, since * is commutative, you can save 1/2 of your computation if you restrict yourself to cases where x >= y:

[ x*y | x<-[100..999], y<-[100..x], ... ]

Second, if you could generate all the products in a non-increasing list, you'd just be searching for the first element of such a list satisfying the predicate, which would also speed the search very much. See data-ordlist package, which implements many useful functions on sorted lists, in particular in your case you'll probably need unionBy or unionAllBy


ASP.NET MVC return early from an action that returns a model

I will review the first method.

Code duplication

I see 3 times checking for dataRetrieveModel.LineList.Count > 0 and 2 times checking for dataRetrieveModel.ModelList.Count > 0 where Count > 0 should be changed to .Any() (thanks to @krillgar) and then be refactored to

if (dataRetrieveModel.LineList.Any())
{
    dataRetrieveModel.ModelList = dataRetrieveDAL.GetModelList(dataRetrieveModel.LineList[0].Value);

    if (dataRetrieveModel.ModelList.Any())
    {
        dataRetrieveModel.LotList = dataRetrieveDAL.GetLotList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
        dataRetrieveModel.EquipmentList = dataRetrieveDAL.GetEquipmentList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
    }
}

This still uses 2 times dataRetrieveModel.LineList[0].Value and dataRetrieveModel.ModelList[0].Value so let's refactor again and add 2 vars holding these two values

if (dataRetrieveModel.LineList.Any())
{
    dataRetrieveModel.ModelList = dataRetrieveDAL.GetModelList(dataRetrieveModel.LineList[0].Value);

    if (dataRetrieveModel.ModelList.Any())
    {
        var lineListValue = dataRetrieveModel.LineList[0].Value;
        var modelListValue = dataRetrieveModel.ModelList[0].Value;

        dataRetrieveModel.LotList = dataRetrieveDAL.GetLotList(lineListValue , modelListValue);
        dataRetrieveModel.EquipmentList = dataRetrieveDAL.GetEquipmentList(lineListValue , modelListValue);
    }
}

The remaining part of this method I would just keep it like it is, because it is more readable than yours and also uses only one return point at the end.
Looking at your approach, I would suggest either adding {} brackets at your if statements, or at least write them in one line.


There are three key features of the builder pattern that need to exist before the pattern becomes recognizable.

the class you are tying to build should have a lot of properties/fields that you would normally want to pass as a constructor
you want those properties to be 'immutable' - constant for the life of the car (and this implies that there should not be 'setter' methods for those values)
the class is constructed from many places so having a more convenient system is... convenient

In your case, you have three parameters, the color, wheels, and speed for the car. These things can't be changed after the Car is built. You want a Car that has getColor(), but not setColor(...).

The non-builder way to do this would be to have a single constructor that takes all the parameters:

public Car(String color, String wheels, int speed) {
    ....
}

and then call that constructor from everywhere. If there are a lot more parameters though, it gets messy to call the constructor:

Car mine = new Car(view.getCarColorDropDown().getSelectedValue(), view.getCarWheelsOptionRadioButton().getSelectedValue(), view.getCarSpeedSpinner().getValue());

Now imagine if you also want to select an interior color, automatic, or manual transmission, etc.

What happens when you have a lot of inputs is that it becomes hard to 'align' the values with the parameters of the class.... you have to cross reference them, and count the values to make sure you are putting the color in to the color parameter, etc.

Finally, what if you want some default values as well... or you need to validate combinations of choices.... like, you cannot select wheels 'abc' and not have speed > 150? Validating that all in the constructor is ... hard.

The builder class is the solution to this. It makes the construction of the Car class a sequential process... you add the data to a builder, it accumulates, validates, and isolates the inputs until you have captured all the information you need. Making sure the right parameters are given the right values is easy because the method has just one argument, and a logical name: setColor(view.getCarColorDropDown().getSelectedValue());. Then, the builder organises the data in to a single call to the constructor (often private) of the Car class.

It is common to make the Builder class a sub-class of the class that is built, too.

Putting this all together, the builder has special permissions to access the Car constructor, the builder accumulates and validates the inputs in to changable values. It then calls the ugly constructor itself, creating a single, immutable class instance, and only one place in the code has to have the ugliness.

public class Car {

    public static Builder builder() {
        return new Builder();
    }

    // static inner class builder
    public static class Builder {
        private String builderColor = "white"; // default color
        private String builderWheels = "round"; // default wheels
        private int builderSpeed = 100; // default speed

        private Builder() {
            // inaccessible constructor, does nothing
        }

        public String getColor() {
            return builderColor;
        }

        public void setColor(String color) {
            // validate color....
            this.builderColor = color;
        }

        public .... //  more setters/getters

        public Car build() {
            return new Car(builderColor, builderWheels, builderSpeed);
        }
    }

    // final (immutable) fields.
    private final String color;
    private final String wheels;
    private final int speed;

    // private constructor, only the builder calls this....
    private Car(String color, String wheels, int speed) {
        this.color = color;
        this.wheels = wheels;
        this.speed = speed;
    }

    public String getColor() {
        return color;
    }

    .... // other getters

}

Now, how does one use the builder? Like this:

Car.Builder builder = Car.builder();

builder.setColor("red");
builder.setWheels("rwd");
builder.setSpeed(200);

Car mine = builder.build();

An often overlooked feature of a builder is that it is reusable as well, so, the above code can create many cars (it is a template of sorts)....

Car[] productionLine = new Car[100];
for (int i = 0; i < productionLine.length; i++) {
    productionLine[i] = builder.build();
}

Or, you can change just small factors, like the VIN number... :

int vin = 123456000;
for (int i = 0; i < productionLine.length; i++) {
    builder.setVIN(vin++);
    productionLine[i] = builder.build();
}


Determining which command line arguments are numeric

In your case, you apparently want to verify that there was not only a successful conversion, but also that the conversion consumed all the input. Given that this is exactly what Boost lexical_cast does, my immediate advice would be to use its existing code to do the job. If you can't do that, I'd still write a similar function, and probably give it the same name, so people who already know about lexical_cast will be able to recognize what you're doing without having to read through the code to do it.

As far as other changes go, rather than using std::copy to copy argv into v_tmp, I'd probably just initialize v_tmp from argv. I'd also note that &x[y] is generally equivalent to x+y, and simplify that part of the code a bit, giving:

std::vector<string> v_tmp(argv+1, argv+argc);

That gives us code that looks like:

template<typename Target, typename Source>
Target lexical_cast(const Source& arg) {
    // ...
}

std::vector<string> v_tmp(argv+1, argv+argc);
vector<float> v_argv;

for (int i=0; i<v_tmp.size(); i++)
    v_argv.push_back(lexical_cast<float>(v_tmp[i]);

That does leave one real question, however: exactly how you want to signal the fact that your lexical_cast has failed. Boost lexical_cast throws an exception. One possible alternative to that would be to return a NaN instead. I'm not at all sure I'd recommend that, but I can imagine situations where it might be the preferred way to go.

Assuming you go the route of throwing an exception, the code would change to something like this:

for (int i=0; i<v_tmp.size(); i++) {
    try {
        v_argv.push_back(lexical_cast<float>(v_tmp[i]));
    }
    catch (bad_lexical_cast const &) {
        std::cerr << "Error: " << v_tmp[i] << " is not numeric.\n";
    }
}

That leaves us with the definition of lexical_cast itself. Most of it would quite obviously be essentially identical to the code you had, just adding a check that after we do the conversion, the stream is empty:

template<typename Target, typename Source>
Target lexical_cast(const Source& arg) {
    istringstream iss(arg);
    Target f = Target(); // generic equivalent to your `0.0` initialization

    iss >> f;
    char c;

    // if the conversion failed, or we can read another character, we
    // couldn't convert, or there's data left in the stream, which we
    // consider a failure.
    if (iss.fail() || iss.get(c))
        throw bad_lexical_cast();
    return f;
}

Since that's throwing a bad_lexical_cast, we'll also have to define that type. In this case, we'll keep it simple:

class bad_lexical_cast {};

In reality, you usually want to derive your exception classes (directly or indirectly) from std::exception (unless you've defined a similar hierarchy of your own -- in any case you typically want a common base class for all your exceptions). You probably also want to include an indication of what failed and why in the exception object itself, so the code that catches it doesn't need as much information about what was being done at the time as we used here.


Retrieving all institutions in a specified country

Country.Institutions should never return a null collection, and if it ever does, I'd prefer having a NullReferenceException thrown to tell me something is broken with my API. The null-check is therefore redundant here:

if (country.Institutions == null || country.Institutions.Count <= 0)
    return Json(string.Empty, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);

As for country.Institutions.Count <= 0, it makes me raise an eyebrow. How would .Count ever return -12? Clearly the intent here is to say "if there aren't any institutions in that country", which is better conveyed like this:

if (!country.Institutions.Any())
    return Json(string.Empty, ...);

Now, you have two separate conditions that both return the same "empty value" - combine them - and because a scope is always better when it's explicit, add those curly braces, too:

if (country == null || !country.Institutions.Any())
{
    return Json(string.Empty, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}

This leaves another "empty value" returned when parent is null... which is annoying.

Why can't GetByCountryCode handle null input? (Iso can't legally be empty, right?)

public Country GetByCountryCode(string countryCode)
{
    if (string.IsNullOrEmpty(countryCode)) { return null; }

    return Session.Query<Country>()
                  .Where(country => country.Iso == countryCode)
                  .FetchMany(country => country.Institutions)
                  .SingleOrDefault();
}

That way country will be null given a null input, and you don't need to repeat yourself anymore:

var country = _countryRespository.GetByCountryCode(parent);
if (country == null || !country.Institutions.Any())
{
    return Json(string.Empty, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}

And then select your data:

var institutions = country.Institutions
    .OrderBy(i => i.Name)
    .Where(i => !i.Name.Contains("institutiontest1"))
    .Where(i => !i.Name.Contains("institutiontest2"))
    .Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() });

hmm.. what's with these .Where statements? Filtering out test data? So if you go and add some institutiontest3 you'll need to add yet another .Where call?

Don't do that. Make yourself a separate, dev/test database, and have another database for your production data - and use proper configuration to determine which connection string to use to initialize your Session.

TL;DR:

[AjaxOnly]
public ActionResult GetInstitutions(string parent)
{
    var country = _countryRespository.GetByCountryCode(parent);
    if (country == null || !country.Institutions.Any())
    {
        return Json(string.Empty, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
    }

    var institutions = country.Institutions
                              .OrderBy(institution => institution.Name)
                              .Select(institution => new SelectListItem
                              {
                                  Text = institution.Name,
                                  Value = institution.Id.ToString()
                              });
    return Json(institutions, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}

If the filtered-out values are meant to be specific values, consider making them explicit:

var ourInstitutions = new[]
{
    "foo",
    "bar"
};

And then you should be able to do this:

.Where(institution => !ourInstitutions.Contains(institution.Name))

Which makes the intent much clearer. If your ORM complains (looks like you're using NHibernate, which I'm not very familiar with), then make that filtering handled by LINQ-to-Objects instead:

.ToList()
.Where(institution => !ourInstitutions.Contains(institution.Name))

If it's just a few values to iterate, there shouldn't be much of a penalty there, and the readability+maintainability gain is considerable, assuming you're looking for specific values. Otherwise, this would be equivalent:

.Where(institution => !ourInstitutions.Any(ours => institution.Name.Contains(ours.Name))


Create dummy variables in dataframe using for loop and apply lambda

df.apply is essentially a loop and can be slower than vectorized methods.  Here is a proposal without using apply:
First, we can rename the keys in the dictionary to match the column names in the dataframe:
d1 = {k.rsplit('_',2)[0]: v for k, v in d.items()}
#{'t_0': 1, 't_1': 2}

Next step is make a subset of your dataframe, since you are interested in second and subsequent columns; for this, use df.iloc. Then, using df.assign, we can assign the values from the dictionary in the columns we are interested in and compare them with the original values using df.gt, then convert the boolean value to int using df.astype . Finally, we can df.join it back to the original dataframe and use rsuffix argument to rename the columns to add "_result"
sub_df = df.iloc[:,1:] #subsets the dataframe leaving the first column out
out = df.join(sub_df.gt(sub_df.assign(**d1)).astype(int) , rsuffix='_result')

Final code looks like:
d1 = {k.rsplit('_',2)[0]: v for k, v in d.items()}
sub_df = df.iloc[:,1:]
out = df.join(sub_df.gt(sub_df.assign(**d1)).astype(int) , rsuffix='_result')
print(out)

  file  t_0  t_1  t_0_result  t_1_result
0    a  1.5  0.5           1           0
1    b  2.5  1.5           1           0
3    c  3.5  0.0           1           0


Swapping int with string using getchar() and putchar()

Review
Vertical White Space
You have way too many blank lines.
Please remove 90% of them.
Formatting
This code is horribly formatted.
Code is designed for humans to read. Part of that is making sure it is easy to read.
DRY
There is one piece of code that is repeated several times.
for (i = 0; str[i] != '\0'; i++) {
    putchar(str[i]);
}

You can simplify your code by putting this into its own function. Then calling the function when you want to print out the string.
Easier to read
Your comparisons to check for a number is overly complex:
else if(c==2+'0'){

The c is a character so simply compare the user input to the expected character:
 else if (c == '2') {


It might be worth introducing an abstraction for the type of piecewise linear functions that bound your intervals. For example (warning, there might be errors)

class PiecewiseLinear
{
    private readonly Vector2 start;
    private readonly Vector2 end;

    public PiecewiseLinear(Vector2 start, Vector2 end)
    {
        this.start = start;
        this.end = end;
    }

    public double ValueAt(double x)
    {
        if (x >= end.x)
        {
            return end.y;
        }

        return (start + (x / (end.x - start.x)) * (end - start)).y;
    }
}

The class name is not ideal, as the class only deals with a very specialised case, but I can't think of a more specific name.

Anyway, you can now use it like this

var max = new PiecewiseLinear(new Vector2(0, 5), new Vector2(3, 2));
var min = new PiecewiseLinear(new Vector2(0, 4), new Vector2(2, 1));

for (double x = 0; x <= 4; x += 0.25)
{
    Console.WriteLine("({0}, {1})", x, max.ValueAt(x) - min.ValueAt(x));
}


Mixing Python 2 and 3

The program is correct in neither Python 2 nor Python 3.

Your program fails to run at all in Python 3, due to the lack of parentheses when calling

print "You failed to guess in time!"

Also, the raw_input() function does not exist in Python 3.

On the other hand, it's not quite correct under Python 2 either.  These print statements

print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")

would be interpreted as requests to print tuples… complete with parentheses and commas.

Initialization

The number of allowed guesses, 5, is buried in the middle of your program, and should be defined in an obvious place near the top.

The bounds, 1 and 100, are each hard-coded twice.  That is a maintenance pitfall, should you ever need to change the upper bound.  Again, these special numbers should be defined just once in an obvious place.

Loop

The "Take a guess" prompting statement is written twice.  It should be moved inside the loop, at the top of the loop.

@MasayukiFujita and @MathiasPanda have the right idea, I think, to use the count rather than the correctness as the loop condition.  I would go a step further and suggest that counting loops in Python would be more idiomatically written using for counter in range(…).

To distinguish between the winning and losing condition without using a boolean variable or retesting the correctness of the guess, you can take advantage of an obscure Python language feature: an else clause on a loop.  The else clause is executed only when the loop terminates "naturally", rather than due to a break.

Newline management

You'll have a better time printing nice output if you make a habit of always putting your newlines at the end of print statements.

Suggested solution

Here is a program that works in both Python 2 and Python 3.

import random

BOUNDS = (1, 100)
TRIES_ALLOWED = 5

the_number = random.randint(*BOUNDS)

print("\tWelcome to 'Guess My Number'!\n")
print("I'm thinking of a number between %d and %d." % BOUNDS)
print("Try to guess it in as few attempts as possible.\n")

for tries in range(TRIES_ALLOWED):
    guess = int(input("Take a guess: "))

    if guess > the_number:
        print("Lower...")
    elif guess < the_number:
        print("Higher...")
    else:
        print("You guessed it! The number was %d" % (the_number))
        print("And it only took you %d tries!\n\n" % (tries + 1))
        break
else:
    print("You failed to guess in time!\n\n")

# Admittedly a contorted way to write a statement that works in both Python 2 and 3...
try:
    input("Press the enter key to exit.")
except:
    pass


Writing billions of lines to text file in java

It sure sounds like you're running out of memory as you try to build (or allocate) the buffer.

You need to figure out how big a buffer you can (or want to) use. You'll need to ask the system how much RAM it has, and how much is available, and make your buffer that large.
You might get a small boost by opening the file as explicitly write-only.
You'll need to flush the buffer as you go. Something shaped like this psudo-code might work:

free = system.free_ram();
use = hungry * free;
buffer = new bytes_buffer_to_file("filename", size=use);
try{
  current_buffer = 0;
  while(line = get_bytes_needing_to_be_written()){
    if(current_buffer + line.length > use){
      buffer.flush();
      current_buffer = 0;
    }
    buffer.append(line);
    current_buffer += line.length;
  }
}
finally{
  buffer.flush();
  buffer.destroy();
}


Create palindrome by rearranging letters of a word

from collections import deque, Counter

def palindrome_from(letters):
    """
    Forms a palindrome by rearranging :letters: if possible,
    throwing a :ValueError: otherwise.
    :param letters: a suitable iterable, usually a string
    :return: a string containing a palindrome
    """
    counter = Counter(letters)
    sides = []
    center = deque()
    for letter, occurrences in counter.items():
        repetitions, odd_count = divmod(occurrences, 2)

odd_count is a bit of a strange name, because its just whether its odd or even, not really an odd_count

        if not odd_count:
            sides.append(letter * repetitions)
            continue

avoid using continue, favor putting the rest of the loop in an else block. Its easier to follow that way

        if center:
            raise ValueError("no palindrome exists for '{}'".format(letters))
        center.append(letter * occurrences)
    center.extendleft(sides)
    center.extend(sides)

Avoid reusing variables for something different. Changing center to be the whole phrase isn't all that good an idea. I suggest using itertools.chain(sides, center, reversed(sides)) and then joining that.

    return ''.join(center)


Turn a non-blocking concurrent queue into a blocking concurrent queue

As a matter of consistency, we don't need to separate typename declaration for this private function void _push(T&& src), and we can depend on the typename declaration on the class level.

void _push(T&& src)
{
    bool notify = false;

    std::unique_lock<std::mutex> lock(_mtx);
    if (!hasData)
    {
        notify = true;
        hasData = true;
    }

    concurrency::concurrent_queue<T>::push(std::forward<T>(src));

    lock.unlock();

    if (notify)
        _cv.notify_one();
}

bool try_pop(T& dest) is not part of public interface, so we can define it as private.
We can depend on std::forward and modify the interfaces for push as follows:

void push(const T&& src)
{
    _push(std::forward<T>(src));
}
void push(T&& src)
{
   _push(std::forward<T>(src));
}

After adapting all these changes it should be as follows. Please note I don't have the system to compile this code from my end.

#include <concurrent_queue.h>
/**
 * Single producer, single consumer blocking concurrent queue.
 */
template<typename T>
class SPSCBlockingQueue final : public concurrency::concurrent_queue<T>
{
  public:

    void push(const T&& src)
    {
        _push(std::forward<T>(src));
    }
    void push(T&& src)
    {
        _push(std::forward<T>(src));
    }

    /**
     * Pop an element from the head of the queue. This method will wait
     * until there is an item in the queue that can be dequeued.
     *
     * @return the dequeued item.
     */
    T pop()
    {
        T dest;
        try_pop(dest);
        return dest;
    }

  private:

    std::mutex _mtx;
    std::condition_variable _cv;
    bool hasData = false;

    bool try_pop(T& dest)
    {
        std::unique_lock<std::mutex> lock(_mtx);

        auto res = concurrency::concurrent_queue<T>::try_pop(dest);
        if (!res)
        {
            // The queue must be empty.
            hasData = false;

            // Wait until there is some data...
            _cv.wait(lock, [&] { return hasData; });

            // This should now work.
            res = concurrency::concurrent_queue<T>::try_pop(dest);
        }

        // res should be true.
        return res;
    }

    void _push(T&& src)
    {
        bool notify = false;

        std::unique_lock<std::mutex> lock(_mtx);
        if (!hasData)
        {
            notify = true;
            hasData = true;
        }

        concurrency::concurrent_queue<T>::push(std::forward<T>(src));

        lock.unlock();

        if (notify)
            _cv.notify_one();
    }
};


var result = new List<ScrapCategory>();
    ...
                if (!result.Contains(parent))

There's one performance problem. Use a data structure which gives fast Contains checks: typically HashSet<>.

                var parent = categories.Where(x => x.Id == parentId)?.First();

There's another one. I assume that IDs are unique, in which case lookup = categories.ToDictionary(category => category.Id) will give you a fast hash map from ID to category.

        if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
            result.Add(category);

        if (category.ParentId > 0)
        {
            int parentId = category.ParentId;

            while (parentId > 0)
            {
                ...
            }
        }

Is this definitely correct? It's not supposed to be

        if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
        {
            result.Add(category);

            if (category.ParentId > 0)
            {
                ...
            }
        }

?

Either way, the if (category.ParentId > 0) is pointless. The test is repeated by the while loop, and a single assignment to a local variable isn't going to be a performance bottleneck.

                if (!result.Contains(parent))
                    result.Add(parent);

Note that with the suggestion of making result a HashSet it becomes preferable to just call Add, which returns a bool to tell you whether it changed anything. If it didn't, you can break out of the loop, because you know that all of the further ancestors have already been added.

The effect of these changes (except the one I'm unsure about) is

public ScrapCategory[] Filter(ScrapCategory[] categories, string searchString)
{
    var lookup = categories.ToDictionary(category => category.Id);
    var result = new HashSet<ScrapCategory>();

    foreach (ScrapCategory category in categories)
    {
        if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
            result.Add(category);

        int parentId = category.ParentId;
        while (parentId > 0)
        {
            var parent = lookup[parentId];
            if (!result.Add(parent))
                break;
            parentId = parent.ParentId;
        }
    }

    return result.OrderBy(x => x.Level).ToArray();
}


Using model view presenter (MVP) in C# code

I think your question would be better if you fleshed it up with your actual working code, there's a lot of "placeholder" code in your post, which makes it border the line of off-topicness.
You may be able to find more information and high-level design guidance about MVP on Programmers.SE.

There isn't a lot to review here, but this is jumping at me:
public static Employee GetEmployeeData(String employeeID)

And then:
Employee Emp = EmloyeeDataService.GetEmployeeData(employeeID);

By doing that, you have tightly coupled the EmployeePresenter class to the EmployeeDataService class. The static method makes the ViewEmployee method harder to unit test - now whatever you do, if you call ViewEmployee you're going to call EmloyeeDataService.GetEmployeeData.
If you code to an abstraction instead of an implementation:
public interface IEmployeeRepository
{
    Employee GetById(string employeeId);
}

public class EmployeeDataService : IEmployeeRepository
{
    public Employee GetById(string employeeId)
    {
        // do whatever it takes to return an Employee object.
    }
}

Here you're accessing an SQL database with ADO.NET, but then later you might want to implement the same interface with Linq-to-SQL, or with Entity Framework - actually, the data could just as well be in XML files on the file system, or on Azure (cloud), or retrieved with some web service - all you need to care is the object's interface, which takes an employeeId and returns an Employee. Exactly how that's done, is irrelevant to the Presenter:
class EmployeePresenter
{
    private readonly IEmployeeRepository _service;

    public EmployeePresenter(IEmployeeRepository service)
    {
        _service = service;
    }
}

Now whoever is instantiating an EmployeePresenter will also need to instantiate some implementation of IEmployeeRepository, and inject that implementation into the presenter's constructor; you're no longer strongly coupled with a specific implementation, and you can change that anytime, without rewriting anything in the EmployeePresenter code.

This is more about SOLID and DI/IoC than MVP. I suggest you look at this read from Martin Fowler about GUI architectures, there's a section on MVP.
However I can tell you that this isn't MVP:
partial class frmEmployeeDetails : Form
{
    btnViewEmployee_Click() //Button Event
    {
        EmployeePresenter.ViewEmployee(txtEmployeeID.text,this);
    }
}

The Form shouldn't know anything about a presenter, or any repository or service - it's just a view. Instead, you fire events that the presenter can listen to, and respond. Shortly put, the Hollywood Principle: don't call them, they'll call you.


Response to an answer: Solution to maxMirror problem

This is looking very good.

First thing I would do is split out a method, GetMaxMirror, and rename maxLength to maxMirror. Then I would put braces around the break, maybe invert the condition if (sequence[frontIndex] == sequence[i]) to reduce nesting, and call it a day.

Ah, whoops, this fails on an empty array by returning the answer 1. Fix, add a unit test, and now we're really done.

Until... I notice that the complexity looks like it's \$O(n^3)\$. Let's increment a counter in the inner while:

while (frontIndex + currentLength < sequence.Length && i - currentLength >= 0)
{
    steps++;
    ...

And run it on our test cases:

GetMaxMirror took 15 steps.
Max length is 5
GetMaxMirror took 9 steps.
Max length is 3
GetMaxMirror took 3 steps.
Max length is 3
GetMaxMirror took 7 steps.
Max length is 2

Not bad!

And after a bit of playing around, we find that it runs badly on this input

private static int[] GetBadInput(int length)
{
    var result = new int[length];
    result[length / 2 - 1] = 1;
    return result;
}

Now let's run it again:

sequences.Add(GetBadInput(1000));
sequences.Add(GetBadInput(2000));
sequences.Add(GetBadInput(3000));

GetMaxMirror took 104664252 steps.
Max length is 999
GetMaxMirror took 835328502 steps.
Max length is 1999
GetMaxMirror took -1477974544 steps.
Max length is 2999

Ahhhh... integer overflow in our counter? Not good.

So what can we do? Let's look at the problem statement again.

  We'll say that a "mirror" section in an array is a group of contiguous
  elements such that somewhere in the array, the same group appears in
  reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the
  largest mirror section found in the given array.

So we're looking for the longest contiguous sequence that appears in the input, and its reversal. This sounds like another problem, longest common substring (LCS).

In particular,

$$
maxMirror(S) = LCS(S, T)
$$

where \$T\$ is \$S\$ reversed. If we can solve LCS, then we have a solution to maxMirror. Using dynamic programming, we can solve LCS in \$O(n^2)\$ time, with \$O(n)\$ space.

The pseudocode in that article is pretty good, so let's translate that to C#:

private static int GetMaxMirrorLcs(int[] sequence)
{
    var length = sequence.Length;
    var prevRow = new int[length];

    var maxMirror = 0;
    for (var i = 0; i < length; i++)
    {
        var row = new int[length];
        for (var j = 0; j < length; j++)
        {
            if (sequence[i] != sequence[length - j - 1])
            {
                continue;
            }

            row[j] = (i == 0 || j == 0)
                ? 1
                : prevRow[j - 1] + 1;
            maxMirror = Math.Max(maxMirror, row[j]);
        }

        prevRow = row;
    }

    return maxMirror;
}

Since we split out our method before, it's easy to test that these give the same results:

foreach (var sequence in sequences)
{
    int maxMirror = GetMaxMirror(sequence);
    int maxMirrorLcs = GetMaxMirrorLcs(sequence);
    if (maxMirror != maxMirrorLcs)
    {
        Console.WriteLine("Answers don't match!");
        Console.WriteLine("Input: [{0}].", string.Join(", ", sequence));
        Console.WriteLine("GetMaxMirror: {0}. GetMaxMirrorLcs: {1}.", maxMirror, maxMirrorLcs);
    }
}


Axiomatic proofs of natural addition properties, in Idris

Inlining the second clause fails because you're shadowing Refl.

plus_assoc (S a) b c = let Refl = plus_assoc a b c in Refl

just reduces to

plus_assoc (S a) b c = plus_assoc a b c


The relevant NSFileManager call, in Foundation, is - setAttributes:ofItemAtPath:error:, and it is the same in iOS as in Mac OS X.  (It's funny that you already call - isExecutableFileAtPath: in the same NSFileManager class.)  Even if you weren't familiar with Foundation, you would still be better off calling the POSIX function chmod(2) rather than the chmod(1) command.

You've neglected to do any kind of error handling on the /bin/chmod task.  The operation could easily fail if, for example, the user did not have permission to modify the file.

It's misleading to name the parameter of runSystemCommand() cmd, as it really only contains the path to the file whose permissions are to be toggled.


First of all, I suggest you read pep8 (https://pep8.org/). I see you have violations. Understanding pep8 is a must if you want to be a pro Python developer. Better yet, use flake8 to automatically find pep8 violations in your code.

Second, using that many elif statements is always a red flag, especially when they seem to be doing the same thing. Can you somehow get rid of that duplication?

Next, put some blank lines between logical blocks of code to improve readability. In Game.start the try catch block is logically separate from the conditional following it, for example.

Next, give your variables meaningful names. For example, game.start is much better than obj.start. Also, avoid using shortened version of words, like object -> obj because it doesn't add much value and can decrease readability.

Finally, I'd like to see some tests. Not because I think your code has a bug but because I want to know how your code actually works. Because there's some logical reasoning in the nature of the problem, you can help the reader by documenting the algorithm you've implemented. Unit tests are perfect for this. They're fast, they target specific conditions one at a time, and document your code better than comments.
If you're wondering where to start when it comes to testing your code I suggest watching some videos on TDD in action. Kent Beck and Uncle Bob have some free videos showing how to do TDD step by step.


Generating all variations of M*N matrix containing boolean values

The code does not produce permutations. It produces the subsets of \$M * N\$-strong set. Below assumes that it is the goal of the code.

Recursive solution is correct, but may take too much memory (there are exponentially many subsets, namely \$2^{N*M}\$ of them). I strongly recommend to switch to an iterative approach:

    bool next_subset(int [] subset) {
        for (int i = 0; i < subset.size(); i++) {
            if subset[i] == 1) {
                subset[i] == 0;
            } else {
                subset[i] = 1;
                return true;
            }
        }
        return false;
    }

which takes the same time, linear memory, and can be used to stream the subsets one-by-one.


Finding k largest (or smallest) elements in an array

You can write it without extra space and with one less variable. Instead of considering a new array (temp array), do all the swap in the original array; in this case, you will skip O(k) extra space. Also, there is no need to keep track of min value. Keep tracking of min index and update it in every round will be enough.

public static void kLargest2(int[] array, int k){

    int minIndex = 0, i;                            //Find Min

    for (i = k; i < array.length; i++){
        minIndex = 0;
        for (int j = 0; j < k; j++){
            if(array[j] < array[minIndex]){
                minIndex = j;
                array[minIndex] = array[j];
            }
        }
        if (array[minIndex] < array[i]){         //Swap item if min < array[i]

            int temp = array[minIndex];
            array[minIndex] = array[i];
            array[i] = temp;
        }
    }
    for (int q = 0; q < k; q++){                            //Print output
        System.out.print(array[q] + " ");
    }
}


With help from @Ingo I got it down to the following, which I think is better.

var innerWork = $('div.indexWorkDetailsInner');
var innerImg = $('div.indexMonitorWork img');

// Add the active class to the first element
innerWork.first().addClass('active');
innerImg.first().addClass('active');

function workAnimate(direction){

    var signOne, signTwo;

    if(direction === "right" ) { signOne = '-'; signTwo = ''; }
    if(direction === "left" ) { signOne = ''; signTwo = '-'; }

    innerWork.not('.active').css({'left': signOne + '450px'}); // Move the not active text to the left
    innerImg.not('.active').css({'left': signOne + '370px'}); // Move the not active images to the left

    // Animate the active element off the screen
    innerWork.filter('.active').stop().animate({'left' : signTwo + '450px'}, 1000, function () {

        $(this).removeClass('active').css({'left': signOne + '450px'}); // Remove the active class, and move element back to the left
        if(direction === "right" ) {
            $(this).next(innerWork).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view
            innerWork.filter(':last').after(innerWork.filter(':first')); // Move the last element to after the first
        } else {
            innerWork.filter(':first').before(innerWork.filter(':last')); // Move the first element before the last item
            $(this).prev(innerWork).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view
        }
    });

    // Animate the active element off the screen
    innerImg.filter('.active').stop().animate({'left' : signTwo + '370px'}, 1000, function () {

        $(this).removeClass('active').css({'left': signOne + '370px'}); // Remove the active class, and move element back to the left
        if(direction === "right" ) {
            $(this).next(innerImg).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view
            innerImg.filter(':last').after(innerImg.filter(':first')); // Move the last element to after the first
        } else {
            innerImg.filter(':first').before(innerImg.filter(':last')); // Move the first element before the last item
            $(this).prev(innerImg).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the previous element in to view
        }
    });
}

// Next Button Click
$('div#indexWorkRight').on('click', function() {
    workAnimate('right');
});

// Previous Button Click
$('div#indexWorkLeft').on('click', function() {
    workAnimate('left');
});


Fun question!
Usually when I find myself doing something like this: select="/people/person[@name=$myname]", I'll use an xsl:key instead.
You could use that key to collect all of the parents based on the parent person's @name in a variable.
If you could treat that variable as a node-set (either XSLT 2.0+ or EXSLT's node-set() function) getting the count of ancestors would simply be a matter of counting the number of items in the node-set (count()).
Another option, which feels a little hacky in my opinion, is to output a separator along with the ancestor name.
To get the ancestor count you can remove all characters other than the separator character (nested translate()) and then count the number of separators (string-length()).
You'd also need to replace all of the separators with a space when you finally output the ancestor names (another translate() call).
Example...
XML Input
<people>
    <person name="adam"/>
    <person name="eve"/>
    <person name="cain">
        <parent name="adam"/>
        <parent name="eve"/>
    </person>
    <person name="henoch">
        <parent name="cain"/>
    </person>
    <person name="gladys"/>
    <person name="frank">
        <parent name="henoch"/>
    </person>
    <person name="jose">
        <parent name="gladys"/>
        <parent name="frank"/>
    </person>
</people>

XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="parent" match="parent" use="../@name"/>

  <xsl:template match="person">
    <xsl:variable name="ancestors">
      <xsl:apply-templates select="key('parent',@name)"/>
    </xsl:variable>
    <xsl:variable name="ancestor_count"
      select="string-length(translate($ancestors,translate($ancestors,'|',''),''))"/>
    <xsl:value-of select="concat(@name,'(',$ancestor_count,'): ',translate($ancestors,'|',' '))"/>
    <xsl:text>&#xA;</xsl:text>
  </xsl:template>

  <xsl:template match="parent">
    <xsl:value-of select="concat(@name,'|')"/>
    <xsl:apply-templates select="key('parent',@name)"/>
  </xsl:template>

</xsl:stylesheet>

Output
adam(0):
eve(0):
cain(2): adam eve
henoch(3): cain adam eve
gladys(0):
frank(4): henoch cain adam eve
jose(6): gladys frank henoch cain adam eve

Fiddle: http://xsltfiddle.liberty-development.net/3MEdvhm


How do you tell what the student type is, without erroring on both International and Domestic?

With your current code, you'd have to do something like:

if hasattr(student, 'student_type'):
    student_type = student.student_type()
else:
    student_type = None

What makes this worse, is you assume None to be International.
Why can't Domestic students have international_documents?

In your requirements you state:

  Domestic students don't require documentation
  International student do require documentation (passports, etc..)

Why should these be separate classes?
Your name mangled variables make your code longer, and generally more horrible to read.
Instead you could make them just normal properties.

However, since they are unsetable, you may want to use a namedtuple instead.

And so I'd use something like:

from collections import namedtuple
from Enum import enum

class StudentType(Enum):
    INTERNATIONAL = 'international'
    DOMESTIC = 'domestic'

Student = namedtuple('Student', 'id first_name last_name type documents')

s1 = Student(0, 'John', 'Doe', StudentType.INTERNATIONAL, [...])
s2 = Student(1, 'Eva', 'Smith', StudentType.DOMESTIC, [])


If you want a combination of readability and performance, consider the following solution.

public class Primes {
    private final boolean[] isComposite;
    private int n = 2;

    public Primes(int sieveSize) {
        this.isComposite = new boolean[sieveSize];
    }

    public static int overestimateOfNthPrime(int n) {
        // http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
        return (int)(1.5 * n * Math.log(n));
    }

    public int next() {
        try {
            return n;
        } finally {
            // Sieve of Eratosthenes: mark multiples of n as composite
            for (int i = 2 * n; 0 <= i && i < this.isComposite.length; i += n) {
                this.isComposite[i] = true;
            }
            do {
               n++;     // TODO: check array bounds
            } while (this.isComposite[n]);
        }
    }

    public static long sumFirstPrimes(int n) {
        Primes primes = new Primes(overestimateOfNthPrime(n));
        long sum = 0;
        while (n-- > 0) {
            sum += primes.next();
        }
        return sum;
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        System.out.println(sumFirstPrimes(Integer.parseInt(args[0])));
        System.err.println(System.nanoTime() - start);
    }
}

If your concern is "people first", then I think this is an improvement.  The sumFirstPrimes() function is more readable because the code that discovers more primes is decoupled from the code that sums them.  There are no magic numbers like 5 and 6, and no weird special cases.  Note that the readability comes mainly from the code structure, not from the comments on the code.

If your concern is performance, then the Sieve of Eratosthenes is a better algorithm for discovering many prime numbers.  It doesn't matter how many ugly hacks you use to optimize your trial division method — the Sieve simply scales better (up to a point).

$$\begin{array}{r|r|r}
\textrm{First } n \textrm{ primes} & \textrm{Legato's trial division} & \textrm{200_success's sieve} \\
\hline
10^3 &         ~1000\ \mathrm{\mu s} & ~2000\ \mathrm{\mu s} \\
10^4 &           ~10\ \mathrm{ms}    &   ~10\ \mathrm{ms}    \\
10^5 &          ~125\ \mathrm{ms}    &   ~40\ \mathrm{ms}    \\
10^6 &         ~4000\ \mathrm{ms}    &  ~500\ \mathrm{ms}    \\
10^7 & \color{gray}{\textit{DNF}}    &    ~7\ \mathrm{s}     \\
\end{array}$$

In the interest of full disclosure…

Making the estimate of the nth prime takes some mathematical knowledge.
I trust the estimate, so I didn't bother to check the array bounds.
For truly large problems (e.g 108), memory management for the Sieve would be a chore.


Transforming a Python dictionary into CSS

#pss.py

I'd recommend an actual docstring rather then a comment

__version__ = '1.0'

class PSS:
    def __init__(self, obj):
        if type(obj) is not dict:
            raise RuntimeError('There\'s no any objects to parse!')

What if its a subclass of dict? What if its a dict-like object? In python we generally do not check types. So I'd just remove this bit. I'd also name it something more meaningful then obj

        self.obj = obj
        self.__data = {}

Use of __ is controversial. I'm in the camp that you should only use one undescore.

    def __repr__(self):
        return self.__build(self.obj)

This isn't what __repr__ is for. __repr__ should give a python representation of your object, not produce the string version. Look at repr() vs str() on python strings.

    def __build(self, obj, string = ''):
        self.__parse(obj)

Why parse here instead of in the constructor?

        for i in sorted(self.__data.keys()):

i is a terrible name, it usually means index but you aren't using it that way here

            if self.__data[i]:

Use for key, value in sorted(self.__data.items()): then you won't need to access self.__data[i]

                string += i[1:] + ' {\n' + ''.join(self.__data[i]) + '}\n\n'

Adding strings can be expensive. Its generally better to build the strings in a list and then join them or use StringIO, and write the string pieces by piece.

        return string

    def __parse(self, obj, selector = ''):
        for i in obj:

use for key, value in obj.items() whenever you need both the keys and values in a dict. Python isn't stupid like some other languages

            if type(obj[i]) is dict:

Checking types is considered bad form in python. If you must differentiate between types it is perferred to check some aspect of the dict interface, such as the items method.

                rule = selector + ' ' + i

I'd store these as tuples rather then strings.

                self.__data[rule] = []
                self.__parse(obj[i], rule)

            else:
                prop = self.__data[selector]
                prop.append('\t%s: %s\n' % (i, obj[i]))

Again, I'd store this as something besides a string. Probably keys in a dictionary.

        return self

Why return self

Parsing usually refers to converting text into some internal representation. But you are actually doing the opposite. You are converting python objects into partial python objects, partial text. That's simply not parsing. Its also not clear that you gain anything by doing this pre-processing before converting entirely over to text.

from pss import *

css = PSS({
    'html': {
        'body': {
            'color': 'red',
            'div': {
                'color': 'green',
                'border': '1px'
            }
        }
    }
})

I must admit that looks pretty sweet.

Interface-wise, why is this a class? It seems to me that is should be a function. Its a one way transformation from dicts to css string representation. That seems to me to be a fit for a function not a class.

Here is my tackle at the problem:

from StringIO import StringIO

def write_css(selector, data, output):
    children = []
    attributes = []

    for key, value in data.items():
        if hasattr(value, 'items'):
            children.append( (key, value) )
        else:
            attributes.append( (key, value) )

    if attributes:
        print >> output, ' '.join(selector), "{"
        for key, value in attributes:
            print >> output, "\t", key + ":", value
        print >> output, "}"

    for key, value in children:
        write_css(selector + (key,), value, output)

def PSS(data):
    output = StringIO()
    write_css((), data, output)
    return output.getvalue()


Handle Java Process outputs without extra-threads

Is inputStream.available() a blocking method?

The process might send an error message while your are blocked (possibly forever) in the standard output available() waiting for something that will never arrive.


Red-black tree not matching performance of Java's TreeMap

My own tests

I ran your program with various inputs, and in all my tests, your red black tree was faster than the TreeMap version.  I even fixed the TreeMap version so that it wouldn't search up to three times for the same word:

        Integer val;
        arr=line.split(" ");

        for(String k:arr) {
            val = tm.get(k);
            if (val == null) {
                tm.put(k,1);
            } else {
                int newVal = val + 1;
                tm.put(k, newVal);
                if (newVal > max) {
                    S = k;
                    max = newVal;
                }
            }
        }

With the above change, the TreeMap version is about 10% slower than your red black tree.  It makes sense that the red black tree version would be faster because in the TreeMap version, you have a get followed by a put for each string.  In your red black tree version, you only have one insert which performs both functions.

Comments on your code

There were several places where I thought you squished your code when you didn't have to.  For example:

 else {x=new Node(key,x.value+1,x.color,x.left,x.right);}

 if(isRed(x.right)&&!isRed(x.left))   x=rotate_left(x);
 else if(isRed(x.left)&&isRed(x.left.left)) x=rotate_right(x);
 else if(isRed(x.left)&&isRed(x.right)) flip_color(x);

and

Node left,right;static int max=0;static String S="";

I feel like you should space your code out and keep your statements on separate lines from the if and else.

Improvement to red black tree

In your red black tree code, where you have this:

 else {x=new Node(key,x.value+1,x.color,x.left,x.right);}

it could be faster if you don't allocate a new node and instead modify the current one.  Also, you could make the insert faster by only calling the comparison function once.  Here is a rewrite of your insert() function that makes your program about 10% faster than before:

public static int max;
public static String S;
public Node insert(Node x,String key)
{
    if (x == null) {
        if (max == 0) {
            max = 1;
            S = key;
        }
        return new Node(key,1,'R',null,null);
    }
    int comparison = key.compareTo(x.key);
    if (comparison > 0) {
        x.right = insert(x.right,key);
    } else if (comparison < 0) {
        x.left = insert(x.left,key);
    } else {
        x.value++;
        if (x.value > max) {
            max = x.value;
            S = key;
        }
    }
    if (isRed(x.right) && !isRed(x.left)) {
        x = rotate_left(x);
    } else if (isRed(x.left) && isRed(x.left.left)) {
        x = rotate_right(x);
    } else if (isRed(x.left) && isRed(x.right)) {
        flip_color(x);
    }
    return x;
}

Try HashMap instead

What I think you are missing is that a HashMap is faster than both the TreeMap and the red black tree.  I replaced the TreeMap with a HashMap and the result was about 50% faster than the TreeMap and about 25% faster than the improved red black tree.


Adding checks? Just specify

set -e

at the beginning of the script. Should any command fail, the script will stop running, instead of wreaking more damage.

Using variables for repeated paths might make the script more readable.

tomcat1=/home/deploy/tomcatfirst
tomcat2=/home/deploy/tomcatsecond

sh "$tomcat1"/bin/catalina.sh stop

(BTW, shouldn't the second stop use $tomcat2?)

Once you have them, changing the above line to

set -eu

might be another improvement - the script will fail if a variable is not defined, which can happen if you mistype its name.

As the commands for both the server are the same, you can wrap them in a loop:

for tomcat /home/deploy/tomcat{first,second} ; do
    sh "$tomcat"/bin/catalina.sh stop
    # ...
done

If the servers are critical, you should specify the commands with full paths (e.g. /bin/mkdir).


Questions:

Why do you use the class field _object? Does it serve any real purpose that a method-local variable cannot?
Why do you implement IEnumerable?
(only consider this if you have a decent understanding of concurrency issues, and want to practice) How can you make this code thread-safe?

Suggestions:

Several method throw exceptions in unexceptionable scenarios. Why do you blow up if I want to print or clear an empty stack? That's like having the waiter shoot herself if I try to order food right as the kitchen has closed.
When you're done with the exercise, consider making your stack generic. Casting from object is so old-school C#.
Consider improving your error messages. For one, "Cannot use .Pop() if list count equals 0." could be something like: "Cannot pop an element off an empty stack".


K&R 2.6 Exercise setbits(x,p,n,y) function

Your example, which uses x = 0 and y = ~0, is not a very useful demonstration, as those degenerate cases would tend to let bugs remain undetected.

You have some common expressions that reappear several times, which should be given variable names:

(p+1-n) appears three times in result.  I would name it shift.
~(~0 << n) appears in ybits, but it is the same as helper.  I would name it mask.

I would write it as (1 << n) - 1 instead.  It's probably not any more or less efficient than ~(~0 << n).  However, you use bitwise negation a lot.  When you write (~(helper << (p+1-n))), that's a negation of a negation of a negation, which I find headache-inducing.

Conversely, you gave variable names to ybits and result, neither of which provide any benefit.

Your strategy is, in summary:

(x | ForceRelevantBitsOn) & ((ybits << ShiftToRelevantPlace) | OnesEverywhereElse)

However, that strategy requires you to construct OnesEverywhereElse.  I recommend the following simpler technique instead:

(x & ForceRelevantBitsOff) | (ybits << ShiftToRelevantPlace)

Here's how I would write it:

unsigned setbits(unsigned x, int p, int n, unsigned y) {
    int shift = p - n + 1;
    unsigned mask = (1 << n) - 1;
    return (x & ~(mask << shift)) | ((y & mask) << shift);
}

The last line could be replaced with this expression, which might be more efficient (using five operations instead of six), but is more cryptic:

    return ((((x >> shift) ^ y) & mask) << shift) ^ x;

That works by determining which bits in x need to be toggled.


Sanity Checking an unordered_set of unique_ptrs to objects

Consider specializing standard templates

If the key fields of your structure are general, wherever it is used (rather than being a subset chosen for this particular set), then you could specialize std::hash and std::equal_to instead of declaring your own functors:

#include <functional>
namespace std
{
    template<>
    std::size_t hash<TestPtr>::operator()(TestPtr const& s) const
    {
        if (!s) return 0;
        auto h1 = std::hash<std::string>{}(s->strVal);
        auto h2 = std::hash<int>{}(s->intVal);
        auto h3 = std::hash<int>{}(s->intVal2);
        return h1 ^ (h2 << 1) ^ (h3 << 2);
    }

    template<>
    bool equal_to<TestPtr>::operator()(TestPtr const& lhs, TestPtr const& rhs) const
    {
        return lhs
            && rhs
            && lhs->strVal == rhs->strVal
            && lhs->intVal == rhs->intVal
            && lhs->intVal2 == rhs->intVal2;
    }
}

using TestSet = std::unordered_set<TestPtr>;

Notes on the test program

I prefer to separate the test code (in Real Life, you'd put it in a separate file):

#include <functional>
#include <memory>
#include <string>
#include <unordered_set>

struct TestRecord
{
   // and the rest of the production code
};

// --- test code follows

#include <iostream>
#include <list>
bool DoThings(const std::string context, const TestPtr& item)
{
   //
   return true;
}

int main()
{
   // Note: omitted arguments, which weren't used
}

When you move the production code to a header, you don't have to strip out the unnecessary includes.

The return value of DoThings() is ignored; either use it, or return void.

When inserting, it's more idiomatic to call insert() rather than a separate find() step.  The return value tells you whether your value was inserted - if it wasn't, you also get an iterator to assign to.  However, as you've observed, you aren't able to perform the assignment if you passed your value by rvalue reference.  Still, I'd try to encapsulate this in a method:

auto insert_or_assign(TestSet& set, TestPtr&& value)
    -> std::pair<TestSet::iterator, bool>
{
    auto overwrite = set.erase(value);
    auto r = set.insert(std::move(value));
    r.second = !overwrite;
    return r;
}

You can then use it like this:

int main()
{
    std::vector<TestPtr> thisList;

    thisList.emplace_back(new TestRecord{ "name", 1, 2, "Other" });
    thisList.emplace_back(new TestRecord{ "name2", 1, 2, "Less" });
    thisList.emplace_back(new TestRecord{ "name", 3, 2, "Is" });
    thisList.emplace_back(new TestRecord{ "name", 1, 5, "More" });
    thisList.emplace_back(new TestRecord{ "name2", 1, 2, "More" });

    TestSet thisSet;
    for (auto& t: thisList) {
        auto inserted = insert_or_assign(thisSet, std::move(t));
        DoThings(inserted.second ? "new node" : "replace", *inserted.first);
    }
}


I suggest storing your defaults in a location that can be reached by the developers, and automatically filling in the minsize if minsize is included in the default text. For example,

(function ($) {
    "use strict";

    $.fn.counter = function (options) {
        options = $.extend($.fn.counter.defaults, options);

        function defaultText() {
            return options.defaultText.replace(/minsize/ig,options.minimumSize);
        }
        function count(elem) {
            var size = elem.val().length, target = elem.siblings(options.targetClass);
            if (size === 0) {
                target.html(defaultText());
            } else if (size < options.minimumSize) {
                target.html((options.minimumSize - size) + options.minimumWarning);
            } else if (size >= options.minimumSize && size < options.warningSize) {
                target.html('&nbsp;');
            } else if (size >= options.warningSize && size < options.maximumSize) {
                target.html((options.maximumSize - size) + options.maximumWarning);
            } else if (size >= options.maximumSize) {
                elem.val(elem.val().substring(0, options.maximumSize));
                target.html("0" + options.maximumWarning);
            }
        }

        this.each(function () {
            var elem = $(this);
            count(elem);
            elem.keyup(function () {
                count(elem);
            });
            elem.closest('form').submit(function () {
                if (elem.val().length < options.minimumSize) {
                    $(this).find(options.targetClass).fadeOut('fast').fadeIn('fast').fadeOut('fast').fadeIn('fast');
                    return false;
                }
            });
            return elem;
        });
    };

    $.fn.counter.defaults = {
        minimumSize: 15,
        minimumWarning: ' more to go...',
        maximumSize: 25,
        maximumWarning: ' characters remaining...',
        warningSize: 20,
        targetClass: '.help-block',
        defaultText: 'Enter at least minsize characters.'
    };
})(jQuery);


I like your answer. It looks a bit like a counting sort, which is very fast. I expect it's faster than a few of the other answers, although Joseph's answer is cleaner and more readable for sure. If I'm not mistaken your implementation is O(n) (which is excellent).

A couple (minor) things:

Using a dictionary/ hashtable would make more sense than using an array to store the frequency of each number. I'm not sure if creating an array then setting the 10,000th index (eg, if var A=[10000, 1, 1, 5]) as something takes a lot of memory (I don't use js a lot).

if( tempArray[newIndex] === undefined){

can just be

if(!tempArray[newIndex]){

Formatting. Your indentation is all over the place. This is probably due to the copy paste into the text box, but if not this is the biggest thing to make your code more readable.

You have 2 semi-colons:

var tempArray = new Array();;

Lastly, a few comments and better variable names could really help. "A" should be something more descriptive. Ps: The variable A in

function solution(A) {

doesn't have to be the same name as

var A =  [22, 25, 3, 3, 1, 2, 0, 0,100,22,25,1,2]; // returns 100
solution(A)

Though it works fine if it's the same name. I wasn't sure if this was a coincidence or because you didn't know this, but I thought I'd mention it.

That's about all from me... I don't code a lot in js, so any comments are welcome if I've made mistakes above (but I think most of it's pretty applicable).


Max and Min in array using minimum comparisons

First of all, format your code. Indentation goes along way. If everything is left-justified, you can't make out any of the logic.

Secondly, this is a good idea:

max=n[0];min=n[1];

But we should really initialize both to n[0], and on separate lines:

max = n[0];
min = n[0];

The reason is this allows us to start at index 1:

for (i=1; i<c; ++i) {
    if (n[i] > max) {
        max = n[i];
    }
    else if (n[i] < min) {
        min = n[i];
    }
}

We could also consider putting this into a function:

void minmax(int* arr, int len, int* min, int* max) { ... }

minmax(n, c, &min, &max);

Any time you're doing something k times for some constant, or filling in an array - do it front to back. It will be much easier to understand. Don't fill n from index 9 to 0... fill it from 0 to 9. Also, prefer a for loop to a while loop and use i both times:

int c=10, n[10];
for (i=0; i<c; ++i) {
}

And lastly, c is a bad name for the max size of your array. Something like SIZE or LENGTH or anything to that effect would be better.


# Save the file
img = urllib2.urlopen(imgurl)
localFile = open('desktop.jpg', 'wb')
localFile.write(img.read())
localFile.close()

For opening file it's recommend to do:

with open('desktop.jpg','wb') as localFile:
     localFile.write(img.read())

Which will make sure the file closes regardless.

Also, urllib.urlretrieve does this for you.


I think this is pretty good. I would maybe replace the word "list" with "values".

That said, I think you can simplify this code a bit if you embrace newer versions of js, and perhaps with the use of lodash.

Just a quick example of what you could do:

const _ = require('lodash');

async function hash(hashOfPromises){
    let keys = Object.keys(hashOfPromises);
    let promises = keys.map(key => hashOfPromises[key]);
    let values = await Promise.all(promises);

    return _.zipObject(keys, values);
}


Run dir scan as fast and efficient as possible / clean code

Naming things

Be consistent in the way you name things. This applies to the words chosen, whether you abbreviate things or not, whether you separate multiple words or not. There are some names you are using that are not consistent. For example:

def get_size_and_fcount_pathlib(scan_path):

You start with fully spelled out words separated by underscores, and then suddenly there is fcount, two words without separators and with one word being abbreviated. I would start by writing this out consistently as:

def get_size_and_file_count_pathlib(scan_path):

If you want to reduce the size of the name, I would rather omit redundant parts of it. Is pathlib really adding anything to this? If get_size_and_file_count() gives you enough context to deduce what the function does, I would go for that.

Another issue is with this variable:

file_count_collection = [size_gb, all_types_count, file_count, folder_count]

It says it is a file count collection, but it also contains the total size. I would change this to size_and_file_count_collection, to make it clear it also contains the size, and this also better matches the name of the function. Again, if you want to make it shorter, I would then drop _collection from the name, since size_and_file_count already implies it is more than one bit of information.

Arguably, size_and_file_count is also not completely descriptive since it also includes directory count and a count of all types of filesystem entities.
There might be an even better name for this, perhaps directory_statistics?

Use a class to represent structured data

The file_count_collection is just a list. Unless you read the code of this function, it is not obvious in which order you stored the size and counts in this list. It is better to create a class that represents this collection of data, where each piece will get its own name, like so:

class size_and_file_count:
   def __init__(self, size_gb, all_types_count, file_count, folder_count):
       self.size_gb = size_gb
       self.all_types_count = all_types_count
       self.file_count = file_count
       self.folder_count = folder_count

Then, in get_size_and_file_count(), you can replace the last two lines with:

return size_and_file_count(size_gb, all_types_count, file_count, folder_count)

And in the code that calls that function, instead of writing:

result = get_size_and_file_count("...")
file_count = result[2]

You can now write:

result = get_size_and_file_count("...")
file_count = result.file_count

Don't convert values too early

You are calculating the total size, and then converting it to a value in gigabytes (with only 2 decimals), and only storing that final result. What if I want to get the size of a directory that contains less than 10 megabytes of data? Your function will tell me it is 0.00 gigabytes big, which is not helpful. It is better to store the size in bytes, and only convert to gigabytes when printing the result, like so:

print('Directory size in GB:         {:.2f} GB'.format(total_size / 1.0e9))

And of course also store the total size in bytes in the returned collection.

Separate obtaining results from printing results

Your function does two things at once: it calculates the results and it prints them. It is best to separate the two issues, and have get_size_and_file_count() only calculate the results and return them, and then have a seperate function that takes a size_and_file_count variables as a parameter and prints the values to the screen.

If you have made a class size_and_file_count, you could make the function that prints the results a member function of that class.

What is all_types_count?

There are many different types of filesystem entries besides regular files and directories; there are fifos, sockets, symlinks, character devices and so on.
I would expect a variable named all_types_count to count all of them. However, in your code you actually disregard all things that are neither regular file nor directory, and instead all_types_count just counts those regular files whose name does not start with .. So actually your all_types_count is just a non_hidden_files_count. Either this was your intention, in which case you should rename the variable, or you actually wanted to count all filesystem items, in which case your count is wrong.

Optimizing the code

If you want to make the code as fast as possible, there are several ways to do that. First, I would start by replacing the call to glob() with os.walk(). Since you want all files and directories anyway, the glob function is likely incurring an unnecessary overhead of comparing each item it finds against the glob pattern you gave. Also, os.walk() already splits the results for each directory in a list of file names and list of directory names, making your life a bit easier. It would look like:

for root, dirs, files in os.walk(root_directory):
    folder_count += len(dirs)
    for f in files:
        if Path(root, f).is_file():
            ...

If you want more speed, then there are two other ways to consider, that can even be combined. First, write the function in C, and make a Python wrapper function around the C code. Second, you could try to paralellize the code, for example by scanning multiple directories in parallel. However, the latter is a lot of work, and there is a good chance it will not be faster at all, since you might actually not be CPU bound but I/O bound, and even if you are CPU bound, then the overhead of spawning multiple threads or tasks and synchronizing them might be more than the performance gain from the actual parallel execution of the code.

When you are interested in optimizing the code, start with benchmarking it, and then see if the suggestions actually help with performance. Also, before trying to parallelize the code, actually check if your Python code is actually using 100% CPU when scanning directories. If not, it's not worth going that route.


Recursively find all objects of type System.Web.UI.Pair in an object array

You might consider making this an extension method on Pair instead of object.  You could simplify it to this:

public static IEnumerable<Pair> Flatten(this Pair p, List<Pair> toBuild = null)
{
   if (toBuild == null)
      toBuild = new List<Pair>();

   if (p.First is Pair)
   {
      (p.First as Pair).Flatten(toBuild);
   }
   else if (p.First is IEnumerable)
   {
      foreach (object o in (p.First as IEnumerable).OfType<object>().Where(ob => ob is Pair))
      {
         (o as Pair).Flatten(toBuild);
      }
   }

   //repeat for p.Second

  toBuild.Add(p);
  return toBuild;
}

You can use it like this:

var result = myPair.Flatten();

Or on an IEnumerable<Pair>:

var result = myList.SelectMany(p => p.Flatten());

Or on a regular IEnumerable:

var result = myList.OfType<object>().Where(o => o is Pair)
  .SelectMany(p => (p as Pair).Flatten());


Finding optimal row sequence for a melody on 5-row Bayan Accordion, v2.0

To concatenate vectors, you can do this:

(apply #'concatenate 'vector
       (mapcar (lambda (x)
                 (typecase x
                   (vector x)
                   (t (vector x))))
               list-of-vectors-or-numbers))

PS. Since this is CR, here are some notes on your code:

Doc string (no more than one, but it can be multi-line!) usually comes before the declarations. Please see Syntactic Interaction of Documentation Strings and Declarations: (defun foo (...) (declare ...) "doc") will define a function foo which has no docstring and return "doc", while (defun foo (...) "doc" (declare ...)) will declare a function with a docstring, returning nil.
(declare ((vector number) rowlist)) should be (declare (type (vector number) rowlist)).
elt should not be used if you know that the object is a vector; use aref instead.
There is no need to bind exithigh and enterhigh in should-flip-block since they are used just once.
declaim is, I think, more "idiomatic" than proclaim in your case.
It is clearer to use 1- in vector-last.


Is there any performance increase converting search term to lower case before LINQ

Instead of Contains(), use IndexOf() which takes a comparer:

var query = _ctx.Notes.Where(...);
query = query.Where(a => a.Comment.IndexOf(searchTerms, StringComparison.OrdinalIgnoreCase) >= 0)


Meeting Point problem from interviewstreet.com

1. Comments on your code

Your function pos computes the absolute value of a, and is already built into Python under the name abs.
You'd benefit from structuring your code into functions. For example, the expression max(pos(x-inputs[j][0]),pos(y-inputs[j][1])) appears twice. Your code would be clearer if you'd written a function with a docstring, for example:

def distance(A, B):
    """Return the Chebyshev distance from A to B."""
    return max(abs(a - b) for a, b in zip(A, B))

("Chebyshev distance" is a name that mathematicians give to this function.)
You have code near the start for finding the total distance if the meeting point is at house number 0, but then you repeat that code inside a loop over the other meeting points. This seems like a waste. I guess you're doing this because you need an initial value for min.

But instead you could use Python's built-in function min, which avoids the need for a special case to get the initial value. This needs a bit of re-organization, but it comes out quite simple:

def total_distance(Q, points):
    """Return the total distance from Q to each of the points in the
    sequence points.
    """
    return sum(distance(Q, P) for P in points)

def min_total_distance(points):
    """Find that point that minimizes the total distance to the
    other points, and return the minimum total distance.
    """
    return min(total_distance(P, points) for P in points)

If you are a fan of hard-to-read code, then you could write the entire computation in a single expression:

min(sum(max(abs(a - b) for a, b in zip(P, Q)) for P in points) for Q in points)

2. A better algorithm

Your algorithm is \$Θ(n^2)\$: it has to compute the distance between every pair of houses. In the interviewstreet.com version of the problem, they say that \$n ≤ 10^5\$ so your approach takes up to \$10^{10}\$ distance computations. That's not utterly intractable, but it's not going to be doable within the time limits at interviewstreet.com.

So is there an approach which scales better as \$n\$ becomes large?

Well, if we weren't restricted to the meeting point being one of the houses, then the best meeting point would be the geometric median. The geometric median is hard to compute, but it can be approximated by an iterative procedure due to Endre Weiszfeld:

def median_approx(P, points):
    """Return a new approximation to the geometric median of points by
    applying one iteration of Weiszfeld's algorithm to the old
    appromixation P.
    """
    W = x = y = 0.0
    for Q in points:
        d = distance(P, Q)
        if d != 0:
            w = 1.0 / d
            W += w
            x += Q[0] * w
            y += Q[1] * w
    return x / W, y / W

def geometric_median(points, epsilon):
    """Return an approximation to the geometric median for points.
    Start with the centroid and apply Weiszfeld's algorithm until the
    distance between steps is less than epsilon.
    """
    n = float(len(points))
    P = tuple(sum(P[i] for P in points) / n for i in range(2))
    while True:
        Q = median_approx(P, points)
        if distance(P, Q) < epsilon:
            return Q
        P = Q

Unfortunately, for this problem, the meeting point must be one of the original points, so the geometric median doesn't solve it.

However, if the set of points is fairly random (that is, not chosen adversarially), then the best meeting point seems likely to be one of the closest points in the set to the geometric median.

So we have a chance of finding the best meeting point by taking a heuristic approach: compute an approximation \$G\$ to the geometric median, sort the points by their distance from \$G\$, look at the closest \$k\$ points, and pick the best one. If we choose \$ε\$ to be small enough, and \$k\$ to be large enough (but not so large that the computation takes too long), then we'll get the right answer.

from heapq import nsmallest

def best_meeting_point(points, epsilon, k):
    """Return (a guess at) the point in points that minimizes the sum
    of distances to the other points, by computing an approximation
    G to the geometric median (using epsilon) and then taking the
    best point among the closest k points to G.
    """
    G = geometric_median(points, epsilon)
    closest_k = nsmallest(k, points, key = lambda P: distance(G, P))
    return min(closest_k, key = lambda P: total_distance(P, points))

This runs in \$O(jn + kn)\$ where \$j\$ iterations are needed for Weiszfeld's algorithm to converge. \$j\$ doesn't grow proportionally with \$n\$ (it depends on \$ε\$ and on the magnitude of the coordinates in the input), so this is \$o(n^2)\$.

But beware: if the points are chosen adversarially, I think \$k\$ might have to grow like \$Ω(n)\$. I don't know an efficient algorithm for finding the answer in this case. So whether you can use this algorithm to pass the challenge at interviewstreet.com depends on how nice their test cases are. Good luck!


(I didn't know about the other JoinList questions when I was answering the other one one you asked.)

The case

(+++) left@(Single _ _)   right@(Single _ _)   =
  Append (tag $ Append mempty left right) left right

is redundant. There is no need to distinguish this case, also there is no need to call tag on a temporarily created Append value. Other than that, it looks good.

Just a remark, using Product with JoinList probably isn't very meaningful, monoids that provide useful information (depending on the use-case) would be Sum, Min or Max.

For testing, I'd suggest you to study QuickCheck. It allows you to define properties of your operations and automatically test them for various inputs. It's important to define good properties, in particular they should be distinct from the implementation of your operations. For example, you might want to test: For any JoinLists xs and ys

if i < sizeJ xs then indexJ i (xs +++ ys) === indexJ i xs
if i >= sizeJ xs then indexJ i (xs +++ ys) === indexJ (i - sizeJ xs) ys

etc.


In your top=level method mirrorPatch you have:

    // for each row.
    for (int i = 0; i < m.length; i++) {
        // for each column
        flipRow(m[i]);
    }

This is unnecessarily verbose, using the iterable nature of arrays you could simply:

    for (int[] row : m) {
        flipRow(row);
    }

This is self-documenting, and all good.

In your flipRow method, you do a bit more work, and, it is pretty well structured, and readable. If you want to perhaps squeeze out some more performance, I can suggest some changes. Specifically, since you are creating the length variable, you may as well make it more useful by changing it to be last instead, which simplifies the indexing a little bit. Additionally, sometimes (when it is possible), a subtracting-loop is faster (because the condition is simpler), consider the changes as follows:

private static void flipRow(final int[] row) {
    final int last = row.length - 1;
    for (int i = last/2; i >= 0; i--) {
        int x = row[i];
        row[i] = row[last - i];
        row[last - i] = x;
    }
}