Naming

Avoid single-letter identifiers. r, c, d, e, z - who are those guys? What's their purpose? I need to thoroughly study the code to understand that, and then I'd immediately forgot them. Make my life easier.

oddfunction is really get_odd_number
Spacing

if ( d < 0 ) { d = z - 1; } if ( e >= z ) { e = 0; } if ( magic[d][e] != 0 )

is not possible to read. Sparing lines will not make your program run any better, but makes understanding and maintaining it much harder. I hope it is a copy-paste problem.
Redundancy

f and g do not have a right to exist. Especially they do not have right to exist as pointers. Also, you should make up your mind and return the result e.g. of oddfunction either by reference or by return value.
Separation of responsibilities

oddfunction prompts for an odd number, and calls maxfunction, which also prompts for an odd number, this time stating the limit. Double maintenance problem right away. Make one function to deal with IO (prompt and read), and another with business logic (validation). The same validation function shall recognize 2032 as a termination condition.

Along the same line, separate output from the calculations.
The algorithm is not reviewed, mostly due to the naming problem. An introductory comment (or a link to the algorithm) would also be helpful.


Clockwise spiral traversal of 2D input matrix

You’re being a bit verbose, adding elements one at a time in a loop to the output array.  You can use .extend() to add several elements at once, and use a slice to extract the required elements from the inputMatrix rows:

output.extend( inputMatrix[top_row][left_col:right_col+1] )

Unfortunately, you can’t slice a column (without using numpy), but you can still use list comprehension:

output.extend( inputMatrix[row][right_col] for row in range(top_row, bottom_row+1) )

Adding the elements at the bottom of the spiral would require a slice using a negative step, but left_col-1 will initially evaluate to -1 so inputMatrix[bottom_row][right_col:left_col-1:-1] doesn’t work as desired.  You’d need to special case left_col == 0 and use the slice [right_col:None:-1] or [right_col::-1].  Alternately, you could use list comprehension.

Going up the left side is exactly like going down the right side: use list comprehension.

output.extend( inputMatrix[row][left_col] for row in range(bottom_row, top_row-1, -1) )

Notice I used row, instead of i, as the loop index.  I feel this makes the code a little clearer.

An alternative method of doing the spiral copy would be to separate the index generation from the copy.

output = [ inputMatrix[r][c] for r, c in spiral(len(inputMaxtrix), len(inputMatrix[0])) ]

where spiral(rows, cols) is a generator function for the spiral coordinates.  Writing the spiral generator left as an exercise to the student.


Find highly composite number using Python 3

As you said, the naming is not good and the code can be condensed and optimized.

You don't need to keep all the lists, you just need the count
You can split get_divisors so you have another function to get the divisors of a single number
You can use a dictionary to store the divisor count of the numbers.

This would already take care of the variable names:

def get_divisors_count(number):
  divisors = []
  for divisor in range(1, number + 1):
    if (number % divisor) == 0:
      divisors.append(divisor)
  return len(divisors)

def get_divisors_range(number_range):
  divisor_count = {}
  for number in range(1, number_range):
    divisor_count[number] = get_divisors_count(number)
  return divisor_count

def get_highly_composite_number(number_range):
  divisor_list = get_divisors_range(number_range)
  highly_composite_number_list = []
  for i in range(number_range - 1, 0, -1):
    found = False
    for j in range(1, i):
      if (divisor_list[j] >= divisor_list[i]):
        found = True
        break
    if (not found):
      #If you want the list sorted from low to high
      #change this to highly_composite_number_list.insert(0, i)
      highly_composite_number_list.append(i)
  return highly_composite_number_list

This could also be optimized a bit using a lookup for numbers of which you already computed the divisors. For examples, 4 is a divisor of 8, but when you check 8, you can lookup the divisors of 4 and use that.


Reimplementing numpy.genfromtxt in Fortran for Python

Numpy's genfromtxt is indeed slow which is due to it's flexibility. It tries very hard to figure out what the layout of your data file is. So you will not get this flexibility by implementing it yourself in fortran.

Have you tried using loadtxt instead?

Depending on the conditions, for the same matrix genfromtxt may be more than 20 times slower than loadtxt.

BTW a simple implementation in python which is in my case faster than both loadtxt and genfromtxt:

with open("matrix.txt",'r') as f:
    a=array([fromstring(s,dtype=float,sep=' ') for line in f])

I guess the speed comes from the fact that I do not have to read in the whole file to check how many lines it has.

EDIT: I realise this does not really answer your question, but I believe that the speed-up that you may get from using fortran does not really warrant the loss of flexibility.


Replacing part of a string with filler characters

Parameter design

To facilitate currying, you should arrange a function's parameters starting with the one that is the least likely to vary.  In this case, I would consider the fill character the parameter that is most likely to be fixed.

The next parameter, I think, should be the range, and it should be specified as a pair rather than as two separate parameters.  That would make rangedReplace fill (from, to) a filter that takes a string and produces a string.

Using inclusive bounds for from and exclusive bounds for to is the right way to go.

I don't think it's beneficial to automatically swap from and to.  That just encourages your caller to be sloppy.  Rather, I would expect a rangedReplace from 3 to 1 to act as a no-op.

With rangedReplace fill (from, to) string, your main function no longer needs id, map, and the censor helper function.

main = do
  putStrLn $ foldr (rangedReplace '*') "Fork bombs" [(1, 3), (6, 8)]

Implementation

The use of ++ should be considered a yellow flag, as it indicates a full list traversal.  You'll be doing three O(from') operations: take, drop, and ++.

I'd rather go with a recursive solution that does everything in one pass, and is fully lazy.  The implementation is shorter, too.

rangedReplace :: Char -> (Int, Int) -> String -> String
rangedReplace _ _ [] = []
rangedReplace fill (from, to) s@(c:cs)
  | to <= 0   = s
  | from <= 0 = fill:cs'
  | otherwise = c:cs'
  where cs' = rangedReplace fill ((from - 1), (to - 1)) cs


What really hurts this code is that the length method wants to return two things at once: the branch depth, and a global isBalanced status.

To do that, the author returned branch depth directly, and isBalanced as a global variable. I'm all against global variables, but I must admit this does work. I think there's a useless line of code, though:

public int length(TreeNode a) {
    if (a == null) {
        return 0;
    }
    if (isBalanced == false) { // <-- Useless
        return 0;              // <-- Useless
    }                          // <-- Useless

Otherwise, it's not all too bad. It uses a magic value to early return from recursion.

Another possibility is to throw a UnbalancedException - don't kill me right away, throwing exceptions upon rencountering abnormal situations is not evil! If it's not happening too often, it's quite reasonable, and makes for a much cleaner design:

public class Solution {
    public boolean isBalanced(TreeNode root) {
        try{
            length(root);
            return true;
        } catch(UnbalancedException unbalanced){
            return false;
        }
    }

    public int length(TreeNode a) throws UnbalancedException{
        if (a == null) {
            return 0;
        }
        int x = length(a.left);
        int y = length(a.right);
        if (Math.abs(x - y) > 1) {
            throw new UnbalancedException();
        }
        return Math.max(x, y) + 1;
    }
}

With this design, you've gained a length method that actually works!

The most JAVA possibility - suposedly cleaner, but that I like the least - is to create a ad-hoc Response object like a BalancedStatus:

public class BalancedStatus {
     private final boolean isBalanced;
     private int depth;
     // Getters, and constructors here
}

And :

public class Solution {
    public boolean isBalanced(TreeNode root) {
        BalancedStatus rootStatus = length(root);
        return rootStatus.isBalanced();
    }
    public BalancedStatus length(TreeNode a) {
        if (a == null) {
            return new BalancedStatus();
        }
        BalancedStatus x = length(a.left);
        if(!x.isBalanced()){
             return new BalancedStatus(false);
        }
        BalancedStatus y = length(a.right);
        if(!y.isBalanced()){
             return new BalancedStatus(false);
        }
        if (Math.abs(x - y) > 1) {
             return new BalancedStatus(false);
        }
        return new BalancedStatus(Math.max(x, y) + 1);
    }
}

But I don't like this because it instantiates two Objects per recursion level...

Finally, we could axe the recursion and use iteration instead, but since this is a branching recursion we'd need a List (Queue?) to track the progress.
Pros:

No recursion (no stack overflow etc.)
Easy early exit (just return)

Cons:

Requires to setup a List of nodes to do
Requires to be able to link back from node to parent (Map?) to propagate depth


Streamreader file.Readline properly closing the stream

You always need to dispose of objects in the finally close to ensure that they are disposed correctly.

StreamReader sr = null;
try
{
    sr = = new StreamReader(ValidFilePathName);
    line = file.ReadLine();
    While (line != null)
    {
        line = file.ReadLine();
    }
}
catch
{
    // blah Do nothing
}
finally
{
   if (sr != null)
   {
       sr.Close();
   }
}


def fourth_wall(fbuserid)
  result ||= graph.get_connections(fbuserid, 'feed')
  second ||= result.next_page
  third ||= second.next_page
  fourth ||= third.next_page
end

A couple of problems here: result, second, third and fourth are all local variables. This means they won't persist after the method call is finished and they will never persist after the method call is finished. So:

You don't need to set the fourth variable as you never use it in the method and it won't be available after
You don't need ||= as the variables will never be set anyway.

I.e. your code is equivalent to this:

def fourth_wall(fbuserid)
  result = graph.get_connections(fbuserid, 'feed')
  second = result.next_page
  third = second.next_page
  third.next_page
end

Or just:

def fourth_wall(fbuserid)
  graph.get_connections(fbuserid, 'feed').next_page.next_page.next_page
end

The same goes for the other wall methods.

Further your fourth_wall method contains the entire code of the third_wall method (which contains the entire second_wall method and so on). This is bad style. Just let the methods call each other:

def fourth_wall(fbuserid)
  third_wall(fbuserid).next_page
end

(And again the same for the other wall methods of course)

However since you seem to only call those functions together (i.e. you never use fourth_wall without having used third_wall before) it seems much more sensible to have one method which returns all for walls:

def four_walls(fbuserid)
  first = graph.get_connections(fbuserid, 'feed')
  # For more than 4 pages the following should be replaced by a loop
  second = first.next_page
  third = second.next_page
  fourth = third.next_page
  [first, second, third, fourth]
end

In your get_post_ids method you're repeating the same code four times. This is again bad style. You're also creating an empty array and then appending to it from a loop. This is often (but not always) a sign of bad code in ruby as well. Also using x and var as variable names is not a good idea and having a variable name that starts with @get_ just seems weird and confusing.

I'm also assuming that your find_nil method is supposed to check whether either wall[i] or wall[i]['id'] are nil. There are better ways to do this.

In this case you can use map on the walls and then the numbers from 0 to 25 to create an array of user ids for each wall, then use compact to remove nils and flatten to turn the array into one single array rather than an array of four subarray. Thus your whole get_post_ids method can be replaced with this:

def retrieve_post_ids(fbuserid)
  walls = four_walls(fbuserid)
  @post_ids = walls.map do |wall|
    # Iterate over the first 26 entries in wall
    (0..25).map do |i|
      wall[i] && wall[i]['id']
     end.compact
  end.flatten
end

Though if the walls allow slicing similar to arrays, this would be better:

def retrieve_post_ids(fbuserid)
  walls = four_walls(fbuserid)
  @post_ids = walls.map do |wall|
    # Iterate over the first 26 entries in wall
    wall[0..25].map do |entry|
      entry && entry['id']
     end.compact
  end.flatten
end

If the wall never contains more than 26 elements, you don't even need the [0..25] and you can just use well.map.

However it occurs to me that the reason you needed the nil check at all was that each wall contains 25 elements and you got nil for index 25 because you did not realize that ranges using .. are inclusive. In that case you can just use:

def retrieve_post_ids(fbuserid)
  walls = four_walls(fbuserid)
  @post_ids = walls.map do |wall|
    # Iterate over the entries in wall
    wall.map do |entry|
      entry['id']
     end
  end.flatten
end


Polynomial curve-fitting over a large 3D data set

In terms of possible speed optimisations there's not much to work with, but one thing does stand out:

        def func(t, a, b, c, d, e, f):
            return a+ b*t+ c*(b*t)**2+ d*(b*t)**3+ e*(b*t)**4+ f*(b*t)**5

(and similarly for the four-element case). It's fairly standard knowledge that polynomials evaluation can be optimised for speed using Horner's method. I'll also pull out that multiplication by b:

        def func(t, a, b, c, d, e, f):
            bt = b*t
            return a + bt*(1 + bt*(c + bt*(d + bt*(e + bt*f))))


Extracting performance statistics from FTP session transcript

Assuming the "Output" section is stored in "filename.txt", and assuming you have GNU tools:

grep -oP '(?<=\.\d\d)\d+\.\d\d(?=disconnect)' filename.txt

That's a perl regex meaning: prececeded dot and two digits, find some digits, a dot and two digits, followed by "disconnect". grep's -o option means "output only the matched text".


Open text file and read data to an arrayfire array using Qt and C++

Prefer return over Output parameter

A result as an out parameter seems like a smell to me:

void getNumberOfLines(std::string filename, int &numLines)
{
    std::ifstream in(filename);
    std::string line;

    while(std::getline(in, line))
        numLines  = numLines + 1;
}

Why not return the number of lines as a result of the function?

Also when counting the lines you don't actually need to read the strings out. You just need to find the end of line marker. To avoid the cost of copying and re-sizing lines for data you don't need, you can use the std::istream::ignore() method.

Lets also pass the filename by reference to avoid a copy (copying strings is relatively expensive (its const as you don't modify it)).

std::size_t getNumberOfLines(std::string const& filename)
{
    std::size_t   result = 0;
    std::ifstream in(filename);

    while(in.ignore(std::numeric_limits<streamsize>::max(), '\n') {
        ++result;
    }
    return result;
}

You can now change the call point to:

// From
int numLines = 0;
getNumberOfLines(filename, numLines);

// To
int numLines = getNumberOfLines(filename);

Illegal identifiers:

    std::string 1_tmp, 2_tmp, 3_tmp;

Those are not legal variable names. Not sure how you think this is compiling!

Check stream reads/writes

You should always check the result of a stream input/output operation to make sure it worked. Streams are the one place in the standard where exceptions are turned off so you need to check the error codes (luckily this is easy as the stream used in a boolean context will convert itself into the current error code state).

    // Here you read value from a stream
    // But don't check that it worked.
    is >> 1_tmp >> 2_tmp >> 3_tmp;
    data1(i) = std::stof(1_tmp) * pow(10, -9);
    data2(i) = std::stof(2_tmp);
    data3(i) = std::stof(3_tmp);
    i++;

Should look like this:

    if (is >> 1_tmp >> 2_tmp >> 3_tmp)
    {
        data1(i) = std::stof(1_tmp) * pow(10, -9);
        data2(i) = std::stof(2_tmp);
        data3(i) = std::stof(3_tmp);
        i++;
    }
    else
    {
        // If something went wrong with one line.
        // Then do you trust the rest of the stream?
        // I think not. So you should also mark the input stream
        // bad at this point.
        in.setstate(std::ios::failbit);

        // This will cause the outer loop reading the file to stop.
    }

Use the stream read ability

Why read a string when the data is a float?

Why go to the effort of parsing a string when the data could be a float? In your code you are effectively scanning each value twice, which seems like a lot of extra work.

 std::string 1_tmp;
 in >> 1_tmp;
 double 1_val = std::stof(1_tmp);

Instead, use the existing read float capabilities of the stream input operator.

 double 1_val;
 int >> 1_val;

Copy ss Move

This is a copy:

dS.d1 = data1;
dS.d2 = data2;
dS.d3 = data3;

But you never use data[123] again. So you may as well try and move the data.

dS.d1 = std::move(data1);
dS.d2 = std::move(data2);
dS.d3 = std::move(data3);


I find that your program is obfuscated and therefore incomprehensible to anyone except for perhaps an expert in those calculations methods.  You should pick more informative variable names than a, b, k, m, n, and x.

faculty(m) should be renamed factorial(m).  Ideally, you wouldn't need it — see below.

If you could verify that the denominator is always a divisor of the numerator, you should use // integer division.

Use more whitespace for readability.  Here, I would break with Python guidelines and be more generous with whitespace than usual.

Verbose comments, especially docstrings, would also be appreciated for complicated mathematics:

def chudnovsky(b, n):
    """
    Based on the identity

                    n
      1     inf (-1)  (6n)! (13591409 + 545140134n)
    ----- = SUM -----------------------------------
    12 PI   n=0              3       3n + 1.5
                   (3n)! (n!)  640320

    Returns the nth term of the sum.
    """
    return b + (
        ((-1)**n) * (factorial(6 * n)) *
        (13591409 + (545140134 * n))
    ) // (
        factorial(Decimal(3) * n) *
        (factorial(n)**3) *
        640320**(3 * n + (Decimal(3) / Decimal(2)))
    )

Many parts of that expression would be more efficiently computed based on their counterparts in the previous term, instead of starting from scratch.  You might want to build an generator  that caches those intermediate results.

Furthermore, you have very large numbers in both your numerators and denominators, especially factorials.  You can help keep those small by cancelling out the factorials in the numerator and denominator as soon as possible.

def ChudnovskyTerms():
    """
    Based on the identity

                      n
      1    inf 12 (-1)  (6n)! (13591409 + 545140134n)
    ---- = SUM --------------------------------------
     PI    n=0                3       3n + 1.5
                    (3n)! (n!)  640320

    yields successive terms of the sum.
    """
    term = 0
    sign = 1
    factorial_6_3 = 1         # = factorial(6 * n) / factorial(3 * n)
    numerator_sum = 13591409
    n_factorial_cubed = 1
    denominator = 640320**1.5

    while True:
        yield 12 * sign * factorial_6_3 * …

        term += 1
        sign *= -1
        for i in range(6):
            factorial_6_3 *= (6 * term - i)
        for i in range(3):
            factorial_6_3 //= (3 * term - i)
        numerator_sum += 545140134
        # etc.


Kadane's Algorithm Variant (Start Index and End Index with Sub Array returned even for all negative numbers)

It will fail in the case 8, -19, 5, -4, 20. The startIndex and endIndex will not update until 20, but the start should be 5.


There are already tools for choosing elements from a collection with some given probabilities. In the standard library there is random.choices, which takes the values, the probabilities and the number of items you want:

import random

values = ["get_10_20", "get_20_30"]
#p = [0.5 * 0.6 + 0.5 * 0.4, 0.5 * 0.4 + 0.5 * 0.6]
p = [0.5, 0.5]

n = 10
random.choices(values, weights=p, k=n)
# ['get_10_20', 'get_10_20', 'get_10_20', 'get_10_20', 'get_10_20', 'get_20_30',
#  'get_20_30', 'get_20_30', 'get_10_20', 'get_10_20']

The other possibility is to use numpy.random.choice for this, which allows you to directly generate multi-dimensional data:

values = ["get_10_20", "get_20_30"]
p = [0.5, 0.5]

n, m = 2, 3
np.random.choice(values, p=p, size=(n, m))
# array([['get_10_20', 'get_10_20', 'get_20_30'],
#        ['get_20_30', 'get_20_30', 'get_20_30']], dtype='<U9')

Both approaches assume that you can combine the probabilities to a total probability for each value. The numpy method enforces that they sum to one, while the standard library random does that for you, if necessary.


Seperate out validations from a service and use custom exceptions for entities not found

As I do not know the other entities beside "Student" it becomes very hard to evaluate it.

One general thing: having duplicate code does not mean you have a problem. The problem comes if the duplicate code comes with real duplicate semantic for your business domain.

It may be that you are missing an business relevant abstraction of "Student" and the other entities that have std or division in common. But you should think about that if there is really a proper abstraction. You can test it by making up an artificial requirement that affects the Student and the std or division. If the other entities must change as well to have a consistent model then there is semantic duplication and you should consider an abstraction or composition.

If you have identified an abstraction to be proper then you can abstract the null checks as well. Another way is to encapsulate std and division in one object and provide a validate-method that does the check. Furthermore search the internet for refactoring methods like "introduce parameter object".

If you haven't identified an abstract responsibility then leave your code as it is. Otherwise you may fall into a type II error. (Acting if there is a problem, but there isn't). This is related to the SRP. Robert C. Martin shows this in one of his talks: https://youtu.be/Gt0M_OHKhQE?t=698. As well as you should remove duplicate responsibilities you also should separate different responsibilities.

Some other things:

You said you have a business layer but the separation isn't proper. And here is why: Your "business layer" is responsible to serve a web service by throwing a BadRequestException. You are mixing in technologies that belong to other layers.
You do not distinguish between proposal objects, consistent business objects and communication objects. They are all same (StudentDTO in, StudentDTO out).
The null checks are not business relevant. They are a result of mapping from one representation (String) to another representation (Std, Division) while you do not know if the source made proper assumptions of the presents of the requested business objects. This is related to the web service layer that has to ensure to pass correct non-null values to the business layer. On the other side you have code that composes an entity in the same method. That should be separated at least into another class but after all it is a different layer, maybe the business layer, in my opionion the dao layer.


Custom shapes objects using polymorphism in JavaScript

[I] want to know if it properly represents PolyMorphism in JavaScript?

Your code could be considered a representation of polymorphism when considering that the noOfSides() function was changed for a single instance of the customShape type, but that doesn't really apply to all objects of that type. Traditionally in Object-Oriented programming, sub-typing would be used to create sub-classes that inherit the properties and methods of the base class.

You created instances of customShape, but didn't really make any objects that inherit that functionality. For instance, you made the triangle instance and added a function (like a method) to that one instance:

var triangle = new customShape();
triangle.noOfSides = function(){
    return ("Total No of Sides = " + 3);
}

Looking at the fourth reference you included, look at the Padawan inheritance example

var jedi = function(name, age) {
    Padawan.call(this, name, age);
};
jedi.prototype = Object.create(Padawan.prototype);

Similarly, you could make a constructor for a triangle. The customShape constructor doesn't appear to accept any parameters, though it could accept the number of sides, in which case the triangle constructor could pass that in as an argument to the call to customShape.call(), but for now, the sides property can be set after that call.

function triangle() {
    //initialization code
    customShape.call(this);
    this.sides = 3;
}

And then set the prototype for the triangle to an object with the customShape prototype:

triangle.prototype = Object.create(customShape.prototype);

Then you don't need to add an additional noOfSides() function for the triangle. See a demonstration below. Note that I updated the noOfSides() method to utilize this.sides instead of a hard-coded value (like Matt Fletcher mentioned in a comment on your SO question, and also did in the jsbin example he made and linked in another comment).

var customShape = function(){
    this.sides = 4;
    this.length = 5;
    this.perimeter = 4 * this.length;
};

customShape.prototype.noOfSides = function(){
    return ("Total No of Sides = " + this.sides);
}

var rect = new customShape();
var square = new customShape();
var triangle = function() {
    customShape.call(this);
    this.sides = 3;
}
triangle.prototype = Object.create(customShape.prototype);

var tri = new triangle();
console.log('rect: ', rect.noOfSides());
console.log('square: ', square.noOfSides());
console.log('triangle: ', tri.noOfSides());

Matt Fletcher has good points in his comment at 2017-11-29 12:37:29Z:

  @Deadpool Fine. This is a somewhat improved version: jsbin.com/jazasav/edit?html,js,console ... but it still makes little sense, because "length" can differ on all sides. Also these shapes and their values don't follow such simple mathematical rules. In a real world example you'd need to be able to pass in much more complex data and get it to process it in a more complex way. Perhaps use the whole "Animal" inheritance pattern to better explain it, if that's what you're planning on doing. I just would like to know what you're actually trying to gain from generating polymorphic obj

And Matt's jsbin includes an ES2015 example, which should be fsmiloar to OOP users in other languages like C++, Java, PHP, etc.

// ES6 style

class CustomShape {
  constructor(sides, length) {
    this.sides = sides;
    this.length = length;
    this.perimeter = sides * length;
  }
  noOfSides() {
    return ("Total No of Sides = " + this.sides);
  }
}

class Square extends CustomShape {
  constructor(length) {
    super(4, length);
  }
}

const mySquare = new Square(5);
console.log(mySquare.noOfSides());


Validating search parameters in an Angular $scope

If you can wrap your arrays into an object and keep their names in line with the search attributes, you can have:

<tbody ng-repeat="user in users | customFilter:searchParams "> ...

$scope.updateSearch = function() {

//  Uncomment to test the following block in console:
//  var $scope = {search: {login:'log1', status:'status0'}};

    var searchParams = {},
      arr = { // Initialise arrays (if needed?)
        login: [],
        name: [],
        status: [],
        accounts: [],
        profiles: []
      };

    Object.keys($scope.search).forEach(
      e => {if(/\S/.test($scope.search[e])) {
        arr[e].push($scope.search[e]);
        searchParams[e] = arr[e];
      }}
    );

    $scope.searchParams = searchParams;
  };

If you definitely need renaming:

<tbody ng-repeat="user in users | customFilter:searchParams "> ...

$scope.updateSearch = function() {

//  Uncomment to test the following block in console:
//  var $scope = {search: {login:'log1', status:'status0'}};

    var searchParams = {},
        loginArr = [],
        nameArr = [],
        statusArr = [],
        accountsArr = [],
        profileArr = [];

    function mapSearch(src, arr, sTgt) {
      if(src !== undefined && /\S/.test(src)) {
        arr.push(src);
        searchParams[sTgt] = arr;
      }
    }

    mapSearch($scope.search.name    , nameArr    , 'name');
    mapSearch($scope.search.login   , loginArr   , 'login');
    mapSearch($scope.search.status  , statusArr  , 'merchant.status');
    mapSearch($scope.search.accounts, accountsArr, 'merchant.accounts');
    mapSearch($scope.search.profiles, profileArr , 'merchant.profiles');

    $scope.searchParams = searchParams;
  };


Signed 64-bit integer (long in both Java and C#) can have values between approximately -9 · 1018 and 9 · 1018. Unsigned 64-bit integer (ulong in C#) can have values between 0 and approximately 1.8 · 1019. The value of 20! is approximately 2 · 1018, so it fits comfortably both to long and ulong. The value of 21! is approximately 5 · 1019, so it doesn't fit even into ulong.

Because of this, 20! should be computed correctly both in Java and c#, but 21! should be incorrect in both, no matter whether you use long or ulong.

If you want to make sure you are getting correct results in C#, you can use unchecked. If you do that and the computation overflows, you will get an exception.

What should you do if you want to compute larger values than 20!? The best option would be if there was some type that could represent arbitrarily large integers. Fortunately, both languages have them, there is BigInteger in C# and BigInteger in Java.


Advent of Code 2018 day 1 part 2: find the first repeated number after some increases and decreases

Small things

Data.List.Split

I don't see the need for this module. I see what you're going for with splitOn "\n", however Haskell has a function in Prelude called lines:

words :: String -> [String]

Prelude> lines "test\nphrase, please\nignore"
["test","phrase, please","ignore"]

parseString

I think it's cleaner to instead first parse your input into an Integer format and then use [Integer] everywhere instead of [String]. This simplifies your parsing and also gives you a more general function. Note that my implementation is a partial function.

parseInt :: String -> Integer
parseInt (op:s) =
  case op of
    '+' -> read s
    '-' -> (-1) * read s
    -- There is a hole here: this will error if 'op'
    -- (the first character) isn't '+' or '-'

Return values

The type of findFreq is

findFreq :: Integer -> [Integer] -> [String] -> (Integer, Integer, [Integer])

I see no reason why it can't return a single Integer. Perhaps you returned all values to debug initially, but once that's done you should switch back.

It also seems to me like you were using 0 as an "error value," which is appropriate in other languages but generally frowned upon in Haskell. In this case, you can instead use Maybe to indicate failure and change your type signature to

findFreq :: Integer -> [Integer] -> [String] -> Maybe Integer

Like I mention later, this isn't necessary since we can condense and fix some logic, but I would recommend using Maybe instead in the future.

curr and acc

You do some switching around with your variables curr and acc which confused me a bit. I'd keep acc as the accumulation value for your frequency everywhere and call the list of visited values something like seenFreqs or prevFreqs.

Correctness

Repeating frequencies of 0

Your code currently assumes the repeated frequency is the first nonzero repeated frequency. Thus, it fails for the +1, -1 test case. You could change the code to

findRepeatingFrequency :: Integer -> [Integer] -> [String] -> Integer
findRepeatingFrequency init nums xs =
  let (found, acc, lst) = findFreq init nums xs
  in found

to accommodate that.

This breaks your way of going through the list again if you don't find a repeat the first time, but fortunately there's a less obfuscated way to avoid your checking and continue: you can use cycle, which creates an infinite list consisting of the input list repeated infinitely.

cycle :: [a] -> [a]

Prelude> take 20 $ cycle [1,2,3,4]
[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]

You can call findRepeatingFrequency on cycle input to prevent having to do the cycling yourself in the function.

Efficiency

Things go wrong for efficiency in findFreq. There are two problem points that make your code asymptotically inefficient.

First, in the following line

  in if next `elem` acc

elem is an O(n) operation. You're calling it for each of the n elements in your input list, meaning that your function is at least O(n^2) (and it turns out that this is the final complexity).

I checked the number of iterations required for my sample input and it took 142991 iterations to find a repeated frequency. An O(n^2) runtime is going to require about 10 billion iterations for the lookups alone. Ouch.

Second is a more insidious mistake that is easy to overlook. In this line,

   else let f = acc ++ [next]

Appending to a list is an O(n) operation. Lists in Haskell are implemented as linked lists, and appending to the back of one cannot be amortized to O(1) like one might in Python's list or Java's ArrayList. You need to travel all the way to the back to add in a link.

Fixing the second issue actually isn't very hard since you don't care about the ordering of the list. You can switch it to

   else let f = next : acc

to return to O(1) inserts.

Fixing the lookups, however, requires a change of data structure.

Introducing Data.Set

Data.Set provides unordered sets with O(log n) lookup and insert time. Yeah, it's O(log n), but the total runtime for me when I checked the implementation was less than a second.

I'm including a sample implementation of day 1 below that I've tested and confirmed on my inputs if you want to compare. However, you said you wanted pointers, so here's the pointers I'll give.

You can keep your code mostly the same (although I'd recommend making the style changes I suggested)
You will want to use two functions from Data.Set: member and insert.
Your end result will look a lot like a fold but with some differences in end conditions (kind of like findFreq)

Sample implmentation

Finally, here's a sample implementation.

module Main where

import Data.Set (Set)
import qualified Data.Set as S

-- This is a partial function
parseInt :: String -> Integer
parseInt (op:s) =
  case op of
    '+' -> read s
    '-' -> (-1) * read s
    -- There is a hole here, assuming valid input

findRepeatingFrequency :: Integer -> Set Integer -> [Integer] -> Integer
findRepeatingFrequency acc seen (x:xs) =
  if acc `S.member` seen
     then acc
     else findRepeatingFrequency (acc + x) (S.insert acc seen) xs

partOne :: [Integer] -> Integer
partOne = sum

partTwo :: [Integer] -> Integer
partTwo ints = findRepeatingFrequency 0 S.empty $ cycle ints

main :: IO ()
main = do
  file <- readFile "input.txt"
  let input = filter (not . null) $ words file
  let ints = map parseInt input
  print $ partOne ints
  print $ partTwo ints


Time complexity of finding a triangle in undirected graph

Before I'll get to your timecomplexity let me tell you something:

Your code screams for a lint:

class Triangle
{
 static ArrayList<LinkedList<Integer>> g;

this part should become:

class Triangle {
    static ArrayList<LinkedList<Integer>> g;

no wait scratch that:

Whenever possible - specify visibility
Program against interfaces
Use speaking variables

Okay let's try again

public class Triangle {
    private static List<List<Integer>> graph;

same goes for your int[]s. On a very related note, you should encapsulate state into a class and not into the static context, where everything can modify it. Drop the static modifiers you use.

Use the final keyword to signal immutability. Use it wherever possible to reduce risk of misassigning variables.

The initialization blocks become:

private final List<List<Integer>> graph = new ArrayList<List<Integer>>();
private int[] visited;
private int[] level;
private int[] parent;
private final Queue<Integer> queue = new LinkedList<Integer>();

I usually prefer to add an empty line before a method head to help in recognizing it as new method. And also respect Java naming conventions for method names. This means: no snake_case and no SHOUTCASE. camelCase is the way to go:

public void createGraph() {

Also respect the braces placement of Java conventions. On a related note keep nice spacing around your operators. Cramping code together doesn't help readabiltiy and the times of scarce memory, where every unnecessary space was a wasted Byte are over:

Scanner s = new Scanner();

is preferrable over:

Scanner s=new Scanner();

same goes for all the operations you're doing...

While we're at Scanner. One of these Scanners is not used, neither is ever closed. Close your resources with try-with-resources, remove all of your unused variables and declare variables as close as possible to their usage.

This gets rid of:

int so, i;
Scanner s=new Scanner(System.in);
int n,i,k,j;

To make things clear, this is what your code looks like in my IDE right now:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;

class Triangle {

    private final List<List<Integer>> graph = new ArrayList<List<Integer>>();
    private int[] visited;
    private int[] level;
    private int[] parent;
    private final Queue<Integer> queue = new LinkedList<Integer>();

    public void createGraph() {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("enter the value of number of vertices");
            int vertexCount = scanner.nextInt();
            visited = new int[vertexCount];
            level = new int[vertexCount];
            parent = new int[vertexCount];
            for (int i = 0; i < vertexCount; ++i) {
                visited[i] = 0;
                level[i] = -1;
            }
            for (int i = 0; i < vertexCount; ++i) {
                graph.add(new LinkedList<Integer>());
                System.out.println("enter the number of vertices adjacent to " + (i) + " and what are they?");
                int k = scanner.nextInt();
                for (int j = 1; j <= k; ++j) {
                    graph.get(i).add(scanner.nextInt());
                }
            }
        }
    }

    public boolean triangleCheck(int so, int l) {
        visited[so] = 1;
        queue.add(so);
        level[so] = l;
        while (queue.size() != 0) {
            int i = queue.poll();
            for (int e : graph.get(i)) {
                if (visited[e] == 0) {
                    visited[e] = 1;
                    level[e] = level[i] + 1;
                    queue.add(e);
                    parent[e] = i;
                }
                else if (level[e] == level[i] && parent[e] == parent[i])
                    return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Triangle tri = new Triangle();
        tri.createGraph();
        if (tri.triangleCheck(0, 0)) {
            System.out.println("The graph contains a triangle");
        }
        else {
            System.out.println("The graph does not contain a triangle");
        }
    }
}

By now you're probably asking yourself "Why did I even come here, I wanted to know about time-complexity"... The answer is. I couldn't even understand your code until just now.

Honestly I still now have problems, bit I think you should get down to   \$O(V)\$, under the assumption that this code actually produces correct results..


If I understand correctly, the role of this procedure (which is far from obvious from the name alone) is to assign either _CreateUTC or _ModifyUTC values (which should be _createUTC and _modifyUTC if they're private fields - always use camelCase for fields and locals/parameters.

You don't need that rows list of lists of strings at all, let alone iterate that monster afterward to retrieve a value.

Just loop and locate the value as you're looping, don't store anything but what you need and stop looping once you got it - I think something like this would do it:

var headerIndex = 0;
DateTime value;
foreach (var htmlRow in htmlRows)
{
    if (htmlRow.FindElements(By.TagName("th")).Count > 0)
    {
        headerIndex = tableHeaders.Select(th => th.Text.ToString()).IndexOf(columnHeader);
        continue;
    }

    var cellsInRow = htmlRow.FindElements(By.TagName("td")).ToArray();
    if (cellsInRow[0] == entryName)
    {
        value = Convert.ToDateTime(cellsInRow[headerIndex].Text.ToString());
        break;
    }
}

if (columnHeader = "Create UTC Date")
{
    _createUTC = value;
}
else if (columnHeader = "Modify UTC Date")
{
    _modifyUTC = value;
}


Is this Python pathfinder efficient enough?

About your code following common practices, you may read about PEP8.

You have far too many lines with more than 80 characters, you even have a line with 180+ characters: Does not fit my screen.

You may, as PEP8 states, put spaces around binary operators.

You also have an undocumented function with a name that does not helps me.

Seems you have copy/pasted some code many times, that's not DRY, and that may be bad, you may win some readability by using a function.

You should not use this kind of control flow:

for y in xrange(len(w)):
    for x in xrange(len(w[0])):
        if (w[y])[x]==2:
            if hor-1>-1: #going left
                if (w[ver])[hor-1]==2:

That's freaking unreadable, and I'll NOT read it. Avoid imbricate so many control flow.


Don't catch (or throw) Exception.
Try not to return null. If you cannot return a normal value you want one of the following to happen:

Program quits with an error. (Your current program seems to do this)
You expect calling site to take some action and try to recover and continue execution
You do not want to hassle the caller of the method and try to continue execution with a sensible default value.

If you want program to quit with an error. Wrap the exception in a runtime exception with a meaningful (to the developer, not user) message. That way in your logs you will see what went wrong and where. If you return a null what you probably get is a nondescript NullPointerException down the line.

If you want the caller of the method to check if something went wrong, you want to throw a checked exception. Null checks always get ignored and your program crashes and burns in inopportune moments and users think, rightly, the program is of low quality. If you do not have and cannot create a suitable Exception, you can propagate the exception.

Third option is usually ignored but sometimes continuing with some default value is the most logical thing to do. Think what browsers do if they cannot download an image, which basically is an IOException. They show a white rectangle with a red cross on it. A web page with some of the images missing is more useful than a page full of stack trace. And note that a white rectangle with a cross behaves like a normal image in terms of layout, hence do not break the page layout. This is the essence of the Null Object Pattern.
(Updated as per @Sulthan) You should call the InputStream.close() in a finally block. Because if ImageIO.read throws an exception you never reach the close() statement.

A few notes about the example code below:

Resource leaks may occur if InputStream.close throws. There isn't much you can do about it.
Wrapping example and the ImageReadException do not pull their weights as they are. they are here for demonstration.
Method names are shortened to fit screen.

Here is the basic case:

private static BufferedImage readPropagate(String imagePath) throws IOException {
    InputStream is = null;
    try {
        is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);
        // an example of how null checks can easily be forgotten
        if (is == null) {
            throw new FileNotFoundException("Resource not found: " + imagePath);
        }
        return ImageIO.read(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

Here are some examples of what can be done when the above example is not sufficient:

public static class ImageReadException extends Exception {
    private static final long serialVersionUID = 1L;

    public ImageReadException(String message, Throwable cause) {
        super(message, cause);
    }

    public ImageReadException(String message) {
        super(message);
    }
}

private static BufferedImage readWrap(String imagePath) throws ImageReadException {
    try {
        return readPropagate(imagePath);
    } catch (IOException e) {

        // log with your normal logger
        logException(e, "An error occured while loading image " + imagePath);

        // Message should be something meaningful to the calling site
        throw new ImageReadException("An error occured while loading image", e);
    }
}

private static BufferedImage readWithDefault(String imagePath) {
    try {
        return readPropagate(imagePath);
    } catch (IOException e) {

        // log with your normal logger
        logException(e, "An error occured while loading image " + imagePath);

        //default image may be passed as a parameter instead
        return IconManager.DEFAULT_IMAGE;
    }
}

// YOU SHOULD NOT DO THIS IN LIBRARY CODE
// The decision of whether to crash the program belongs to the top level application
private static BufferedImage readThrowSilently(String imagePath) {
    try {
        return readPropagate(imagePath);
    } catch (IOException e) {
        // you can do this, e.g., while loading a desktop application
        // you discover a vital resource could not be loaded
        // continuing execution does not make sense
        throw new RuntimeException("An error occured while loading image " + imagePath, e);
    }
}

private static void logException(IOException e, String message) {
    Logger.getLogger(IconManager.class.getName()).log(Level.SEVERE, message, e);
}


Python insert line in the middle of the file

Your code goes through the file twice - once to find the index where your new line is to be inserted, and again to actually perform the change.

My approach to this problem would be to create a class that contains three variables:

The lines in setup.py before "REQUIRED_PACKAGES = ["
The contents of the REQUIRED_PACKAGES list
The lines in setup.py after the REQUIRED_PACKAGES list

Your problem then splits nicely into three distinct sub-problems:

Parsing setup.py and returning an instance of the class above
Adding an element to the required packages list in your custom class (trivial)
Writing a new setup.py file

Looking at your code specifically, your docstring for parse_file does not match what the code is doing. It says that data is returned, but the code actually returns line_index, and the data member you initialise is unused.

Your code comments in general could be improved. You comment some obvious things such as"open the file and read through it line by line" and "if there are no matches". These operations are immediately apparent from looking at the code, and do not require comments.


Implementing JQuery style 'deferred' and 'promise' in C#

I like how you can call Resolve any number of times, but the listening objects will only be notified once. I also like how you can attach a listening object after Resolve has already been called, and the listening object will still get the notification. If you're programming in an uncertain multithreaded environment, it greatly reduces the amount of thinking you have to do.

This sounds a lot like TaskCompletionSource along with the Task it controls.

Assuming you have a TaskCompletionSource<T> tcs:

To attach a listener, use tcs.Task.ContinueWith(_ => /* listener code here */). You can do this before or after the Task has been completed and the listener code will be executed only once after the Task has been completed.
To complete the Task (the equivalent of resolving), use tcs.TrySetResult(someValue). If you'll use the TrySetResult() variant instead of SetResult(), the second and following attempt at completing will be ignored (SetResult() would throw an exception).

The difference with your code is that TaskCompletionSource always has some result type. You can either just ignore that (using e.g. TaskCompletionSource<object> and SetResult(null)), or use the non-generic TaskCompletionSource from AsyncEx.


Init.d script for Rails managing a Rails app via Unicorn

Quoting command line arguments

This is not safe:

[ -f $PID_FILE ] && ...

Variables and the result of $(...) should be double-quoted to protect from parameter expansion and globbing:

[ -f "$PID_FILE" ] && ...

A longer example (fixed version, compare with your original):

if [ -f "$PID_FILE" -a -n "${KPID}" -a -d "/proc/${KPID}" ]; then
      logger -sit "$TAG" "Process ${KPID} in PID file $PID_FILE exists. Service '${PROJ_NAME}' should be running"

The lack of quoting is the most common violation in the posted code,
review carefully.
Copy-paste to https://www.shellcheck.net/, it should help.

Use $(...) instead of `...`

The backtick format is obsolete, and harder to read. Always use $(...).

Usability

The stop function waits for 2 seconds after sending the TERM signal to the process to check if the PID file still exists.
That seems a bit arbitrary, and possibly fragile.
It would be better to sleep for 1 second 5 times in a loop.
This is also pretty arbitrary, but a bit more flexible.

Pointless [ -f $PID_FILE ] && KPID=`cat $PID_FILE`

This is executed always, regardless of the sub-command.
And then most sub-commands reload the value in $PID_FILE.
It would be better to create a function for getting the PID,
and calling that function when you need it.

Signal to PID that might not exist

Some of the functions signal to $(cat "$PID_FILE"),
without making sure that PID actually exists,
or even that $PID_FILE actually exists.
It would be better to validate the state more accurately,
and raise errors as appropriate.

Recursive execution

The restart function calls $0 start to restart the script.
It would be more natural to simply call the start function directly.


Making this reduce() Fibonacci generator better

A reduce (that's it, a fold) is not exactly the abstraction for the task (what input collection are you going to fold here?). Anyway, you can cheat a little bit and fold the indexes even if you don't really use them within the folding function. This works for Python 2.x:

def next_fib((x, y), n):
    return (y, x + y)

reduce(next_fib, xrange(5), (1, 1))[0]
#=> 8


Reducing execution time of an HTML parsing script

There's a few things you can do to improve here:

Use curl instead of get_file_contents, it speeds the document retrieval up so much.
The following could be converted to a ternary statement:

if (count($var1) >= 2) {
    $var1 = implode("%20",$var1);
} else {
    $var1 = implode("%",$var1);
}

Notice that the condition is reversed:

$var1 = implode('%' + (!count($var1) >= 2 ?: "20"), $var1);

You shouldn't be joining strings like this: "\""."$var1"."\"":

Do this instead: "\"{$var1}\"" (see that the variable is wrapped in curly braces)

Don't array_push, use the $array[] notation instead.

$return_array[] = $text1;
$return_array[] = $text2;


Function to find a substring within a string

Sorry but your code is an accident waiting to happen.

Using a constant to declare the available space in you char arrays allows your code to be more maintainable.
scanf() can overflow your buffer and corrupt everything after your buffer.  Forcibly set the BufferSize-1 character to NULL after you have run scanf() its the best you can do with the limitations you have be given.
Why are you declaring index so far up the code, always declare a variable as near to the point of first use as you can, also it could be const, which will make it clear to the reader that its value will never change.
Unless you compiler won't allow it declare loop variables inside the for statement i.e. for (int i = 0; i < momLength; ++i).  The ++i makes no difference for simple types, but when you move on to iterators it does.
Always try and use meaningful variable names, i and j are not very meaningful.  You might read this again in 12 months, so make it easy for yourself.
Now the bad news, I think you algorithm is wrong.  Why are you creating a copy of a string (test)?  I think it would be easier to scan through mum until you find the first character of babe (index).  Then match every character of babe to the characters of mom.  If you get to the end of babe then you have a match starting at index, if a character doesn't match then start scanning mum again at index + 1.
You need to check for zero length mom and babe values entered by the user.
stringLength() could go on "infinitely"  As it stands if you scan a value which overflows the buffer then you could keep going until you run out of memory.  You need to impose a maximum length of BufferSize.
And finally, stick some comments in, it will make it easier when you are getting marked and you'll get a better score.


CodeReview is more about reviewing code than fixing various bugs, here goes my once over:

Use a beautifier, either TidyUp in jsfiddle or jsbeautifier.org, your code is badly indented and is hard to follow because of it
Use more meaningful names:

onLegendClick: function(dt, i) { <- I am guessing dt is data, i could be anything
.style("fill-opacity", function(d, j) <- Same here

Commenting is hard, only comment what is not obvious and the general purpose of code blocks

This is too obvious:

//animate slices
methods.animateSlices(newDataSet);

This is not, but there is no comment:

var isActive = Math.abs(1 - d3.select(this).style("fill-opacity"));

Not sure if this is a bug, or something I dont grasp, why are you referring to completeData even though you might be running of methods.manipulatedData, if this is correct then you should have a comment there

 newDataSet[j].total = completeData[j].total;

This could use shortcut syntax:

newDataSet = completeData;
if(methods.manipulatedData) {
  newDataSet = methods.manipulatedData;
}

becomes then

newDataSet = methods.manipulatedData || completeData;

This could also use a short cut syntax:

if(isActive) {
  newDataSet[j].total = completeData[j].total;
} else {
  newDataSet[j].total = 0;
}

becomes then

newDataSet[j].total = isActive ? completeData[j].total : 0;

Do not pollute the global namespace, newDataSet is used without a var declaration

All in all, I think you could have pasted more code to review, we tend to not review the code in the jsfiddle, only what you pasted. My counter proposal would look like this:

onLegendClick: function(dt, i) {

  var completeData = jQuery.extend(true, [], methods.currentDataSet),
      newDataSet = methods.manipulatedData || completeData;

  d3.selectAll('rect')
    .data([dt], function(d) {
      return d.data.label;
    })
    .style("fill-opacity", function(d, j) {
      //Witty comment on how this works
      var isActive = Math.abs(1 - d3.select(this).style("fill-opacity"));
      //Witty comment as to why I still need completeData
      newDataSet[j].total = isActive ? completeData[j].total : 0;
      return isActive;
    });

  methods.animateSlices(newDataSet);
  methods.manipulatedData = newDataSet;
}


Project Euler Problem # 8 maximum product of sequences

Some suggestions:

number and n could be parameters to this script. That way the whole thing would be reusable.
You can use list comprehensions to partition your string:

>>> def partition(digits: str, length: int) -> List[str]:
...     return [digits[index:index + length] for index in range(len(digits) - length + 1)]
...
>>> partition("12345", 3)
['123', '234', '345']

Multiplying N random digits is going to be slower than checking whether any of the digits are zero. So your first pass could be to exclude any partitions which contain zero. If there are no partitions left afterwards the max is zero, and you've done no multiplications at all.

>>> partitions = partition("7316717653133062491", 13)
>>> nontrivial_partitions = [partition for partition in partitions if "0" not in partition]
>>> nontrivial_partitions
['7316717653133']

An optimization on the above is to immediately discard the next N - 1 digits as soon as you encounter a zero when generating partitions, since all of those partitions are also going to multiply to zero. Make sure you check for any zeros within those numbers as well to keep skipping.
It looks like you have a newline at the end of number.


My 2 cents:

please use lowercase camelcase ( lib_is_list -> libIsList )
The first 5 lines seem clumsy

Checking for an array with typeof 'object' is odd
Changing the type of a variable/parameter is odd and not recommended, you do this twice
Dont drop newlines ( for (var i in lib) require(lib[i], obj, libs_obj); )

You can use lib.callbacks = lib.callbacks || [] instead of if (lib.callbacks === undefined) lib.callbacks = [];
Why would you assign first callbacks, and then check() whether you should return
Your handling of obj , count and callbacks is roundabout, the lack of newlines dont help,
The function name ready() is unfortunate, ready is most commly used for the callback after http requests
You should consider merging/reworking ready/script_downloaded/download_script
The src parameter is unfortunate, since it does not contain the source, maybe url ?
I like defensive programming, but checking for callback seems much, since your code guarantees it

Overal, I have to say this seems over-engineered, I think you are trying to be too smart.


Modifying a string by passing a pointer to a void function

No, I've compiled your code with C90 and it doesn't reverse the given string.

int main(int argc, char *argv[]) If you're not compiling from the command line with arguments to be used by the program, then int main() suffices.
Passing argument by pointer is used when you want the value of the variable changed. Say I have a variable int var and a function change(.), I want change to alter the value of var. If I declare change as void change(int n) and I call change(var), function change will take a copy of var named var but it's only a copy, its address is different from the original var. Any change you make on copy var will not affect the original var. If i declare change as void change(int* n), then change will only accept int pointers, I have to pass the address, &var into change as change(&var). Now working on this address is exactly like working on the initial var.

To understand pointer-array relationship read wikipedia.

int array[5];      // Declares 5 contiguous integers
int *ptr = array;  // Arrays can be used as pointers
ptr[0] = 1;        // Pointers can be indexed with array syntax
*(array + 1) = 2;  // Arrays can be dereferenced with pointer syntax
*(1 + array) = 3;  // Pointer addition is commutative
2[array] = 4;      // Subscript operator is commutative

Array names are not really pointers but can be used as pointers. Instead of  strreverse(&str[0]), you can do strreverse(str). Same result.

You've passed argument as pointer but your code still fails, why?

One thing to know about fgets is that unless there is an [EOF][2] which you can only get from an input file or Ctrl+Z if you run from the command line, fgets exits when the length argument is reached or it encounters a newline. In summary, fgets reads the newline as a character when you press enter key, increasing your desired length by 1. So if I had entered "my string" + Enter, your variable str becomes "my string\n".
So you got the length of the string into len. The array string is zero-based, calling string[len] return the char after the desired last one. The last char is string[len - 1].

You should have done this;

char string2[len];

for(i=0; i<len; i++){
  c=string[i];      //variable c is unimportant
  string2[len-i-1] = string[i];  //observe the -1, when i = 0, string2[len - 1] = string[0]
}
string2[len] ='\0';

Now that you're done reversing, you need to understand the implication of your next move.

string = string2;

string is a pointer, but that doesn't make it any less of a variable, it's a pointer variable, it also has an address. And if I declare a pointer variable to its address, that pointer will also have an address. Going back to what I said earlier, when you call change(&var), a copy of the address of var is passed into the function, so when you change the value of this pointer, it no longer holds the address of var. You may think about dereferencing, like this

*string = *string2;

but this will only alter the first value of the array since *string is same as string[0]. The solution is to copy element by element.

for(i=0; i<=len; i++)
  string[i] = string2[i];

Now your string is reversed.

Read this wikipedia article to understand how an array can be reversed faster.


It's been a couple of months so maybe you've moved on, but I had a look through this today. I also may have read too much into your example use case, so apologies if this isn't helpful.

If like in your example we can restrict the scope down to cases where K is covariant, and we can also remove the higher-kindedness of the value type, then we can improve the type safety significantly. So much so that we can escape all of the asInstanceOf calls!

class TypeMatchingMap[K[+_ <: B], B](private val contents: Map[K[B], B]) {
  def +[T <: B](kv: (K[T], T)): TypeMatchingMap[K, B] =
    new TypeMatchingMap[K, B](contents + kv)

  def -[T <: B](k: K[T]): TypeMatchingMap[K, B] =
    new TypeMatchingMap[K, B](contents - k)

  def apply[T <: B : ClassTag](k: K[T]): T =
    contents(k) match {
      case t: T => t
      case _ => throw ??? // Insert throwable here
    }

  def get[T <: B : ClassTag](k: K[T]): Option[T] =
    contents.get(k).flatMap {
      case t: T => Some(t)
      case _ => None
    }

  def toSeq: Seq[(K[B], B)] = contents.toSeq

  override def toString: String = contents.toString()

  override def equals(obj: Any): Boolean =
    obj match {
      case m: TypeMatchingMap[_, _] => m.contents == this.contents
      case _ => false
    }

  override def hashCode(): Int = contents.hashCode()
}

object TypeMatchingMap {
  def empty[K[+_ <: B], B]: TypeMatchingMap[K, B] =
    new TypeMatchingMap[K, B](Map.empty)
}

object TypeMatchingMapTest extends App {
  sealed trait NumBox
  type BoxID[+T <: NumBox] = UUID

  case class FloatBox(n: Float) extends NumBox
  case class DoubleBox(n: Double) extends NumBox
  case class IntBox(n: Int) extends NumBox

  var map: TypeMatchingMap[BoxID, NumBox] = TypeMatchingMap.empty[BoxID, NumBox]

  val id5f: BoxID[FloatBox] = UUID.randomUUID()
  map = map + (id5f -> FloatBox(5f))

  val id6d: BoxID[DoubleBox] = UUID.randomUUID()
  map = map + (id6d -> DoubleBox(6.0))

  val id7i: BoxID[IntBox] = UUID.randomUUID()
  map = map + (id7i -> IntBox(7))

  val f5: FloatBox = map(id5f)
  val d6: DoubleBox = map(id6d)
  val i7: IntBox = map(id7i)

  println(map)
  println(map.toSeq)
}

If you can't make the assumptions I've made above, I'd still recommend changing the signature of - to def -[T <: B](k: K[T]): TypeMatchingMap[K, V, B]. Consider the following:

val map: TypeMatchingMap[K, V, Int] = ???
val k: K[String] = ???
map - k

We know that the last line won't ever do anything useful, so in my mind it would be kinder to prevent it from compiling so as to prevent any client of the API from making a mistake.

Happy to discuss the code more, but didn't want to go into too much detail if you're no longer interested.


Student Class in C++ using sstream for format

You are writing a C++ program, so why have you used C Style comments?
If parameters aren't changing it makes it clearer to readers/maintainers if you declare them as const.  It they are const they may as well be const references.
The point of namespaces is to provide a degree of separation of the code in libraries, so they don't clash.  using namespace std; breaks this don't use it.
Defining multiple variables on a line is a maintenance nightmare, also it means you can write comments explaining what they are used for.
There are very few cases when not assigning an initial value to a variable is a good idea.  The first time you production code crashes on the customer's machine you will appreciate why initialising variables is a good idea.
Rather than calling 4 set functions why not define a constructor that takes for optional parameters?
Rather than letting main() format the output why not write a function that displays the student record in the format that the class dictates.  To make it easier, just right the data to a multi line string.
You should get into the habit of commenting the code better.
Although you don't need to explicitly declare the class members as private it is a good idea to do so, because then someone can add a public function at the top of the class without exposing all your variables.
Its a personal preference but I think the Java style of curly braces {} shouldn't be used in C++.  It makes the code clearer if every { and } is on a separate line.  IMO.
Always include all header files you need, it makes it easier to reuse code because everything you need is there.  (You missed ).
The code should be in 2 files, the class in one and main in another.

`

#include <string>
#include <iostream>
#include <sstream>

// Enter code for class Student here.
// Read statement for specification.
class Student
{
private:
    int m_age;
    string m_first_name;
    string m_last_name;
    int m_standard;

public:
    Student(const int age, const std::string& fName, const std::string& lName, const int& standard)
        : m_age(age)
        , m_first_name(fName)
        , m_last_name(lName)
        , m_standard(standard)
    {
    }

    int get_age() const
    {
        return m_age;
    }
    std::string get_first_name() const
    {
        return m_first_name;
    }
    std::string get_last_name() const
    {
        return m_last_name;
    }
    int get_standard() const
    {
        return m_standard;
    }
};

int main()
{
    int age(-1)
    int standard(-1);
    std::string first_name();
    std::string last_name();
    stringstream ss();

    cin >> age >> first_name >> last_name >> standard;

    Student st(age, first_name, last_name, standard);

    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";

    ss << st.get_age() << "," << st.get_first_name() << "," << st.get_last_name() << "," << st.get_standard();
    cout << ss.str() << endl;

    return 0;
}

`


Implementing parser combinators in a functional manner

I'm going to admit right off the bat here that I've never written a parser using combinator functions before. I have quite a bit of experience with Clojure though, so I'll be primarily focusing on idiomatic Clojure, and proper functional practice.

I have a few main concerns with your code:

You're using def inside of defn! This is a very bad idea. def (and by extension, defn) create(s) globals that persist even after the function they're in has returned! Run your -main, then check what the value of digit is. You're in for a surprise. It's in scope, and has the last value that was assigned to it. From a functional perspective especially, this is bad. def carries out side effects and is leaking the internal state of your functions into the global scope. Use let instead.

Instead of writing:

(def a 1)
(def b 2)
(println (+ a b))

Write:

(let [a 1
      b 2]
  (println (+ a b)))

let creates a restricted scope, and just generally looks much cleaner.
Your brace placement is very reminiscent of imperative style curly brace placement. This is causing a lot of bloat and making your code more verbose than it needs to be.

I'm guessing you're doing this to make matching braces easier for you. If this is the case, don't make your life unnecessarily difficult! Lisps are quite difficult to write unassisted. If you're going to write Clojure, you should spend an afternoon getting familiar with Par-Infer. It infers parenthesis placement based on indentation, so you can write Clojure like it's Python. This is huge. Besides the odd edge case, I never need to manually add a closing brace, or worry about its placement.

I highly recommend IntelliJ with the Cursive plugin; both of which have free community versions. I've been using them for roughly 2 years now, and it's a phenomenal environment to write in.

Just to show the difference, this is what your many function automatically gets formatted as when I paste it into IntelliJ:

(defn many [p0]
  (fn [stream]
    ((fn inner [stm]
       ((fn [res]
          (if res
            ((fn [r1]
               (if r1
                 (list (concat (nth res 0) (nth r1 0)) (nth r1 1))
                 res))

             (inner (nth res 1)))
            res))
        (p0 stm)))
     stream)))

No more needing to carefully place trailing braces to make debugging brace placement issues easier. Just let Par-Infer handle it for you.
Your variable names are bad. Names like r1 and p0 give very little information, and are the kind of names I'd expect to see post-decompilation. For the sake of you and those who may read your code, more descriptive names are a must.
You have what appears to be documentation as comments above your functions. defn has a built-in ability to handle documentation:

(defn alt
  "Returns first successful parse"
  [& ps]
  (fn [stream]
    (reduce #(or %1 %2) error (map #(% stream) ps))))

You use this for -main, but nowhere else.

After taking the above suggestions into consideration (except for the variable names), your code would look more like:

(ns main.core
  (:gen-class))

(def error "The error message for the parser functions"
  false)

(defn lit
  "Parses a single charactor"
  [c]
  (fn [stream]
    (if (= (first stream) (first (seq c)))
      (list (seq c) (rest stream))
      error)))

(defn alt
  "Returns first successful parse"
  [& ps]
  (fn [stream]
    (reduce #(or %1 %2) error (map #(% stream) ps))))

(defn seqn
  "Tries to parse in series, error if any have an error"
  [& ps]
  (fn [stream]
    (apply
      (letfn [(inner ([stm p0] ; Letfn is the local equivilent of defn
                      (p0 stm))

                     ([stm p0 p1]
                      ((fn [r0]
                         (if r0
                           ((fn [r1]
                              (if r1
                                (list (list (nth r0 0) (nth r1 0)) (nth r1 1))
                                error)
                             (p1 (nth r0 1))))
                           error)
                        (p0 stm))))

                     ([stm p0 p1 & p]
                      (let [r0 (p0 stm)]
                        (if r0
                          ((fn [r1]
                             (if r1
                               ((fn [res]
                                  (list (list (nth r0 0) (nth r1 0) (nth res 0)) (nth res 1))
                                 (apply inner (nth r1 1) p)))
                               error)
                            (p1 (nth r0 1))))
                          error))))])

      stream ps)))

(defn many
  "Parser that parses as many times as it can, at least once though, or it is an error"
  [p0]
  (fn [stream]
    ((fn inner [stm]
       ((fn [res]
          (if res
            ((fn [r1]
               (if r1
                 (list (concat (nth res 0) (nth r1 0)) (nth r1 1))
                 res)

              (inner (nth res 1))))
            res)
         (p0 stm)))
      stream))))

(defn func
  "Parser that applies a function to the result of another parser."
  [p0 f]
  (fn [stream]
    ((fn [res]
       (list (f (nth res 0)) (nth res 1))
      (p0 stream)))))

(defn num-to-int [n]
  (Integer/parseInt (apply str n)))

(defn get-val [[res remains]]
  res)

(defn -main
  "Main function, this computes the number 1904 from the string '34*56'"
  [& args]

  (let [digit (alt (lit "1") (lit "2") (lit "3") (lit "4") (lit "5") (lit "6") (lit "7") (lit "8") (lit "9") (lit "0"))
        number (func (many digit) num-to-int)
        mul (func (seqn number (lit "*") number), (fn [[a b c]] (* a c)))]

    (println (get-val (mul "34*56")))))

These were the main things. Now I'll just comment on more nitpicky things:

nil is more commonly used to represent bad data, instead of false. Also, unless you think you may want to change the value of error later, I'd also just write nil directly instead of labeling it as error. It's generally understood that nil represents the lack of usable data, which appears to be your intent here.

list is most commonly used when writing macros to create code in the macro (because lisps are homoiconic). Consider just using a vector literal ([]) instead unless you absolutely need list behavior:

(list (seq c) (rest stream))

to

[(seq c) (rest stream)]

Some of your functions are huge! I would definitely consider breaking them down. For example, I don't see why inner is defined inside of seqn; it doesn't form a closure over any local variables. From the looks of it, it's quite complicated and makes up the majority of the functionality of seqn. I'd make it it's own function, then have seqn use it. That will leave you with two smaller, easier to test functions. Also, are you sure inner should be a giant function with multiple arities? It wouldn't be cleaner to have it with fewer arities, or even make it multiple smaller functions? Remember, when programming functionally, the function is considered the smallest unit of code. Functions should be as large as necessary, but as small as possible. If you look at my repositories, I have a ton of small, bite-sized functions that each have an extremely focused, narrow scope. This makes testing very easy, and prevents you from needing to go over a giant wall of code making up a function trying to decipher what it's doing in it's entirety.

For num-to-int, long is the native number type that Clojure uses. If you cast to int, it's just going to be converted to long somewhere down the road, and that could potentially lead to a performance hit. You might also want to make it clearer that "n" is actually a seq. Calling the parameter n then writing (apply str n) is very confusing, since I wouldn't expect n to be a sequence. I would change it to:

(defn num-to-int [n-seq]
  (Long/parseLong (apply str n-seq)))

get-val is basically just first. Unless you really like how the name helps readability, I'd just use first.

(alt (lit "1") (lit "2") (lit "3") (lit "4") (lit "5") (lit "6") (lit "7") (lit "8") (lit "9") (lit "0"))

has a ton of repetition. There's a lot of ways to fix this. I'd lean towards something like this though:

(->> "1234567890"
  (map str) ; Turn each char into a string
  (map lit) ; Turn each string into a literal f
  (apply alt)) ; Then give them to alt

Note that even though map is used twice, this only does a single iteration due to laziness! This could also be shortened using comp:

(->> "1234567890"
  (map (comp lit str)) ; Turn each char into a string, then give to lit
  (apply alt)) ; Then give them to alt

Although I find the former more readable.

I'm trusting that your constant return of anonymous functions is necessary for the algorithm. I've never seen so many functions being returned from other functions! If it's necessary, it's necessary, but while trying to debug a issue, I got a mess of an error like this:

  ArityException Wrong number of args (0) passed to: parser-review-fixed/func/fn--1421/fn--1422  clojure.lang.AFn.throwArity (AFn.java:429)

The function inside of the function inside of func threw an arity error! Good luck debugging that!

The recursive call inside of inner inside of many could/should be "optimized". Change:

(inner (nth res 1))

to

(recur (nth res 1))

Use of recur prevents Stack Overflows by essentially making use of Tail-Call Optimization (although, from what I understand, the inner workings are far more complicated than that).

I personally love threading macros (-> and ->> mainly). I'd lean towards writing your alt function as:

(defn alt
  "Returns first successful parse"
  [& ps]
  (fn [stream]
    (->> ps
         (map #(% stream))
         (reduce #(or %1 %2) error)))) ; %1 can just be written as %

That's nice (imho), but it's not optimized. reduce actually allows for early exit using reduced! It would be more efficient (but more verbose) to write:

(defn alt
  "Returns first successful parse"
  [& ps]
  (fn [stream]
    (->> ps
         (map #(% stream))
         (reduce (fn [acc x]
                   (if x
                     (reduced x)
                     acc))
                 error))))

As soon as an accumulator for reduce becomes reduced, the reduction ends, and the reduced value is returned. This prevents the entire sequence from needing to be checked if, say, the first value is truthy.

But, the core already has a function that basically does this: some. Since you don't need to do any conversion prior to testing for thruthiness though, you can use identity to "forward" the value in place of a predicate. Then alt just becomes:

(defn alt
  "Returns first successful parse"
  [& ps]
  (fn [stream]
    (->> ps
         (map #(% stream))
         (some identity)))) ; some returns the first truthy value

I came back to this and realized it can be reduced further! You can get rid of the call to map and make the #(% stream) the predicate of some. This makes it trivial:

(defn alt
  "Returns first successful parse"
  [& ps]
  (fn [stream]
    (some #(% stream) ps)))

Regarding your recent edit clarifying what seqn is doing, these are the two options I'd choose between:

(defn sequence-parser1 [& parsers]
  (fn [stream]
    (reduce (fn [[res acc-stream] p]
              (let [[r stream'] (p acc-stream)]
                [(conj res r) stream']))
            [[] stream]
            parsers)))

(defn sequence-parser2 [& parsers]
  (fn [stream]
    (loop [[p & rest-parsers] parsers
           acc-stream stream
           res []]
      (if p
        (let [[r stream'] (p acc-stream)]
          (recur rest-parsers stream' (conj res r)))

        [res acc-stream]))))

Both are basically the same code; just a reduction over parsers. I tend to lean towards using loop when I have multiple accumulators though, as I find constant pairing/deconstruction in the reducing function to be messy.

If you didn't need to accumulate a stream while iterating the parsers, this could be done very succinctly using map, but alas, that wouldn't work here unfortunately.

WARNING!

I have to admit, I have basically no clue what most of this code is doing, and because of the unidiomatic way that it's written, it confused the hell out of my IDE. Because of the indentation and the constant application of temporary functions, this was extraordinarily difficult to make runnable after I fixed it up. If you try to run that first "touched up" code dump I posted, you'll get an error. There's a mismatched brace somewhere in the seqn I posted, but I can't for the life of me find the issue. Use what I posted here more as a general guide instead of copying and pasting it and trying to use it.


Grouping consecutive numbers into ranges in Python 3.2 : New version for set

def range_find(pageset,upperlimit=1000):

    pagerangelist=[]

    for page in range(0,upperlimit):

There is no reason to include the 0. Why don't you calculate the upperlimit by max(pageset)?

        if page in pageset and previouspage in pageset:pagerangelist[-1].append(page)
        elif page in pageset and not (previouspage in pageset):pagerangelist.append([page])
        else: pass

Don't squish all that stuff onto one line. It makes it harder to read. Having an else: pass case is useless

        previouspage=page

Since you are counting, just use page - 1 instead of previouspage

    pagerangestringlist=[]

    for pagerange in pagerangelist:

        pagerangestringlist.append(str(pagerange[0])+('-'+str(pagerange[-1]))*((len(pagerange)-1)>0))

Too clever. Just use an if. This technique makes it harder to see what is going on. Also pointless extra parens.

    return(','.join(pagerangestringlist))

Don't put parens around your return statement expressions.

Algorithmwise this may be problematic because it will slower for books with many pages even if you don't use many pages from them. For example

range_find({1, 2, 1000000},100000000)

Will spend a long time churning through pages that aren't really of interest.


Generic class for displaying UIAlertView / UIAlertController on iOS

As a start, this is confusing:

- (BOOL) supportsiOS8 {
    Class kAlertViewClass = NSClassFromString(@"UIAlertController");
    return !kAlertViewClass ? NO : YES;
}

There was a time when I was uncomfortable with ternary operators.  They're admittedly kind of weird.  I've gotten used to them, and I do enjoy them, but they should be used appropriately.

The logic here is that NSClassFromString returns nil if it can't figure out what class you've specified.

For starters, I'd change this to look more like this:

- (BOOL)supportsiOS8 {
    return NSClassFromString(@"UIAlertController") != nil;
}

Now it's slightly more readable and more clear what we're doing.  We don't actually care what's returned beyond whether or not it is nil.

However, there's still problems...

Your method is called supportsiOS8, but all your method actually checks is whether or not this class can see a class called UIAlertController.  And there's a difference.

I can use a class called UIAlertController on iOS 7 and lower.  It's simply a matter of me implementing that class myself.  If I've imported that class's file into this file, your supportsiOS8 will return YES.  And my implementation of UIAlertController may or may not match Apple's implementation.  So with that said, simply renaming the method as supportsAlertController wouldn't really work.

Moreover, it's likely that UIAlertController will continue to exist in iOS 9 and onward.  Apps that use this class may or may not actually support iOS 8 (because supporting iOS 8 isn't actually necessary).

Instead, what we actually need to do is check the version of iOS that the user is actually using and compare it to the minimum iOS version for Apple's UIAlertController (iOS 8).

For starters, we can use the following method to determine the device's version:

[[UIDevice currentDevice] systemVersion];

This will return the device's version as an NSString.  It might look something like @"8.1".

Now, we compare the return of this to the version we want.

- (BOOL)hasMinimumRequiredOS {
    NSString *deviceVersion = [[UIDevice currentDevice] systemVersion];
    return ([deviceVersion compare:@"8" options:NSNumericSearch] != NSOrderedAscending);
}


The design is fine. You modeled the rover as a class, its actions with methods, and its state with member variables. This is natural, intuitive and simple, good this way.

On top of the issues Jerry already pointed out in his answer, I have a few additional comments about the implementation technique.

The rotation methods are a bit tedious, and tedious tasks are sometimes error prone. I would recommend a different approach for changing the orientation:

Create a simple string with the orientations in clockwise order, that is "NESW"
Forget about storing the name of the current orientation, it's enough to store its index in the orientations string. In all actions of the rover, we can work with this index and the string
When rotating right,  the index of the target orientation is the index of the current +1 modulo length(orientations)
When rotating left, the index of the target orientation is the index of the current + length(orientations) -1 modulo length(orientations)

For moving forward, you could do similarly, by using arrays for the x and y movements depending on the index of the current orientation, so for x the content will be {0, 1, 0, -1}, and for y it will be {1, 0, -1, 0}.

The benefit of this approach will be faster actions, as there will be no more conditional statements (also called a table driven approach).


Python XML parsing, extraction and renaming files

Some style changes can happen, most are described here.

Using single letter variable names can be hard to understand, and don't explain what the data is well. It is good not to use them.
str.format is the best way to put variables into strings. E.G. '{}_{}.cps'.format(xmlfile, name_suffix)
CONSTANTS should be all caps. MODEL_FILE = 'ct.cps'
When passing 'kwargs' don't put spaces around the = operator. E.G. encoding='utf-8'
Use new-lines sparingly.
In-line comments are harder to read then comments before the code.
Comments should have a space between the '#' and the comment.

It may be good to change create_paramsuffix_copies to a generator, in this case it should be faster than making a list.

def create_paramsuffix_copies(xmlfile):
    NSMAP = {"c": "http://www.copasi.org/static/schema"}
    parsed = ET.parse(xmlfile)
    for a in parsed.xpath("//c:Reaction", namespaces=NSMAP):
        for b in a.xpath(".//c:Constant", namespaces=NSMAP):
            yield '{}_{}'.format(a.attrib['name'], b.attrib['name'])

You could add docstrings to your program so people know what the functions do at a later date.

But it looks really good!


Here's a generator in a generator:

m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

def diags(mat):
    width, height = len(mat[0]), len(mat)
    def diag(sx, sy):
        for x, y in zip(range(sx, height), range(sy, width)):
            yield mat[x][y]
    for sx in range(height):
        yield list(diag(sx, 0))
    for sy in range(1, width):
        yield list(diag(0, sy))

Usage:

>>> list(diags(m))
[[1, 6, 11, 16], [5, 10, 15], [9, 14], [13], [2, 7, 12], [3, 8], [4]]

diag starts from a coordinate and walks down the diagonal, yielding elements from it. It doesn't raise an IndexError, because zip exits after the shortest iterable is exhausted.

The last four lines are a bit inelegant, but I don't know a better way.


1. Review

There are a bunch of small problems here — I think that if you had given yourself some more time (or looked more carefully at the answers you were given to your previous question) then you would have been able to fix many of them yourself.

Missing docstrings — you've written one for factors_factorial but what do the other functions do?
Vague variable names — what kind of object is obj? What kinds of objects are counted by obj_count? The name i is normally used for indexes but this code uses it for characters, so c would be better. I would expect the name p to refer to a prime, but here it refers to a count or multiplicity, so n or m would be better.
For portability to Python 3 it's a good plan to stick to // for integer division and / for floating-point division. In Python 2 you can use from __future__ import division to enforce the Python 3 semantics. (Note that PEP 238 is from 2001 — fifteen years later you shouldn't be writing new code using the old semantics.)
In the expression:

Counter([i for i in Counter(obj).values() if i > 1])

there's no need to create a list which you are going to throw away again immediately — you can pass a generator expression directly to the Counter constructor.
Instead of looping over the keys of a mapping and then having a separate lookup to find the value, use the items method to loop over the keys and values simultaneously.
Instead of adjusting the values of factors one at a time:

count_p = factors_factorial(n, m)
for prime in count_p:
    factors[prime] -= count_p[prime]

make use of the subtraction operation on Counter objects:

factors -= factors_factorial(n, m)

Each time factors_factorial is called, it has to generate the primes again. It would be better to generate them just once.
Instead of log(n)/log(p), write log(n, p) and save a function call. See the math.log documentation.
This loop requires two calls to log, and computes a power on every iteration:

for k in range(1, int(1+log(n)/log(p))):
    mul += n // p**k

It's better to write the loop like this:

k = n
while k:
    k //= p
    mul += k

Writing it like this is not only simpler and avoids the power, but k gets smaller on each iteration, and so the divisions get cheaper as you go along.

2. Use NumPy

The code in the post imports NumPy in order to use numpy.prod. But if you're going to use NumPy at all, then there's no reason not to use it throughout the code:

import numpy as np

def factorial_factors_powers(primes, n):
    """Return an array containing the power of each prime in the
    factorization of n!.

    """
    p = primes
    n = np.full_like(p, n)
    result = r = np.zeros_like(p)
    while True:
        n //= p
        if n[-1] == 0:       # some primes not contributing any more?
            l = n.argmin()   # number of primes still contributing
            if l == 0:
                break
            n, r, p = n[:l], r[:l], p[:l]
        r += n
    return result

def fast_unique_perms(s):
    """Return the number of unique permutations of the string s."""
    s = str(s)
    primes = generate_primes(len(s) + 1)
    powers = factorial_factors_powers(primes, len(s))
    for n, m in Counter(Counter(s).values()).items():
        if n > 1:
            powers -= factorial_factors_powers(primes, n) * m
    return np.prod(np.array(primes, dtype=int) ** powers)

Note the use of dtype=int to force NumPy to do the final set of multiplications using Python's bignums instead of NumPy's fixed-width numbers.

This is around five times as fast as the code in the post.


Let's summarize the business rules:

Characters other than digits, !, or x are stripped.
If any of the four types of phone numbers is provided, it must be valid.
At least one of { home, mobile, work } must be provided.

Requirement 3 is taken care of by validate :phone_provided, which is simple and fine.

The dissatisfaction comes from implementing Requirements 1 and 2.

The implementation of Requirement 1 can be simplified by making strip_bad_characters() tolerant of nil.  You can also call #read_attribute_before_type_cast() to avoid interpolation.

def strip_bad_characters(attr)
  input = read_attribute_before_type_cast(attr)
  input.gsub(/[^\d+!x]/, '') if input
end

Also, clean_phone_numbers() can use a loop:

def clean_phone_numbers
  [:phone_home, :phone_mobile, :phone_work, :phone_fax].each do |attr|
    self[attr] = strip_bad_characters(attr)
  end
end

The solution for Requirement 2 is simple: wrap the entire regular expression in \A( )?\Z to make it optional.  Then, you can get rid of all the …_is_filled? helpers.


Your specific usage seems to be thread-safe. But it's relying on implementation details (about lambdas), which you shouldn't do. It's also extremely easy to get it wrong.

I believe the only way it will work is if you're closing over this, but not any other variables and that this is a type that properly implements ISynchronizeInvoke (like a WinForms form or control). This means that it won't work if:

you're calling it from a static method
you're only calling a static method from inside the lambda
you're closing over some local variable or parameter
you're calling it from another class

Because of that, I would never use code like this.

I think that you should just use Invoke() directly, something like:

Invoke(new Action(onCompleteHandle));

If you don't like that you need to specify the delegate type, you could write a couple of simple extension methods like:

public static void Invoke(this ISynchronizeInvoke target, Action action)
{
    target.Invoke(action, null);
}

and then use it like this (that this is required):

this.Invoke(onCompleteHandle);


If you change the first line from

byte[] output;

to

byte[] output = GetBytes(context, model, viewName, configureSettings);

and then revert the if condition you can return early.

So the remaining code (if the filename is valid and the file exists) could become

by stacking the usings which saves some horizontal spacing
by using the byte[] output for the PdfReader ctor
and using copyStream.GetBuffer() instead of calling its ToArray() method which eleminates the creation of an additional array

like so

public byte[] GeneratePdfOutput(ControllerContext context, object model = null, string viewName = null,
    Action<PdfWriter, Document> configureSettings = null, string filename = null)
{
    byte[] output = GetBytes(context, model, viewName, configureSettings);

    if (string.IsNullOrEmpty(filename) || !File.Exists(filename))
    {
        return output;
    }

    using (var copyDoc = new Document())
    using (var copyStream = new MemoryStream())
    {
        copyDoc.Open();

        PdfCopy copy = new PdfCopy(copyDoc, copyStream);
        copy.CloseStream = false;
        copy.AddDocument(new PdfReader(output));

        using (var reader = new PdfReader(filename))
        {
            reader.ConsolidateNamedDestinations();

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                PdfImportedPage page = copy.GetImportedPage(reader, i);
                copy.AddPage(page);
            }
        }

        copy.Close();
        copyDoc.Close();
        return copyStream.GetBuffer();
    }
}


Readability of JavaScript shorthand for converting strings to numbers with default value

Seems fine syntactically and perfectly idomatic, but always, always supply a radix argument to parseInt:

var numberToAdd = parseInt($('#number-to-add').val(), 10) || 500;

To quote MDN:

  radix: An integer that represents the radix of the [...] string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
  [...]
  If the input string begins with "0", radix is eight (octal) or 10 (decimal).  Exactly which radix is chosen is implementation-dependent.  ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.  For this reason always specify a radix when using parseInt.

(emphasis in the original)


Two things stand out:

In your Bomb constructor, you do this:

Wire current_wire(wire);

This is creating a locally scoped variable current_wire and setting its value to wire, it's not updating the member variable of the class.
You are keeping track of more information than you need to.  You only need know the previous wire to know if the current wire is going to cause an explosion.  You are however keeping track of every wire in previous_cuts, although you're not using the value anyway.  Generally, you're better off not having redundant code, so if you're not going to use it, get rid of it.