Shell script that verifies checksums when moving between filesystems

I'll start with your entry point and will go through you code step by step.
The last code block will contain an updated version.

The key elements in my changes are split your functions and only do one specific task, e.g. extra function for getting a checksum of a file and another one comparing two checksums etc. A function should also get all necessary information by PARAMETER not by an environment variable set outside. This simplifies testing a lot.

The getopts part is fine but you should just store the flag with the additional "-" as it will simplify things later in your code. You may also want to exit if an unknown parameter was provided. I would also rename FLAGS to MV_FLAGS as it describes better what the flags are for. You would normally also print a usage if an invalid parameter was provided. After parsing the options you should also check if enough parameters were provided and print a message otherwise but this is just a UX thing.

MV_FLAGS=''
#get all the move flags and store them in a variable
while getopts "finv" opt; do
    case $opt in
        f) MV_FLAGS="$MV_FLAGS"f ;;
        i) MV_FLAGS="$MV_FLAGS"i ;;
        n) MV_FLAGS="$MV_FLAGS"n ;;
        v) MV_FLAGS="$MV_FLAGS"v ;;
        ?)
        echo "Invalid argument $1" >&2
        exit 1
        ;;
    esac
done
[ -n "$MV_FLAGS" ] && MV_FLAGS="-$MV_FLAGS"

#shift optindex past the flags
shift $(( OPTIND-1 ))

if [ $# -lt 1 ] ; then
   echo "You must specify additional filenames" >&2
   exit 1
fi

For the next part you should definitely quote $@ as otherwise you won't handle parameters with spaces correctly. There is also no need to compare $i with ${BASH_ARGV[0]} as $@ contains the parameter starting at 1. Instead of specifying environment variables to call your main function you should specify them as a parameter instead. BASH_ARGV is according to man bash also only set if you have debugging enabled, so it is not portable. I also don't really understand what DESTINATION should be, but you should change it as well. You should also either quote your parameters with " or use ${ I wouldn't mix them and there is no need to use " as well as ${}. You should also check if the source file is a valid file before pushing calling your function. The function name could also be improved, e.g move_file

for i in "$@" ; do
    SOURCE="$i"
    DESTINATION="$0""$(basename "$SOURCE")"
    if [ ! -f "$SOURCE" ] ; then
       echo "$SOURCE does not exist, ignoring." >&2
       continue
    fi
     move_file "$SOURCE" "$DESTINATION"
done

In your main and my move_file function you always call check_software but there is no need for it. It is enough to call it once  at the beginning. You should also create a function handling verifying the filenames so your code doesn't get clustered with the different program parameters etc:

#function that checks if dependencies are installed
check_software() {
    for name in md5sum md5 openssl ; do
        if [ $(type "$name") > /dev/null 2>&1 ] ; then
           return 0
        fi
    done
    return 1
}

if ! check_software ; then
    echo "Neither md5sum, md5 nor openssl are installed. Quitting." >&2
    exit 1
fi

Your check_filesystem can also be simplified a lot if you use a device number instead of parsing df, I'd also rename it to same_filesystem

same_filesystem() {
    if [ $# -ne 2 ]  ; then
       echo "Usage: $0 source target" >&2
       return 1
    fi
    FS1=$(stat -c "%d" "$1")
    FS2=$(stat -c "%d" "$(dirname "$2")" )
    [ "$FS1" -eq "$FS2" ]
    return $?
}

You can also simplify your main/move_file function a bit, e.g:

move_file() {
     # we already checked if the necessary programs are available no
     # need to check again
     if [ $# -ne 2 ] ; then
         echo "Usage: $0 source target" >&2
         return 1
     fi

     SOURCE="$1"
     DESTINATION="$2"

     if [ -f "$DESTINATION" ] ; then
       # do something if file already exists?!
       :
     fi

     #if file is being moved on the same filesystem
     if same_filesystem "$SOURCE" "$DESTINATION" ; then
        mv $MV_FLAGS -- "$SOURCE" "$DESTINATION"
        return 0
     fi

     echo "Starting bettermv" >&2
     #copy the file
     cp -p "$SOURCE" "$DESTINATION"

     if verify_files "$SOURCE" "$DESTINATION" ; then
        rm "$SOURCE"
        return 0
    else
        echo "Error moving $SOURCE to $DESTINATION, abort." >&2
        rm "$DESTINATION"
        return 1
     fi
}

get_checksum() {
     if [ $# -ne 1 ] ; then
         echo "Usage: $0 source" >&2
         return 1
     fi
     if type openssl >/dev/null 2>&1 ; then
         echo $(openssl md5 "$1" | awk '{print $2}')
     elif type md5sum >/dev/null 2>&1 ; then
         echo $(md5sum "$1" | awk '{print $1}')
     elif type md5 >/dev/null 2>&1 ; then
         echo $(md5 "$1" | awk '{print $4}')
     fi
     return 1
}

verify_files() {
    if [ $# -ne 2 ] ; then
         echo "Usage: $0 source target" >&2
         return 1
     fi

    CHECKSUM1=$(get_checksum "$1")
    CHECKSUM2=$(get_checksum "$2")

    [ $CHECKSUM1 = $CHECKSUM2 ]
    return $?
}

The complete script with all changes (i tested it):

#!/bin/sh

#function that checks if dependencies are installed
check_software() {
  for name in md5sum md5 openssl ; do
  if type "$name" 1>/dev/null 2>&1 ; then
    return 0
  fi
  done
  return 1
}

if ! check_software ; then
  echo "Neither md5sum, md5 nor openssl are installed. Quitting." >&2
  exit 1
fi

move_file() {
  # we already checked if the necessary programs are available no
  # need to check again
  if [ $# -ne 2 ] ; then
    echo "Usage: $0 source target" >&2
    return 1
  fi

  SOURCE="$1"
  DESTINATION="$2"

  if [ -f "$DESTINATION" ] ; then
    # do something if file already exists?!
    :
  fi

  #if file is being moved on the same filesystem
  if same_filesystem "$SOURCE" "$DESTINATION" ; then
    mv $MV_FLAGS -- "$SOURCE" "$DESTINATION"
    return 0
  fi

  echo "Starting bettermv" >&2

  #copy the file
  cp -p "$SOURCE" "$DESTINATION"

  if verify_files "$SOURCE" "$DESTINATION" ; then
    rm "$SOURCE"
    return 0
  else
    echo "Error moving $SOURCE to $DESTINATION, abort." >&2
    rm "$DESTINATION"
    return 1
  fi
}

same_filesystem() {
  if [ $# -ne 2 ]  ; then
    echo "Usage: $0 source target" >&2
    return 1
  fi

  FS1=$(stat -c "%d" "$1")
  FS2=$(stat -c "%d" "$(dirname "$2")" )

  [ "$FS1" -eq "$FS2" ]
  return $?
}

get_checksum() {
  if [ $# -ne 1 ] ; then
    echo "Usage: $0 source" >&2
    return 1
  fi

  if type md5sum >/dev/null 2>&1 ; then
    echo $(md5sum -- "$1" | awk '{print $1}')
  elif type md5 >/dev/null 2>&1 ; then
    echo $(md5 "$1" | awk '{print $4}')
  elif type openssl >/dev/null 2>&1 ; then
    echo $(openssl md5 "$1" | awk '{print $2}')
  else
    return 1
  fi
}

verify_files() {
  if [ $# -ne 2 ] ; then
    echo "Usage: $0 source target" >&2
    return 1
  fi

  CHECKSUM1=$(get_checksum "$1")
  CHECKSUM2=$(get_checksum "$2")

  [ $CHECKSUM1 = $CHECKSUM2 ]
  return $?
}

MV_FLAGS=''
#get all the move flags and store them in a variable
while getopts "finv" opt; do
  case $opt in
  f) MV_FLAGS="$MV_FLAGS"f ;;
  i) MV_FLAGS="$MV_FLAGS"i ;;
  n) MV_FLAGS="$MV_FLAGS"n ;;
  v) MV_FLAGS="$MV_FLAGS"v ;;
  ?)
  echo "Invalid argument $1" >&2
  exit 1
  ;;
  esac
done

[ -n "$MV_FLAGS" ] && MV_FLAGS="-$MV_FLAGS"

#shift optindex past the flags
shift $(( OPTIND-1 ))

if [ $# -lt 1 ] ; then
  echo "You must specify additional filenames" >&2
  exit 1
fi

for i in "$@" ; do
  SOURCE="$i"
  DESTINATION="$0""$(basename "$SOURCE")"

  if [ ! -f "$SOURCE" ] ; then
    echo "$SOURCE does not exist, ignoring." >&2
    continue
  fi

  move_file "$SOURCE" "$DESTINATION"
done


Preventing numbers from showing up in scientific notation

You could use vsnprintf if it's available on your system.  It might seem like a step backwards to use a C-style printf derivative in C++ code, but that's what's used in gcc on my Linux machine.  You can use alloca which allocates space on the stack, or a fixed size (but guaranteed sufficient) local array.

Because your StreamBuffer is not derived from std::ios_base and you haven't provided details of its implementation, I can't really show a code example but I presume that the StreamBuffer& operator<<() either is already or can be adapted to use vsnprintf.


Finding the sum of all the multiples of 3 or 5 below 1000

You are not using tail recursion in my-sum, so the compiler cannot easily turn it into iteration.
It depends on the specific problem; in this case I would probably do it iteratively.
Sure, loop is useful and convenient.

Here is my attempt:

(defun multiple-of-3-or-5 (x)
    (or (zerop (mod x 3))
        (zerop (mod x 5))))
(defun my-sum (from to)
  (loop :for i :from from :to to
    :when (multiple-of-3-or-5 i)
    :sum i))


Creating controls on a page which differ slightly depending on an external state

The alternative would be to create two similar but separate sets of controls in the markup

The terms similar and separate are confusing when considering class design. So allow me to think this through...

A calendar, dropDown, and textBox. - parts of a single class

From the given information both start and stop have these. And the only difference is the labels. So you can have one class, instantiating 2 objects, one for "stopping" and one for "starting".

public class StartStopper {
   //DatePicker control
   //DropDown control
   // TextBox control

   public StartStopper (string DatePickerLableText, string dropdownText, string reasonLabelText) { //assign the strings }
}

------------------------------------------------------------------

  The alternative would be to create two similar but separate sets of controls in the markup, and simply hide the set which are not relevant to the current state of the work item.

Here is an alternative:

The Design Paradigm

All the layering that's about to be done is all about the single responsibility principle applied well.
Classes start small and focused. DropBox and Textbox have distinct behavior and business rules between themselves. So the single responsibility of a StartStopBox class is to provide the all the behavior and features of their intimate, private, interaction - and nothing else.
DropDown, TextBox interaction and rules are what they are. It does not matter if it is for "stopping" or "starting". Either way, for example, "select the dropdown, the textbox must have an entry."
Aggregate classes into a StartStopCalendar class - it's single responsibility is to make the component classes interact, giving us more complex behavior.  Now we can tell when or if the calendar requires a value.
If any component needs more behavior for it's share of the interaction, fine. But that behavior is not StartStopCalendars responsibility. Remember, it's single responsibility is to make that new behavior interact with other components.
Net result is classes are more re-usable - it carries all it's own baggage. There is less coupling - Change what "I am valid" means and the clients don't know! They just call the same method as always.

Business Rules affecting Design

All 3 controls always work interactively

If business rules apply to all 3 controls together then let's keep them in one class. The calender has rules relating to the dropdown, and separate rules relating to the text box. And the dropdown and textbox have their relation rules too.

In this case, one class to rule them all. However we assume these rules are the same; it doesn't matter if we're going to use is for "stop" or "start".  Below we'll see how we get that context through class composition.

DropDown and textbox work together. This focused interaction is independent of the calendar

The dropDown and Textbox should be one class, and the calendar another. Further the calendar requires a StartStopBox object so we aggregate them:

public class StartStopBox {
    // "start" or "stop" work the same, only the labels have changed.
    public StartSTopBox ( string dropDownLabelText, string TextBoxLabelText) {}

    // This is ugly, and not so single responsibility.
    // The client is forced to evaluate the returned string
    // to decide if the object is valid.
    // But it's expedient and we'll see this get encapsulated later.
    public string Validate() {
        string errorMessage = string.Empty;

        if (! dropdown.IsEmpty() && ! TextBox.IsEmpty() {
             errorMessage = "\nDropDown and TextBox must both have enteries";
        }
        return errorMessage;
    }
}

public class StopStartCalendar {
     public StartSTopCalendar (StartStopBox aStarterOrStopper) {  }

      public string Validate () {
          string errorMessage = string.Empty;
          bool startStopperIsValid = false;

          errorMessage += aStarterOrStopper.Validate();
          startSTopperIsValid = string.IsNullOrEmpty(errorMessage) ? true : false;

          if (string.IsNullOrEmpty (theCalendar.DateSelected() && startStopperIsValid) // or however it's done.
          { errorMessage += "\nA date must be selected"; }

          return errorMessage;
      }
}

We have business rules for a "start object" interacting with a "stop object"

For example "cannot stop earlier than we started"

public class Interval {
     public Interval ( StopStartCalendar starter, StopStartCalendar stopper)
     {
         public bool isValid() {
             return string.IsNullOrEmpty(Validate()) ? true : false
         }

         public string Validate() {
             string errorMessage = string.Empty;
             errorMessage += "Starter object errors: \n\n" + starter.Validate();
             errorMessage += "Stopper object errors: \n\n" + stopper.Validate();

             if (starter.Date > stopper.Date ) {
                errorMessage += "\n\nStop Date cannot be Earlier than Start Date";
             }
             return errorMessage;
         }
     }

Out of the Trees and into the Forest

  ... It is a single aspnet page, which displays controls to either start or stop tracking, depending on the state of the work item.

public ProjectState { Undefined, Planning, Started, Ended }

public class Project {
    protected ProjectState currentState = Undefined;

    public Project ( Interval projectDates ) { }
    ...

Wait! Now I want to be able to ask the StartStopCalendar if it is in it's proper state, and single responsibility principle guides us in making changes.

public class StartStopBox {
    // Make it simpler, less error prone for the client.
    public bool IsValidState() {
        return string.IsNullOrEmpty(this.Validate()) ? true : false;
    }
}

public class StartStopCalendar {
    // ditto
    public bool IsValidState() {
        return string.IsNullOrEmpty(this.Validate()) ? true : false;
    }
}

public class Interval{
     . . .

     public bool IsStartState() {
         return ( starter.IsValidState() && !ender.IsValidState() );
     }

     public bool IsEndState() {
         return ( !starter.IsValidState() && ender.IsValidState() );
     }
}

public class Project {
    protected ProjectState currentState = Undefined;

    public void StartProject () {
        if (startStuff.IsStartState()) {
            currentState = ProjectState.Planning;
            DoStartingStuff(true);
        }else
           currentState = ProjectState.Undefined;
           DoStartingStuff(false);
        }
    }
}

ALMOST THERE

public class ProjetManager {
   protected Project me { get; set; }

   public ProjectStatus WhereAreYouOnThatProject () {
        return me.currentState;
   }

   public string ArentYouDoneYet() {
       return me.ProjectDates.IsEndState() ? "Yes" : "My dog ate my Homework";
   }

}

// THE CLIENT

public bob = new ProjectManager ( bobsProject);

bob.WhereAreYouOnThatProject();
bob.ArentYouDoneYet();

bob.YoureFired();

" NotImplementedException was thrown.  Stack trace ....."


This article says that a test run on that algorithm showed a bias with items less likely to move farther away from their original location than near (a bias).

My own intuition says that it could cause issues because the .sort() algorithm expects that when a given two elements are compared they will always have the same comparison result and yet that is not true when using this function.  Therefore, I'm thinking that how well this work could also depend upon how the .sort() method was actually implemented internally.

This article shows what seems to me like a better algorithm for randomness, though I wouldn't expect it to be particularly efficient:

Array.prototype.shuffle = function() {
    var s = [];
    while (this.length) s.push(this.splice(Math.random() * this.length, 1));
    while (s.length) this.push(s.pop());
    return this;
}

EDIT: Also just found this same question here: https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling.  That answer suggests this which is based on the Fisher-Yates algorithm and would be a lot more efficient than the algorithm above:

function shuffle(array) {
    var tmp, current, top = array.length;

    if(top) while(--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
    }

    return array;
}

And, here's a testpage that shows the results of your proposed method vs. the Fisher-Yates method in your browser: http://phrogz.net/JS/JavaScript_Random_Array_Sort.html.


Refactor highlight matched word in string

If text may contain HTML (in that case text is a somewhat misleading variable name) you definitely should use a HTML parser. What about this? (adding a
 as wrapper, otherwise xpath won't find parent text nodes).

require 'nokogiri'

def highlight(html, word)
  Nokogiri::HTML::fragment("
" + html + "
").tap do |doc|
    doc.search('.//text()').each do |text_node|
      new_contents = text_node.text.gsub(/\b(#{word})\b/i, '\1')
      text_node.replace(new_contents)
    end
  end.xpath("p").inner_html
end

puts highlight('
Run Rabbit Run
', "run")
#
Run
# Rabbit Run


Looking pretty neat!

But it is missing some important functionality:

Ability to define the method of request. There are many kinds of HTTP request methods. Click here to learn more.
The fact that you have to call the "dyn" method for dynamic URLs is just not my taste. Other routers are capable of determining if the URL is dynamic or not. This is pretty easy to implement. You could do it like this. You can use REGEX, specifically, you can use the pattern /^<+(.*)+>$/. What you do is, you split the URL with / and use the above REGEX pattern to determine if  that particular part of the URL is dynamic or not. You can then get the value by getting the string in the same spot from the typed in URL comparing with the URL route defined.
Another great feature would be Request and Response objects. What you would do is, in each request, you pass a Request object with all the HTTP data and that controller method would return an instance of a Response object  that would tell the router what to do. Basically, it could be what data to return, HTTP Status Code, etc.

Otherwise, good job!


Find the greatest common divisor of n numbers

As I am not a native in Javascript, I'll try to review your algorithm:

start from the lowest value and its factor is a good idea to improve speed
for your second loop I suggest you to start not from the lowest factor but start from the biggest factor. GCD is trying to find the biggest factor, So if you start from the biggest number, after you find a number that can divide all number in arr you can break your loop, it's more efficient.
I've tested it with generalizedGCD(2,[27,8]) and it returns 4 instead of 1, why? the problem is in your second loop, the size of factors changed after you delete its element and you accidentally "skip" some elements. If we try to simulate this with the example above:

    generalizedGCD(2,[8,27])
    ...
    k=0 factors=[1,2,4,8]  arr[j]=27 {27 is divisible with factors[k]=1}
    k=1 factors=[1,2,4,8]  arr[1]=27 {27 is not divisible with factors[k]=2}
    k=2 factors=[1,4,8]    arr[1]=27 {27 is not divisible with factors[k]=8} // you skipped 4
    ...
    factors=[1,4]

The solution that I can think is subtract k by 1 so it doesn't "move" when you are deleting an element in factors:

    if ( arr[j]  % factors[k] != 0 ) {
        factors.splice( k, 1);
        k--;
    }

Suggestion for another algorithm

I think it'll be better if you use faster algorithm: Euclid Algorithm. You can find GCD of every number in array by find GCD each two of them.

GCD( GCD( GCD(a[0], a[1]), a[2]), ...)

It's simple recursion:

function gcd(a, b) {
    if(b === 0) {
        return a;
    }

    return gcd(b, a%b);
}

function generalizedGCD(num, arr)
{
    factors = arr[0];

    for ( let i = 1; i < num; i++) {
        factors = gcd(factors, arr[i])
    }

    return factors;
}


In object-oriented programming, a card object is supposed to represent a card.  Your card, though… I'm not sure what it represents!  If anything, it's the ultimate chameleon card: every time you call .getSuit() or .getValue() on it, it reports a different value!

The card's identity, therefore, must be determined in the constructor, and it should never change thereafter.  All three methods should be declared const.

Furthermore, it's a bad idea to have the card's identity be randomly assigned in the constructor.  How would you create a deck of 52 different cards, if you couldn't instantiate each one deterministically?

The displayCard() method makes no sense — why should you pass in suit and value as parameters, which will then be ignored?

using namespace std; defeats the purpose of the std namespace.  It's sloppy practice in general.  In particular, you should never do that in a header file, because any .cpp file that includes that header will have its namespace contaminated as well.

Your comments are wrong: displayCard() is not a constructor.

So, the header file should look more like this:

#ifndef  CARD_H
#define  CARD_H
#include <string>

class Card
{
    public:
        // Constructor
        Card(const std::string &suit, const std::string &value);

        // Member Functions
        std::string getSuit() const;
        std::string getValue() const;
        std::string display() const;

    private:
        std::string suit, value;
};
#endif

I'll leave it to you to figure out what the implementation should look like.


Calculating factorial using Stirling's approximation

The biggest problem of your code (while being very short itself) is that hard to read and complicated formula. One way to improve readability of the formula is by using meaningful variables to name parts of the formula. This also makes it easier to find errors, because you can first look in what part of the formula the error occurs, and debug more easily.

Furthermore, adding spaces around operators inside the formula makes it more readable.

However, Python already has a solution for that in the standard library. Since your question implies that your goal is not to implement Stirling's approximation, but rather a pythonic solution, I suggest the following:

from math import factorial

print(factorial(1337))

This is probably the most pythonic way of doing it. Using math.factorial from the standard library, your code becomes more readable and you get around hard to find errors by avoiding complicated formulas.


Timing how long garbage collection is taking in C#

For continuous monitoring I agree with Zer0 to look at the % time spent in GC performance counters.

However for a session based analysis a more informative approach would be to collect the ETW traces from .NET. You can see here for the different GC related events, GCStart and GCEnd would most likely be relevant for you.

view the .NET documentation for Garbage Collection ETW Events

You can specify the GC Collect Only option exists which would be very useful here.

  The GC Collect Only Checkbox - Turns off all providers except those
  that describe garbage collections. Thus even the GC allocation
  sampling is turned off. This mode logs even less data than GC Only,
  and thus can collect data over an every longer period of time (say a
  day) in reasonable size (say 200 meg). The /GCCollectOnly command line
  option achieves the same effect.


Checking for duplicate values in database with Python

In python checking membership of an item in a set is extremely fast.

I suggest you use sets.


As pointed out by @Bob Dalgleish, you mix mutable/immutable.  You also mix pattern matching (enQueueNext) with if/else (bfs_visit).  You also mix camel case notation (enQueueNext) with underscore notation (bfs_visit).

trait would be more appropriate for Tree than abstract class.  You don't really need Tree, as I show in my example, but that is debatable.  You don't really need a queue either.

You can make very succinct code with Scala.  In my example below, the recursive BFS algorithm is basically a single line: bfsLoop(nextLayer.map(_.value) :: accum, nextLayer.flatMap(_.childrenLeftRight)).

object TreeTraversal extends App {

  case class Node[+T](value: T, left: Option[Node[T]], right: Option[Node[T]]) {
    def map[V](f: T => V): Node[V] =
                 Node(f(value), left.map(l => l.map(f)), right.map(r => r.map(f)))
    def childrenLeftRight: List[Node[T]] = List(left, right).flatten
  }
  def terminalNode[T](value: T) = Node(value, None, None)

  def dfs[T](tree: Node[T]): List[T] = {
    var output = List[T]()
    tree.map(t => (output = t :: output))
    output.reverse
  }

  def bfs[T](tree: Node[T]): List[T] = {
    @tailrec
    def bfsLoop(accum: List[List[T]], nextLayer: List[Node[T]]): List[T] = nextLayer match {
      case Nil => accum.reverse.flatten
      case _ => bfsLoop(nextLayer.map(_.value) :: accum, nextLayer.flatMap(_.childrenLeftRight))
    }
    bfsLoop(List[List[T]](), List(tree))
  }

  val tree1 = Node[Int](6, Some(Node(13, Some(terminalNode(101)), None)), Some(Node(42, Some(terminalNode(666)), Some(terminalNode(65)))))
  println("map: " + tree1.map(i => s"Hello$i"))
  println("dfs: " + dfs(tree1))
  println("bfs: " + bfs(tree1))
}

I also put this code for a separate codereview after posting it as an answer.


Checking for circular primes - Project Euler Problem 35

Updated since reading the wikipedia definition of circular prime

There are a few things I would recommend you change in your findCircularPrimes algorithm. First, you should note the algorithm is O(d*n^2) where d is the length of the max digit. If we use a hash instead of an array to store all the primes we can stop using .indexOf() to check if a number is prime, making our algorithm O(d*n).

Another note is that javascript will represent large numbers in scientific notation. This is probably not important as your algorithm will crash the browser before it becomes an issue :)

I've re-implemented your algorithm using es5 methods reduce to create the primeHash and filter to produce the circularPrime list, but your old approach will work as well.

Edit stole @200_success much faster rotate function to make the comparison a bit fairer and updated the jsperf :)

var LN10 = Math.log(10);
// Rotates the least-significant base-10 digit to the front
function rotate(number) {
    return (number / 10 >> 0) +
           (number % 10) * Math.pow(10, Math.floor(Math.log(number) / LN10));
}
//Find primes within range which are circular primes
function findCircularPrimes(range) {

    var primes = findPrimes(range);

    //use a hash of primes for faster lookup
    var primeHash = primes.reduce(function(memo, prime) {
        memo[prime] = true;
        return memo;
    }, {});

    //use a hash of primes for faster lookup
    var circularPrimes = primes.filter(function(prime) {
        //check ciruclar primes
        var nextDigit = prime;
        while( (nextDigit = rotate(nextDigit)) !== prime) {
            if(! (nextDigit in primeHash)) {
                return false;
            }
        }

        return true;
    });

    return circularPrimes;
}

Performance test of your implementation vs mine (original set of tests)


F#unctional Immutable Trie (Prefix Tree)

There are several libraries for writing unit tests in F#. For example:

FsUnit
Unquote
Fuchu

The logic is pretty clear, but there are a couple of comments

1.
Instead of:

        let child =
            match Map.tryFind el trie.Children with
            | Some t -> t
            | None -> empty

you can rewrite this code with using defaultArg

        let child =
            Map.tryFind el trie.Children
            |> defaultArg  <| empty

2.
You can use functions from a module Option, so..instead:

        match Map.tryFind el trie.Children with
        | Some t -> contains els t
        | None -> false

better:

        Map.tryFind el trie.Children
        |> Option.exists (contains els)


I found a solution using cv2.filter2D that cuts the time to 25% of the original time:

def bilateral_adaptive_threshold_f2d(img, ksize=30, C=0, mode='floor', true_value=255, false_value=0):

    mask = np.full(img.shape, false_value, dtype=np.int16)

    left_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((1,ksize+1)), anchor=(ksize,0), delta=0, borderType=cv2.BORDER_CONSTANT)
    right_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((1,ksize+1)), anchor=(0,0), delta=0, borderType=cv2.BORDER_CONSTANT)
    up_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((ksize+1,1)), anchor=(0,ksize), delta=0, borderType=cv2.BORDER_CONSTANT)
    down_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((ksize+1,1)), anchor=(0,0), delta=0, borderType=cv2.BORDER_CONSTANT)

    left_thresh /= ksize
    right_thresh /= ksize
    up_thresh /= ksize
    down_thresh /= ksize

    if mode == 'floor':
        mask[((img > left_thresh+C) & (img > right_thresh+C)) | ((img > up_thresh+C) & (img > down_thresh+C))] = true_value
    elif mode == 'ceil':
        mask[((img < left_thresh-C) & (img < right_thresh-C)) | ((img < up_thresh-C) & (img < down_thresh-C))] = true_value
    else: raise ValueError("Unexpected mode value. Expected value is 'floor' or 'ceil'.")

    return mask

Also, see the amazing response to this post for more details:
https://stackoverflow.com/questions/42540173/python-how-to-make-this-color-thresholding-function-more-efficient


Merge 2 arrays, when one is larger and can accomodate smaller

Do not throw NullPointerException when arguments are null. NPE is thrown when you are trying to access properties and methods of null reference. Not when you are checking on some preconditions. Throw IllegalArgumentException as you do in length validation. In other method you use assertions. Chose one method and stick with it, dont mix them.

You don have to define empty constructor. It is created implicitly.


General Style:

Use functions where you can. You have embedded all the code in to one method.

For many reasons, you should create a function which takes the 100 value as a parameter. Additionally, the purpose of the code is to return pairs of numbers that have 100 as the product, so what you want is a container to store each pair.

This is a start to turning your code in to Object Oriented code.

Classes (OOP)

A container for a result, which is two values that multiply to the target, would be called something like CoFactors (Factors which together make the target). It would look something like:

public class CoFactor {
    private final int lesser, greater;

    public CoFactor(int lesser, int greater) {
        this.lesser = lesser;
        this.greater = greater;
    }

    public int getLesser() {
        return lesser;
    }

    public int getGreater() {
        return greater;
    }
}

Algorithm

Now, with that class, we can return the factors of a number with a method like:

public static final List<CoFactor> getCoFactors(int target) {
    ....
}

The above method will return a list of factors that have the target as a product.

How would that be coded? First, some math....

each factor of a number has a partner (perhaps, if the number is a square number, the partner is itself (3 x 3 = 9 for example) The lesser factor will only be smaller when the lesser factor is less than the square-root of the target....
each small factor has a partnering large factor, and there is only one partner.
we only need to find the small ones to also be able to find the large ones.
we can tell if a number is a factor if there's no remainder after a division (use the % modulo operator)

This can be computed as:

List<CoFactor> factors = new ArrayList<>();
int root = (int)Math.sqrt(target);
for (int attempt = 1; attempt <= root; i++) {
    if (target % attempt == 0) {
        factors.add(new CoFactor(attempt, target / attempt));
    }
}
return factors;


The parms array could be initialized like this:

new SqlParameter("@REMOTE_ADDR", SqlDbType.NVarChar,15) { Value = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] }

It gives minimal performance gain, cause you don't need to access the array members, and it becomes more robust against the order of parameters. You could add a new one on top, without the need to change the indexes of all the other ones.

This is useless

 SqlDataReader dr = null;

it can be done right here:

 var dr =  sqlh.ExecuteReaderStoreProcedure("usp_InsertFileLocation", parms);

It's still useless, you can omit the entire dr variable.

In general I cannot see what this routine is doing. Does it a Query or an Insert on the Database. It Executes a Reader, but there's something called "InsertFileLocation". So this need at least some comment. For a clear design you might divide Taking the Request and Storing something in two different routines. Cause you should be able to test it separately.

If you have a HttpContext as a Parameter, why do you access the static variable HttpContext.Current. It is probably the same reference, but it's not good habit to use a static workaround if you already have a local parameter with the same content.


Looking at the class SimpleRandomNumberGenerator :

Having generate() delegate to a private method is, in this case a bit overkill.
You create a new Random instance for each method invocation. This makes the SimpleRandomNumberGenerator not genrating an even distirbution of random numbers. Make it a private final field initialized at the declaration or in the constructor.
Good use of coding to interfaces, by hiding the implementation details behind an interface.

Then MainApplication :

Spot on : kept simple this class' responsibility is to wire everything together and kick things off.

And now for the meat SimpleGuessingGame :

Several fields of this class can be truned into local variables in the one method that uses them : difficultyLevel, random and input.
startGame() is well implemented, easy to read.
On the whole the class has at least 2 responsibilities :

handling user interaction
keeping track of game state

That is too much. Imagine here you'd want to be able to play the same game but with a graphical UI.

So we want to split this into more classes using interfaces to hide implementation from one another.

I would suggest using these two interfaces :

interface UserInteraction {

    String askDifficulty();

    void close();

    String askToGuess();

    void showHowToEndMessage();

    void showWinMessage();

    void showGuessSmallerMessage();

    void showGuessLargerMessage();
}

interface GameState {

    Result guess(int guess);
}

public enum Result {

    CORRECT, GUESS_LARGER, GUESS_SMALLER
}

checkInputIsNumber() should be split into two separate methods : one for the difficulty and one for the guesses. They can then be named more aptly to increase readability (boolean parameters say so little at the call site)
the loop in the play() method is implemented as an infinite loop, while it is obviously driven by the game state. Meanwhile endGame() quite harshly exits, this makes it harder to embed the game in a larger program. Only the MainApplication class should call System.exit()

There's more to do as a follow up on these remarks, but I'd start there.


An alternate approach

The routine is same for all types of inputs, except for when the len(list) == 1. This is why we can use a generator function  to simplify the routine, and then a simple if statement to work with the exception

def comma_code(iterable):
    result = ', '.join(str(value) for value in iterable[:-1])
    return f"{result}, and {iterable[-1]}"

Now, since we have to deal with a special case, an if-statement can work
def comma_code(iterable):
    if not iterable: return None
    if len(iterable) == 1: return f"Just {iterable[0]}"

    result = ', '.join(str(value) for value in iterable[:-1])
    return f"{result}, and {iterable[-1]}"

The question hasn't stated what to do if the size of the container is 0, hence I have just returned None. As stated by @Stef in the comments, you can also return an empty string which is just ''.
I would prefer None as it becomes easy to trace back if an issue occurred. Moreover, you can also design a simple function that would check if the container is empty. If it is then the function can print a custom warning which can help you in debugging your code
Explanation
result = ', '.join(str(value) for value in iterable[:-1])

This is called a generator function, we're basically appending str(value) + ', ' for every value in iterable. iterable[:-1] so that we only iterate till the second last element.
to be fully verbose, :-1 says everything in iterable up till the last element


Find the intervals which have a non-empty intersection with a given interval

1. Review

There is no docstring. What does the function find_intersections do? The text in the post is pretty clear, so you could use this as the basis of a docstring. I would make it explicit that the intervals are open (if that's what you really intend), since in Python intervals are normally half-open.
There seems to be some uncertainty about whether the input intervals is supposed to be already sorted. On the one hand, if it's already sorted then there's no point in calling sorted. But on the other, if it's not sorted then returning a range of indexes is not very useful, as these are indexes into _times, not into intervals.

I recommend picking one possibility or the other: if intervals is supposed to be sorted, then don't sort it (you might assert that it is already sorted); but if not, then translate the returned indexes so that they refer to intervals.
If there is no intersection, find_intersections prints a message. But if the caller is already printing some output, it would be inconvenient (at best) to have this kind of message appear in the middle of the output. Better to leave the printing of messages (or not) up to the caller.
If there is an intersection, find_intersections returns a range of indexes. But if there are no intersection, find_intersections returns None. It is not a good idea to return an exceptional value like this, because it would be easy for the caller to forget to check for the exceptional value, and to write something like this:

result = find_intersection(intervals, new_interval)
print(f"Number of intersections = {len(result)}.")

which would fail with:

TypeError: object of type 'NoneType' has no len()

What they should have written is:

result = find_intersection(intervals, new_interval)
if result is None:
    print("Number of intersections = 0.")
else:
    print(f"Number of intersections = {len(result)}.")

but this is very long-winded. In this case a simple improvement would be to return an empty range of indexes.
If you're going to use NumPy, then you might as well use it wherever possible. So instead of itertools.chain.from_iterable, use numpy.reshape; instead of sorted, use numpy.sort; and so on.

2. Revised code if intervals are unsorted

If intervals is unsorted (as suggested by the call to sorted), then there's no point in sorting it. Sorting costs \$O(n\log n)\$ whereas comparing the query interval with every element of intervals only costs \$O(n)\$.

So in this case we can take advantage of the fact that the open interval \$(a, b)\$ overlaps with the open interval \$(c, d)\$ if and only if \$a < d\$ and \$c < b\$, and write:

def find_intersection(intervals, query):
    """Find intersections between intervals.
    Intervals are open and are represented as pairs (lower bound,
    upper bound).

    Arguments:
    intervals: array_like, shape=(N, 2) -- Array of intervals.
    query: array_like, shape=(2,) -- Interval to query.

    Returns:
    Array of indexes of intervals that overlap with query.

    """
    intervals = np.asarray(intervals)
    lower, upper = query
    return np.argwhere((lower < intervals[:, 1]) & (intervals[:, 0] < upper))

3. Revised code if intervals are sorted

If intervals is already sorted, as suggested by returning indexes into the sorted array, then take advantage of the side argument to numpy.searchsorted and the floor division operator, //:

def find_intersection(intervals, query):
    """Find intersections between intervals.
    Intervals are open and are represented as pairs (lower bound,
    upper bound).

    Arguments:
    intervals: array_like, shape=(N, 2) -- Array of intervals.
    query: array_like, shape=(2,) -- Interval to query.

    Returns:
    Array of indexes of intervals that overlap with query.

    """
    endpoints = np.reshape(intervals, -1)
    lower, upper = query
    i = np.searchsorted(endpoints, lower, side='right')
    j = np.searchsorted(endpoints, upper, side='left')
    return np.arange(i // 2, (j + 1) // 2)


How can I improve my code which dynamically populates a section of a page?

If you don't need the data as JSON, you could just have the server send you the table markup. Then just inject it straight into the page using .load()

Alternatively, if you want JSON data, or can't/won't mess with the server side, you might consider having a hidden, empty table in the markup to begin with, so you don't need to create the entire thing from scratch. Then you can just populate the header cells with the relevant text, and only worry about adding the rows to tbody.

Of course, it'll introduce tighter coupling between the markup and the JS, which you might want to avoid. Since this is a new project that's probably changing all the time, it might be best to simply stick with you current approach of doing everything in JS, to keep things flexible. But my thinking is that since you're basically hardcoding things like the table headers in JavaScript, you're better off hardcoding it the markup where it belongs, rather than generating it.

And you can also make the coupling a little looser, by using some data-* attributes in the "template" table to declare their intended content.

For instance, have this in the page markup

      Name
      Command

Then, on the JS-side, do something like:

var tbody    = $("tbody"),
    template = tbody.children(".template").removeClass(".template").remove(), // removed, but still in memory
    newRow, item;

for(var i = 0, l = deviceArray.commands.length ; i < l ; i++) {
  item   = deviceArray.commands[i];
  newRow = template.clone();
  newRow.children("[data-property]").each(function () {
    var cell = $(this),
        prop = cell.data("property");
    cell.text(item[prop]);
  });
  newRow.appendTo(tbody);
}

That should populate table nicely.

Of course, for such a simple two-column table, it might be overkill. Still, if you need to populate more tables like this, you can create a pretty generic function that you just pass a "scaffold" element like the empty table above plus a data array, and use that anywhere it's needed.


Handling keyboard shortcuts in C# software

Also I may want to implement shortcut customization in the future, and there is no easy way to find out what keys are mapped to which method so it will have to be rewritten.

Stop right here! Extract a class for each command (e.g. instead of a mark_as_fixed method, you'll have a MarkAsFixedCommand class). If you're using WPF you can implement the ICommand interface and have nevermind, you're using WinForms. Still, extract the command classes - WPF's ICommand is a really simple interface that merely exposes bool CanExcute(object) and void Execute(object) methods (you don't have to implement the object parameter if you don't need it) - by extracting your logic into command classes, you can prepare the ground for the day you redo your UI with WPF (which you should!).

  there is no easy way to find out what keys are mapped to which method

Make one! Have your command classes derive from an abstract CommandBase class that exposes a method for it:

public abstract bool IsShortcutKey(Keys keys);

Now every derived command class has to implement this IsShortcutKey method. The implementation for MarkAsFixedCommand could look like this:

public override bool IsShortcutKey(Keys keys)
{
    return keys == (Keys.Control | Keys.Enter)
        || keys == (Keys.Shift | Keys.Enter);
}

A cleaner way would have been to expose some Keys ShortcutKey { get; } property getter, but that wouldn't play nice with multiple shortcuts for the same command.

Anyway now that each command implementation is responsible for is shortcut key logic, you can easily fetch the configuration and make that method return true when keys matches whatever Keys value you have in your config.

Then, whoever runs this ProcessCmdKey method simply needs to know about all available commands - take them as an IEnumerable<CommandBase> constructor parameter and let whoever is calling this constructor deal with providing it with the command instances (which you will acquire with some reflection code).

Now ProcessCmdKey can be as simple as this:

// assume only 1 command returns true for specified keyData value:
var command = _commands.SingleOrDefault(cmd => cmd.IsShortcutKey(keyData));
if (command != null && command.CanExecute())
{
    command.Execute();
    return true;
}

return base.ProcessCmdKey(ref msg, keyData);

PS - Method names should be PascalCase, not lower_snake_case.


English code reads better, since the Python standard library is English.  If you use Dutch, though, please do so consistently.  Don't mix file_input and invoer, or def weave(self, weef_rij).

It's hard to understand what the task to be performed is, and what this code does.  Docstrings and doctests would be a good idea.

It is awkward how you do parts of the parsing all over the place:

strip_file = file_input.strip() and strip_file.split('=') in the main code.  It's especially bad that this snippet is placed before the imports, and before the next line of code (geweefde_rijen = nieuwe_rijen(invoer)).
invoer[i].split() within nieuwe_rijen().
int(coordinaat1[0]), int(coordinaat1[2]) within nieuwe_coordinaten().

It would be better to get the parsing done all at once, into a list of pairs of integers.  Not only would the code be easier to understand, it would also let the program fail earlier if the input is invalid.

I think you have overdone the OOP here.  There is not much point in defining a Coordinaat class, which is basically just a tuple, or CoordinaatRij, which is basically just a list.  All you need for this job is a few functions.

Specifically, it would be useful to take advantage of itertools.izip_longest(), which is the core of what you are trying to do.  Then, to transform the result repeatedly for subsequent rows, use the reduce() function.

from itertools import chain, izip_longest

def coordinaatrijen_parsen(tekenreeks, rij_scheidingsteken='\n'):
    """
    Yield each row of coordinates as a list of (int, int).

    >>> list(coordinaatrijen_parsen('1,2 3,4=  5,6 ', '='))
    [[(1, 2), (3, 4)], [(5, 6)]]
    """
    for rij in tekenreeks.split(rij_scheidingsteken):
        yield [
            tuple(int(c) for c in coord.split(','))
            for coord in rij.split()
        ]

def weven(*rijen):
    """
    Interleave elements from the parameters.

    >>> weven('Geeogn', 'odmre')
    ['G', 'o', 'e', 'd', 'e', 'm', 'o', 'r', 'g', 'e', 'n']
    >>> weven('Gee', 'odmorgen')
    ['G', 'o', 'e', 'd', 'e', 'm', 'o', 'r', 'g', 'e', 'n']
    >>> weven('Gd', 'o', 'eemorgen')
    ['G', 'o', 'e', 'd', 'e', 'm', 'o', 'r', 'g', 'e', 'n']
    """
    return filter(None, chain(*izip_longest(*rijen)))

if __name__ == '__main__':
    with open(...) as f:
        rijen = coordinaatrijen_parsen(f.read(), '=')
    resultaat = [(x + 1, y) for x, y in reduce(weven, rijen, [])]
    for coord in resultaat:
        print '%d, %d' % coord


This review won't help much with your time limit exceeded problem,
but there are some poor practices in your code that I'd like to point out.

The else statement is dead code, and the last else if can be changed to else here:

if (this.Length > other.Length)
    return 1;
else if (this.Length < other.Length)
    return -1;
else if (this.Length == other.Length)
    return this.start < other.start ? 1 : -1;
else
    return 0;

Actually, since all the if-else branches return,
you can simplify to:

if (this.Length > other.Length)
    return 1;
if (this.Length < other.Length)
    return -1;
return this.start < other.start ? 1 : -1;

Method names that start with the word "get" normally return something.
getMinSubInterval is void, and it prints stuff.
So it would be better to rename it accordingly.


You probably want to use timeit module with similar setup:

run.py

from itertools import combinations

def combinations_3(ary):
    l = len(ary)
    for i in xrange(l-2):
        for j in xrange(i+1, l-1):
            for k in xrange(j+1, l):
                yield (ary[i], ary[j], ary[k])

def _test(generator):
    for combination in generator:
        #: To meger time of sequence generation we should ommit IO operations.
        pass

def test_lib(lenght=10000):
    _test(combinations(list(range(1, lenght)), 3))

def test_self_written(lenght=10000):
    _test(combinations_3(list(range(1, lenght))))

test.py

import timeit

#: Print title
print('                library time   self written time')

#: Counter of sequence number.
for i in list(range(10, 100, 10)):
    #: Meger execution time for self written combinations implementation.
    self_written = timeit.Timer(
        #: Tested expression.
        'test_lib({})'.format(i),
        #: Test setup, here we just import tested function.
        'from run import test_self_written as test_lib'
    ).timeit(1000)  #: And here we just set number of testing iterations.

    lib = timeit.Timer(
        'test_lib({})'.format(i),
        'from run import test_lib'
    ).timeit(1000)

    #: Print output in format "<number of elements>: library time, self written time"
    print('{:03} elements: {:10.6f}     {:10.6f}'.format(i, lib, self_written))

And here is my output:

$ python2 test.py
                library time   self written time
010 elements:   0.007060       0.030495
020 elements:   0.058317       0.239376
030 elements:   0.211884       0.817189
040 elements:   0.522477       1.903142
050 elements:   1.047018       3.803112
060 elements:   1.969069       6.590189
070 elements:   2.960615      10.500072
080 elements:   4.468489      15.176092
090 elements:   6.402755      21.669669
$ python3 test.py
                library time   self written time
010 elements:   0.009168       0.038298
020 elements:   0.058049       0.285885
030 elements:   0.208938       1.031432
040 elements:   0.523407       2.450311
050 elements:   1.048463       4.796328
060 elements:   1.828277       7.832434
070 elements:   2.970929      13.067557
080 elements:   4.481792      18.496334
090 elements:   6.353836      26.277946
$ pypy test.py
                library time   self written time
010 elements:   0.011924       0.040272
020 elements:   0.056972       0.046638
030 elements:   0.185858       0.083793
040 elements:   0.456202       0.188640
050 elements:   0.913935       0.338211
060 elements:   1.588666       0.542124
070 elements:   2.537772       0.846942
080 elements:   3.816353       1.232982
090 elements:   5.471375       1.707760

And python versions

$ python2 -V && python3 -V && pypy -V
Python 2.7.6
Python 3.4.3
[PyPy 2.2.1 with GCC 4.8.2]

As you can see, pypy is much faster than cpython implementation.

Actually, if you are using cpython you do not really want to reinvent standard library functions because they are pretty nice optimized by c compiler and you code will be interpreted instead of compiling. In case of pypy you probably want to make some research, because JIT interpreter have a lot of different corner cases.


Feedback
The code makes good use of the jQuery slide functions, as well as basic CSS class addition/removal.
One could utilize event delegation to use a single event listener on a parent container element, along with .is() and tree traversal methods like .parent().
Tips to improve this
Utilize .toggle() and .toggleClass(), along with dynamic function call using a variable (e.g. $(".indented", this)[slideFunction]('100') where slidefunction is a variable containing the function to call) to condense the code.
Also, as mentioned above, use event delegation to register a single click handler. Then check if the target is a child of various elements (e.g. with class indented, with class sub-expander, etc.), and handle actions accordingly.

$(function() {
  // main expansion element
  $(".expander").click(function(event) {
    var target = $(event.target);
    // stop propagation on the link element within .expander class
    if (!target.parent('.indented').length) {
      // sub expansion element
      if (target.parent('.sub-expander').length) {
        var subSelectTextIsMore = $(".more-or-less").text() === "More";
        var slideFunction = subSelectTextIsMore ? 'slideDown' : 'slideUp';

        $(".indented--sub")[slideFunction]('100').toggleClass("show", subSelectTextIsMore);
        $(".sub-caret").toggleClass("reversedCaret", subSelectTextIsMore);
        $(".more-or-less").text(subSelectTextIsMore ? "Show Less" : "More");
      } else { //expander
        var subShown = $("ul > li", this).hasClass("show");
        var slideFunction = subShown ? 'slideUp' : 'slideDown';
        $(".indented", this)[slideFunction]('100').toggleClass("show", !subShown);
        $(".caret", this).toggleClass("reversedCaret", !subShown);
        if (subShown) {
          $(".indented--sub").slideUp('100').removeClass("show");
          $(".sub-caret").removeClass("reversedCaret");
          $(".more-or-less").text("More");
        }
      }
    }
  });
});
.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

        +

More


Logging using function as decorator in Guava

The concept seems fine to me. The problem is that you will still need to decide whether to decorate, or not decorate the function, and that is done outside the function. That makes it a once-per-create decision, which is OK, but you may still end up with a lot of conditions in your code:

Function f = logFunction() ? new DecoratorLoggerInfoFunc(f) : f;

The actual apply method is not very robust though. I would include logging of any potential exceptions that are not declared to be thrown on the function itself...:

public O apply(I input) {
    try {
        O output = function.apply(input);
        logger.info("Input is {} Output is {}", input, output);
        return output;
    } catch (RuntimeException e) {
        logger.warn("Exception running with input {}", input, e);
        throw e;
    }
}


JavaScript: Simulating the process of removing multiple videos at once from a YouTube playlist

for (var i = playlistIndex.length - 1; i >= 0; i--)

Instead of having it negatively looping, which in this instance is unnecessary, do it positively:

for (var i = 0, length = playlistIndex.length; i < length; i++){

Instead of the negatively recurring for loop, consider using a length subtraction operation instead like in the example below:

for (var j = bin.length -1; j >= 0; j--) {
    if (bin[j].length === 0) {
        bin.splice(j, 1);
    }
}

into:

for (var i = 0, length = bin.length; i <= length; i++){
    bin.splice(length - 1 - i, 1);
}

For this example, a negative iteration is the way to go, because otherwise as @Tibos pointed out in the comments below, the array indexes can get messed up and end up leaving them in.

For example, if b were ['a', 'b', 'c'], a normal for loop here with bin.splice(i, 1) would leave 'b'.

bin.unshift with the a negative for loop is the same as bin.push with a positive for loop.

Positive for loops are always preferred when possible.

for (var i = playlistIndex.length - 1; i >= 0; i--) {
    bin.unshift(playlist.splice(playlistIndex[i], 1));
}

into:

for (var i = 0, length = playlistIndex.length; i < length; i++){
    bin.push(playlist.splice(playlistIndex[i], 1));
}

You should have whitespace between your operators:

playlist.length+" video(s) remain in the playlist: "+playlist.join(", ")+"."

into:

playlist.length + " video(s) remain in the playlist: " + playlist.join(", ") + "."

The following block can be converted to a ternary statement:

if (playlist.length === 0) {
    alert("No videos in the playlist.");
}
else {
    alert(playlist.length+" video(s) remain in the playlist: "+playlist.join(", ")+".");
}

into:

alert(playlist.length === 0
    ? "No videos in the playlist"
    : playlist.length + " video(s) remain in the playlist: " + playlist.join(", ") + "."
);

bin = [].concat.apply([], bin): this seems unnecessary; I wouldn't bother doing it.

I thought this was unnecessary, but I was wrong! as you receive arrays from splice, it was necessary to transform it into an singular array, instead of a 2d array.

Instead of that, attach [0] to the end of your bin.push(playlist.splice(playlistIndex[i], 1)), so it would look like:

bin.push(playlist.splice(playlistIndex[i], 1)[0]);

This works because you only splice a single value from the array, but if you were to splice more, you would need to use that concat statement!

Again with the whitespace:

alert(bin.length+" video(s) have been removed: "+bin.join(", ")+".");

into:

alert(bin.length + " video(s) have been removed: " + bin.join(", ") + ".");

  Practically speaking, videos to be removed, and by extension, their corresponding indexes in an array should not be predetermined, but rather be selected by the user. In other words, the playlistIndex array should be empty at first, and index numbers should be added to it one by one as the user ticks checkboxes.

Look at this page(It's w3schools, I couldn't find a MDN post on it, sorry) on HTML checkboxes, this may be exactly what you're looking for.

Then, you can iterate over the array of checkboxes and add the indexes of the ones  that are checked.

  Even after I have ironed out the first problem mentioned above, the current code will remove a selected video immediately after one index number is pushed to the playlistIndex array. So I have to make it so that the code does not start to remove videos until the user has selected every video they want to have removed.

Simply move this to a function! Then attach the function to a submit button on your <form>. It will only get called after the form has been submitted, rather than on addition.

  Lastly, before setting the removal process in motion, the code needs to have the user confirm their decision. Ideally, the user should be asked to press "yes" or "no" in a pop-up that goes something like "You are about to remove 7 videos. Are you sure you want to proceed?"

Use confirm(), it lets you ask a user a question and return a boolean response.

For example:

if (!confirm('Are you sure you want to delete these videos?')){
    return;
}
// do deleting here.

Note the reverse condition allows you to get away from an extra layer of conditional over your entire post.


Window-size-dependent content toggler for an HTML form

What you could do is define in the markup the following:

A data attribute for option to indicate it's a toggle.
A data attribute for radios to indicate it's a toggle.
A data attribute for option to indicate the content it corresponds.
A data attrubute for radios to indicate the content it corresponds.

The data attributes could be selectors or any attribute you can use to target the content.

This way, your script can pick up these elements by class, get their data attribute, and toggle their corresponding contents. This is essentially how Bootstrap allows you to define modals, accordions and such without ever writing scripts. They just look for certain selectors, pick up data, and find the target selectors.

Here's a sample of how the markup would look like:

<select data-component="select-toggle">
  <option value="foo" data-content="#foo">foo</option>
  <option value="bar" data-content="#bar">bar</option>
  <option value="baz" data-content="#baz">baz</option>
</select>

<input type="radio" value="foo" data-component="radio-toggle" data-content="#foo" >
<input type="radio" value="bar" data-component="radio-toggle" data-content="#bar" >
<input type="radio" value="baz" data-component="radio-toggle" data-content="#baz" >

foo

bar

baz

And the script will look like the following. My jQuery is fuzzy at best, but you get the idea:

$('[data-component="select-toggle"]').on('change', function(){
  var contentSelector = $('option:selected', this).data('content');
  $(contentSelector).show().siblings().hide();
});

$('[data-component="radio-toggle"]').on('change', function(){
  var contentSelector = $(this).data('content');
  $(contentSelector).show().siblings().hide();
});


In addition to the other answers, there are a couple common bubble sort optimizations that you can employ.

First, your inner loop steps through the entire array each time. This is unnecessary because each pass through the array is guaranteed to sink the largest value to the bottom, so the tail of the array is always sorted. You can avoid processing the sorted bits of the array by using

for (int j = 0; j < lengthOfInputArray - (i + 1); j++) {
    ...
}

for the inner loop.

Second, you can shortcut processing by ending when the inner loop encounters no swaps.

public static void bubbleSort(int[] arr) {
    boolean swapped = false;

    for (int i = 0; i < arr.length; i++) {
        swapped = false;
        for (int j = 0; j < arr.length - (i + 1); j++) {
            if (arr[j] > arr[j + 1]) {
                if (swap(arr, j, j + 1)) {
                    swapped = true;
                }
            }
        }
        if (!swapped) {
            break;
        }
    }
}

This only happens when the array is fully sorted. So if you start out with a sorted array, then you only have to run through the array once.

Third, the outer loop does not have to be processed once for each element in the array. Take a five element array for example. It is iterated in the following manner:

value of i      max j required
----------      --------------
    0                 3
    1                 2
    2                 1
    3                 0

So the outer loop only needs to be processed arr.length - 1 times. The final optimized bubble sort would look something like this:

public static void bubbleSort(int[] arr) {
    boolean swapped = false;

    for (int i = 0; i < arr.length - 1; i++) {
        swapped = false;
        for (int j = 0; j < arr.length - (i + 1); j++) {
            if (arr[j] > arr[j + 1]) {
                if (swap(arr, j, j + 1)) {
                    swapped = true;
                }
            }
        }
        if (!swapped) {
            break;
        }
    }
}


Computing hash with Python built-in

    pow(self.a, self_size - 1, self.mod)

is much faster than ** and % done separately.
I don't see the reason of passing string argument to update_ax. Passing 1 and -1 directly is much cleaner and likely faster:

def update_ax(self, up_down):
    self.size_x += up_down
    self.ax = self.h(....)

Finding a prime is indeed unconventional. I recommend to run a standard sieve (Chebyshov' theorem aka Bertrand postulate guarantees a prime in [n, 2n] range).


Shell programs should start with a shebang, so that when executed, the OS can select the correct interpreter:

#!/bin/bash

With Bash, we can read prompted input using read -p:

read -p "Enter the mininum number of stars: " min

We should check that we have a valid positive integer before using $min.

The same comments also apply to $max.  For both variables, consider accepting arguments instead of prompting for interactive input.

Prefer printf to echo -n - that's a good practice for portable scripting.

Most of those for loops can be eliminated with suitable printf formatting.  We can produce n stars with printf '%.${n}s' '' | tr ' ' '*', and we can put that into a space that's m wide, with printf '%${m}s' "$(printf '%.$ns' '' | tr ' ' '*')".  If we did keep the loops, we don't need $ for variable expansion within the arithmetic context (( )).

It seems strange to use arithmetic evaluation but also to invoke expr to increment $sum - it's more consistent to simply write ((++sum)).

The echo command with a single empty argument is equivalent to echo with no arguments, so no need to write "" there.


If you use ArrayList instead of int[] you can write rotate2 like this (it's less efficient):

  public static List<Integer> rotate2(List<Integer> numsList, int k) {
    k = k % numsList.size();
    List<Integer> firstPart = numsList.subList(0, numsList.size() - k);
    List<Integer> secondPart = numsList.subList(numsList.size() - k, numsList.size());
    Collections.reverse(firstPart);
    Collections.reverse(secondPart);

    ArrayList<Integer> rotated = new ArrayList<>();
    rotated.addAll(firstPart);
    rotated.addAll(secondPart);

    return rotated;
  }

The arrayRotate1 can also be written this way, I don't know whether it's more readable or not but it's definitely less efficient:

  public static void rotate(int[] nums, int k) {
    k = k % nums.length;
    Queue<Integer> queue = new ArrayDeque<>(k);
    for (int i = 0; i < Math.min(k, nums.length); i++) queue.add(nums[i]);
    for (int i = 0; i < nums.length; i++) {
      int index = (i + k) % nums.length;
      queue.add(nums[index]);
      nums[index] = queue.remove();
    }
  }


If I understand correctly, you're looking for the Cartesian product of the attributes in each attribute category.

To get the Cartesian product, I've adapted* Eric Lippert's solution from his blog post Computing a Cartesian product with LINQ.

let cartesianProduct xs =
    Seq.fold (fun acc xs -> seq {
        for accSeq in acc do
        for x in xs do
        yield Seq.append accSeq (Seq.singleton x)
    }) (Seq.singleton Seq.empty) xs

Then we need to group by the attribute category, and pull out just the attributes**.

let variants (attributes : seq<NewProductAttributeInfo>) =
    attributes
        |> Seq.groupBy (fun attribute -> attribute.AttributeCategoryId)
        |> Seq.map (snd >> Seq.map (fun attribute -> attribute.AttributeId))
        |> cartesianProduct

Here is a test on the sample data you provided

let attributes = [
    { AttributeId = "red"; AttributeCategoryId = "Color" };
    { AttributeId = "L"; AttributeCategoryId = "Size" };
    { AttributeId = "XL"; AttributeCategoryId = "Size" };
    { AttributeId = "Cotton"; AttributeCategoryId = "Material" };
    { AttributeId = "green"; AttributeCategoryId = "Color" };
    { AttributeId = "Polyester"; AttributeCategoryId = "Material" }
]

for variant in variants attributes do
    printfn "%A" variant

Which gives:

seq ["red"; "L"; "Cotton"]
seq ["red"; "L"; "Polyester"]
seq ["red"; "XL"; "Cotton"]
seq ["red"; "XL"; "Polyester"]
seq ["green"; "L"; "Cotton"]
seq ["green"; "L"; "Polyester"]
seq ["green"; "XL"; "Cotton"]
seq ["green"; "XL"; "Polyester"]

* Hopefully without introducing errors.

**
This is a little bit nicer in C# since we have the overload of GroupBy that takes an elementSelector parameter:

return attributes.GroupBy(attribute => attribute.CategoryId, attribute => attribute.Id)
    .CartesianProduct();


Tagging the directories and switching between them by tags - follow-up (Part 2/2: business logic)

Some suggestions:

Use More Quotes™

$@ should be double quoted to pass the parameters without word splitting.
Any variable use should be quoted. It is very rare that word splitting is actually what you want, and it causes sometimes very subtle bugs.
Command substitution should be quoted.

Use good bashisms such as [[ instead of [.
Local variables should be lowercase to distinguish them from system variables, which are uppercase.
There is no need for semicolons in Bash scripts. This may be more contentious, but I generally write like this:

if [[ "$variable" = 'value' ]]
then
    …

Apropos: == to compare strings is a bit of a historical accident. The original operator is just =, but == is probably not going away.
$(pwd) can be simplified to . - it also means the current directory.
The home directory should not be used for temporary file storage (unless that is actually your configured temporary directory). In general you should use something like working_dir="$(mktemp --directory)" (or -d if you don't have GNU coreutils mktemp). This has a few advantages:

It means your home directory isn't going to fill up with temporary files which are never cleaned up (but more about that below).
It is often a memory mapped filesystem, so it may be much faster than your home directory.

Long if/elif sections testing the value of a single variable can usually be easier written as a case block.
head does not fail if run on an empty file:

$ touch foo
$ head foo
$ echo $?
0

So your first test could fail for the wrong reason. You might want to [[ -s "$path" ]] to check if a file is empty.
The file name "dt_tmp" doesn't tell me anything about what it contains or what it's used for - in general I find that adding the project name to anything within the project is redundant, and marking something as temporary is not particularly helpful to know what it is, unless it really can contain anything. Is there a better name you can give it? It looks like it's some sort of command queue, maybe?


Splitting canvas app into separate functions

From a Code Review perspective, what you are asking for, is worse.

Currently, you only need to call canvasApp() and that function does all the work. Inside you have drawScreen which is periodically called, starting in gameLoop.

Still,

I would put all the var statements on top for readability
I would put var in front of context and theCanvas (!)
I would assign your colors ('#EEEEEE') to meaningfully named variables
I would assign Math.PI*2 to a var doublePi = Math.PI*2 for speed
I would consider dropping the curly braces from the guard clause
//Box is not really a meaningful naming, //border and //background would make more sense`

That would give this:

function canvasApp() {

    if (!canvasSupport())
      return;

    var canvas = document.getElementById('canvasOne'),
        context = canvas.getContext('2d'),
        borderColor = '#EEEEEE',
        backgroundColor = '#000000',
        ballColor = '#000000',
        speed = 5,
        y = 10,
        x = 250,
        doublePi = Math.PI*2,
        ballSize = 15,
        refreshInterval = 20; //In milliseconds

    function  drawScreen () {
        //Background + Border
        context.fillStyle = borderColor;
        context.fillRect(0, 0, canvas.width, canvas.height);
        //Background
        context.strokeStyle = backgroundColor;
        context.strokeRect(1,  1, canvas.width-2, canvas.height-2);
        // Create ball
        y += speed;
        context.fillStyle = ballColor;
        context.beginPath();
        context.arc(x,y,ballSize,0,doublePi,true);
        context.closePath();
        context.fill();
    }

    function gameLoop() {
        window.setTimeout(gameLoop, refreshInterval);
        drawScreen();
    }

    gameLoop();
}

I am still not too excited by redrawing every 20 milliseconds 2 large boxes, but I will leave the research on further optimization to you.

Update: after playing the code and reading it more closely, the code only redraws a square once, and then the border, so that should be fine.

A working jsbin version is here: the animation is fast enough, though disappointing as there is no bouncing..
http://jsbin.com/lidil/2


Good:

no warnings with -Wall -Wextra -pedantic with both gcc and clang, no
memory leaks found with valgrind.

Bad:

use prototypes instead of declarations to give compiler a chance
to issue warnings when an incorrect number of parameters is passed or incorrect types are passed:

void play(void)
int main(void)

You don't check if user passes correct acceptable difficulty level:

$ ./main
1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE
What level would you like to play: 6
Floating point exception
$ ./main
1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE
What level would you like to play: 0
Floating point exception

You don't check if user passes an integer in the first place:

$ ./main
1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE
What level would you like to play: a

will make your program go into an endless loop.

Suggested:

convert int difficulty = 1 into an en enum with additional DIFFICULTY_MAX and DIFFICULTY_MIN values, and check if value passed from the user is lower than DIFFICULTY_MAX and larger or equal to DIFFICULTY_MIN.

Use EXIT_SUCCESS to denote success at the end of main():

return EXIT_SUCCESS;

or just omit the return from main() - compiler will automatically return a success value if we run off the end.


Here are my thoughts:

letfn instead of let

You could use letfn instead of let, which would be a little more concise:

(letfn [(update-or-add [m1 k f arg]
          ...

conj vs. update-in

conj and update-in are very similar functions in that they both take a map and "update" the value for a key that may or may not exist. Because of this, they are sometimes exchangeable. update-in is fine here, but I think using conj for both scenarios could make it easier to see at a glance what your function is doing. (See the next example.)

if-let

The (let [x (get m1 k)] (if (nil? x) ... part of your code is a good example of where if-let comes in handy.

(if-let [x (m1 k)]
  (conj m1 {k (f x arg)})
  (conj m1 {k arg}))

Which you could even simplify further by moving the if-let inside of a single conj function call:

(conj m1 {k (if-let [x (m1 k)] (f x arg) arg)})

As an aside, I tend to prefer assoc, although it's really just as good as conj:

(assoc m1 k (if-let [x (m1 k)] (f x arg) arg))

Reducers work best as functions taking 2 arguments

The first thing I noticed about your loop is that its arguments can be simplified:

(loop [m1 m, ms ms]
  ...

Essentially what you're doing is starting with m1 and reducing update-or-add over each key-value pair in each map in ms. The tricky thing here is that, as you pointed out, this is a nested reducing operation, in that each map in ms can have multiple key-value entries. You have the right general idea in that you have a reduce within a loop, but a better/simpler way to do this would be to make your update-or-add function take the two arguments that a reducing function expects -- an accumulator and the next item in the collection being reduced over. Once you have update-or-add working that way, you can do the same thing with your loop and at that point you'll be able to represent your solution as a simple nested reduce.

Let's start with update-or-add. This function takes a working "map in progress" and a key-value pair and either adds it to the map if that key isn't already there, or it updates the value to be the result of calling f with the value already there and the new value as arguments. Note that we don't need to make f an argument because it's already available within the context of the entire function merge-with2. You can also use destructuring to easily access the key and the value of the key-value pair.

(letfn [(update-or-add [m1 [k v]]
          (assoc m1 k (if-let [x (m1 k)]
                        (f x v)
                        v)))]
  ...

Now you can use update-or-add "as-is" within a reduce.

You can do something similar with your main loop. To simplify things, let's make it its own function, and call it something like merge-with-one. This function will take one of the maps supplied to merge-with2 and reduce update-or-add over its key-value pairs. Defining this function is actually super easy, because it's just a call to reduce. So, here is my suggested refactoring of your code:

(fn merge-with2 [f m & ms]
  (letfn [(update-or-add [m1 [k v]]
            (assoc m1 k (if-let [x (m1 k)]
                          (f x v)
                          v)))
          (merge-with-one [m1 m2]
            (reduce update-or-add m1 m2))]
    (reduce merge-with-one m ms)))

It turns out that this is actually pretty close to the actual implementation of merge-with in clojure.core.


I'm not a fan of the two-step initialization idiom but I've resigned myself to use it if the native object has a lot of configuration options followed by a rather complex and error-prone initialization.
The real issue is that I still have some constructors that throw exceptions after native resources have been allocated, though I'm able to avoid it in most cases.

That's a suspicious set of problems to have; too bad you didn't ask for a review of that code.  Off the top of my head, however, I've generally found that "a lot of configuration options" can usually be managed by a builder, and that trivial constructors seldom throw -- dependency injection pushes the exception risk outside of the constructor, where you can usually manage things more easily.
@Override
public void close()

If you aren't intending to let people create sub classes that circumvent the state machine, you might make these methods final.
protected abstract T allocate();
protected abstract void release(final T resource);

These methods don't belong here.  The rest of your class is about lifecycle management; these are about resource management.  You've mixed the concern about coordinating the life cycle with your concern for creation.
interface ResourceFactory<T> {
    void T allocate();
    void release(T resource);
}

Then, in your lifecycle management, defer the work to the factory.
@Override
public void close()
{
    if (this.refState.getAndSet(State.DISPOSED) == State.ALLOCATED)
        this.factory.release(this.resource);
}

10 out of 10 for making the state machine explicit.  I suspect that you should make State.ALLOCATING and State.DISPOSING explicit.  You might also want to look into Stateless4j; trivial state machines often grow in complexity.


Implementation of ApplySort method from IBindingList

The ApplySortCore() method could be made more dry

protected virtual void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
{
    this.SortProperty = property;
    this.SortDirection = direction;

    IEnumerable<T> items = null;
    if (direction == ListSortDirection.Ascending)
    {
        items = this.OrderBy(item => property.GetValue(item));
    }
    else
    {
        items = this.OrderByDescending(item => property.GetValue(item));
    }

    ResetItems(items.ToList ());

    IsSorted = true;
    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, property));
}

You should always try to code against interfaces instead of a concrete implementation.

In the ResetItems() method you should either use an IList<TItem> or better an IEnumerable<TItem> for the input parameter.

The call to this IndexOf() method seems a little bit strange. You already have the items sorted why don't you just add the items one by one ?

Because the methods are inherited from Collection<T> we can use the Add() method which simplifies the ResetItems() method to

private void ResetItems(IEnumerbale<TItem> items)
{
    base.ClearItems();

    foreach (var item in items)
    {
        base.Add(item);
    }
}


Reusable user control (ascx) design for multiple web application

Is there any better elegent ways to solve my problem?

You are going down a horrible path messing with all these user controls.  ASP.NET MVC is much better for dealing with reusable visual parts, and everything happens on the request level so you don't have to worry about horrible event ordering.

Can't use MVC?  Forget the complex events of user controls entirely.  Put no code in user controls.  If you need the data from a textbox in a control for example, pull it directly from the post variables (wrap this in a class if you need to)

Make your goal to deal with requests in a SINGLE, centralized point.  It's the MVC way, it's the MVP way, it's the MVVM way.

Need ajax?  scrap ajax controls and hit a web service;  throw away the ajax toolkit.

I actually wish I had an old crufty webforms app that I could re-work this on.  I would completely bail on the failure that is asp.net lifecycle


Couple of remarks:

IsSent() smells like a property, not a method. It should be more descriptive as well: what  object are you calling this on? It seems to indicate Email.IsSent but that's not what you do: your description makes it sound more like EmailManager.IsDailyEmailSent.
Dispose your SmtpClient instance.
Don't set isEmailSend to true before you actually send the email. You're already synchronizing using the monitor so that's not a reason. Set isEmailSent (notice the t instead of d to indicate past tense) to false from the get-go and set it to true after the sending inside the try block. Now you won't have to repeat the isEmailSent = false anymore either.
Don't rethrow exceptions like that, you're going to lose the stacktrace. If all you do is rethrow it without logging or handling then you might as well not catch it in the first place.


The for loop can be replaced with a lapply statement.
Using base R functions, your read_season_range example is equivalent to the following one-liner:

sixties <- do.call(rbind, lapply(1960:1969, read_season))

or to wrap it in a function:

read_season_range <- function(year_range) {
  do.call(rbind, lapply(year_range, read_season))
}


ListView MultiSelect, MVVM and RoutedCommands

Your approach looks fine to me. Except i would probably use prefix-casting, to get cast exceptions straigt away if something goes wrong, instead of using as.

This can be achieved without modifying code-behind tho. You can bind container's IsSelected property to appropriate item's viewmodel property.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem" >
        <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
    </Style>
</ListView.ItemContainerStyle>

Then you can access selected items in your viewmodel by using:

protected IEnumerable<Item> SelectedItems { get { return Items.Where(x => x.IsSelected); } }


This code is just begging for a Java8 implementation.... and, given that Java 8 has been available for almost a year, it seems reasonable.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Head {

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            throw new IllegalArgumentException();
        }

        Files.lines(Paths.get(args[0])).limit(10).forEach(System.out::println);
    }

}


As someone who's been writing cross-platform tools on .Net Core, this doesn't do what I expect it to do.

finder.TargetDirectories.Add("/src");

I expect that to target a directory named src at the root of the file system. On Linux: /src; on windows C:\src. It would be more clear if the user passed in a relative file path or a complete file path.

Also, please don't concatenate file paths this way.

$"{path}/{new DirectoryInfo(subDir).Name}"

This is terribly error prone. It's hard to get right the first time and it's even harder to refactor later. Always use System.IO.Path.Combine().


Well, first of all you should probably declare variables closer to usage. Not only this will compress your code a bit, it will also save you the trouble of assigning random things to them. For example int current = 0 declaration can be omitted.

You normally want to use != operator when dealing with iterators, so that you can switch containers, implementations, etc; and you'd generally want to increase the iterator without making an extra copy of same. So for example the following

for( i = roman.begin(); i < roman.end(); i++ )
    digits.push( get_roman_value(*i) );

is better written as

for( i = begin(roman); i != end(roman); ++i )
    digits.push( get_roman_value(*i) );

also, there are some obscure reasons to write begin(container) and end(container) instead of invoking member functions, but most would say it's a matter of taste.

Depending on how serious your are, you shouldn't throw strings, instead throw something that derives from exception, which is a part of STL which lives in "<exception>" header.

Then there's some redundancy in your switch, for example

case 'i': return    1; break;

the break statement is not necessary, and most programmers are very familiar with case -> return pattern. Ultimately it's a matter of taste, I guess.

EDIT Answer to comment

I would prefer to remove the declaration of int current = 0, and instead use:

// get the current digit
int current = digits.top();
digits.pop();

Although I personally like your use of comma operator, most people emphatically do not; and encourage to separate statements on separate lines.

I also noticed you are a bit inconsistent with spaces, it's advisable to always have same rules everywhere. For example there are places where you surround the assignment operator with spaces, and then there are cases when you don't.


PHP - Deleting Directory Contents & SubDirectory Contents

function empty_dir($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
                                              RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $path) {
      if ($path->isDir()) {
         rmdir($path->__toString());
      } else {
         unlink($path->__toString());
      }
    }
    rmdir($dir);
}

from: http://php.net/manual/en/class.recursivedirectoryiterator.php


Earliest time frog can jump to the other side of a river in C#

Readability

The code needs more spacing. Considering the comments, the indentation and the ifs, it's hard to read without some good old empty lines.

Use brackets when using conditions, especially if you have comments above your single line, it gets really confusing. Also, the readability is increased and, the biggest factor, you'll avoid weird bugs.

If you really don't want to use brackets, at least indent your comments so it's clear the line under it is still into the if.

Considering that we have your explanation of the problem, we can understand pretty clearly what your variable names mean. But still... it could be improved or at least well documented. fallenLeaves doesn't represent fallen leaves, it represent when leaves are falling at which position. expectedSum and correctSum don't mean much, to a point I'm wondering if they are well initialized.

Result for now :

public static int GetSecondsRequired(int requiredAmountOfLeaves, int[] fallenLeaves)
{
    bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];
    int espectedSum = 0, correctSum = 0;

    for (int i = 1; i <= fallenLeaves.Length; i++)
    {
        if (i <= requiredAmountOfLeaves)
        {
            //get summatory of 1..N
            correctSum += i;
        }

        if (fallenLeaves[i - 1] <= requiredAmountOfLeaves &&
            !leavesAsSteps[fallenLeaves[i - 1]])
        {
            //accumulate where the expected leaf fell and set its location to true
            espectedSum += fallenLeaves[i - 1];
            leavesAsSteps[fallenLeaves[i - 1]] = true;
        }

        if (espectedSum == correctSum && i >= requiredAmountOfLeaves)
        {
            //if all the espected leaves fell, then return the array's
            //index where the last expected leaf was found
            return i - 1;
        }
    }

    return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;
}

Algorithm

You use i - 1 everywhere but one place, it would be smarter to reverse this. Use i everywhere and i + 1 at one place.
You use the accessor fallenLeaves[i] often, you should consider storing it in a variable. It will make the code more readable. So : int currentFallenLeaf = fallenLeaves[i];
The usage of expectedSum and correctSum is too complicated for the problem at hand. You don't need to check the sum, only that the number of true elements in leavesAsSteps (minus one because of the zero index) equals requiredAmountOfLeaves.
You could check right at the beginning of the loop if you already marked the "leaf step" as true and that the leaf is valid, so that you don't do useless work.

public static int GetSecondsRequired(int requiredAmountOfLeaves, int[] fallenLeaves)
{
    // You should comment why there's a + 1 here.
    bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];
    int numberOfFallenLeaves = 0;

    for (int i = 0; i < fallenLeaves.Length; i++)
    {
        int currentFallenLeaf = fallenLeaves[i];

        // Have we already checked this number?
        // Is the leaf number out of range?
        // If so, let's just stop right there for this leaf.
        if (currentFallenLeaf > requiredAmountOfLeaves
            || leavesAsSteps[currentFallenLeaf])
        {
            continue;
        }

        numberOfFallenLeaves++;
        leavesAsSteps[currentFallenLeaf] = true;

        // Have we marked all our leaves? We're done.
        if (numberOfFallenLeaves == requiredAmountOfLeaves)
        {
            return i;
        }
    }

    return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;
}


I don't think that reading in entire files into memory, File.foreach(@filename).map { }.each.map { }.each { }, is going to be memory efficient. Which appears to be what would happen with AccessConsoleWriter.new(parser).call.

What you probably want to do is operate on one line at a time. For instance, you might be able to rewrite FileParser.endpoints to look like:

def endpoints(&block)
  File.foreach(@endpoints) do |line|
    block.call(line)
  end
end

A few other notes:

I don't see a lot of state being stored, so instantiating classes seems unnecessary.
For multi-line blocks, use do ... end instead of { ... }. https://github.com/bbatsov/ruby-style-guide#syntax
each in each.map is redundant.
each.map maps the returns of a block to a new array, but you seem to be ignoring that returned array in some places. In which case, using just each would be fine.
#call is a little confusing, as that's a method on Proc and others.
"...premature optimization is the root of all evil (or at least most of it) in programming."


Simple C++ Dynamicly allocated Matrix with only one memory allocation

Since you have the new keyword, you should make a destructor and delete[].

~Matrix()
{
    delete[] data;
    data = nullptr;
}

Note that it is not necessary to set data = nullptr in the destructor, because it will be deleted as soon as the destructor is called.

You are missing a copy constructor which can cause problems when assigning one matrix to another

What happens if the number passed in [] when slicing from the matrix is out of bounds?

Have a glance at std::initialzer_list in C++, it will simplify assigning values to the matrix.

You will have to overload the arithmetic operators ( +, -, *, /) if you want to perform any kind of operations between two matrices

Lastly, I was a little confused to see size_t rather than std::size_t, if you have using std::size_t in your source code, you should have it here too to avoid confusion.


Get Image From Stream, TCP Stream without converting to MemoryStream first

my though is like this, though i didn't really test it

You must keep the stream open for the lifetime of the Image.  because the Image.FromStream  wont read the data until it needs it, for performance purpose;
you must make sure the all the data for that image is received before you call Image.FromStream. TCP could split your data into multiple packages when transfer.  since you transfer 4 bytes as the length of that image, you can read the length first, then you can keep checking the length of that NetworkStream, but do not read any data.  or you can peek the data but make sure the data is still in the stream;
the last condition, do not transfer more data after the image until you are done with the image. otherwise, the data after the image could be treated as the image data.  if it is hard for your current application's protocol, you might just use a separated tcp connection for image data only.

Update:

Or I think you can derived a class from System.Stream and override the Read method and some other methods as well.  Now you can manage how you read the data.  This way, you can even work on just the same TCp connection because you know the length.   Just pass that derived Stream to the Image.FromStream, that should/might work.


Naming

Keep your #define constant names consistent. You specify that LED_RED, LED_GRN, and LED_BLU are LEDs, but you don't specify what B1 is. A better name would be BTN_B1.

Bracing

Keep your bracing consistent. Stick to one indentation style. For example in your code, you have both

if(...){
        ...
        }

and also

if (...)
    {
    ...
    }

Delay Variable

Use the const keyword if you're not going to be changing delay.

Main Args

If you're not going to be using int argc, char **argv, then they don't need to be there.

Use Functions

The first 7 lines of main are setting up the GPIO pins, you should put that into a setup() function.

Make good use of whitespace

The long block of statements inside the if(bcm2835_gpio_eds(B1)!=0) would be better off separated by some spaces, to make it more readable.

Resulting Code

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <bcm2835.h>

#define LED_RED RPI_GPIO_P1_12 //GPIO 18
#define LED_GRN RPI_GPIO_P1_16 //GPIO 23
#define LED_BLU RPI_GPIO_P1_18 //GPIO 24
#define BTN_B1 RPI_GPIO_P1_22 //GPIO 25

void setup_gpio(void);

int main()
{
    if (!bcm2835_init()) return 1;
    setup_gpio();

    unsigned int delay = 1000;
    while (1) {
        printf("Light cycle machine\n");

        if (bcm2835_gpio_eds(BTN_B1)!=0) {
            printf("Button Pressed!!!\n\n");

            bcm2835_gpio_set(LED_RED);
            printf("Red LED on!!!\n");
            bcm2835_delay(delay);
            bcm2835_gpio_clr(LED_RED);
            printf("Red LED off!!!\n");

            bcm2835_gpio_set(LED_GRN);
            printf("Green LED on!!!\n");
            bcm2835_delay(delay);
            bcm2835_gpio_clr(LED_GRN);
            printf("Green LED off!!!\n");

            bcm2835_gpio_set(LED_BLU);
            printf("Blue LED on!!!\n");
            bcm2835_delay(delay);
            bcm2835_gpio_clr(LED_BLU);
            printf("Blue LED off!!!\n");

            delay(delay);
            bcm2835_gpio_set_eds(BTN_B1);
            printf("\nSystem Idle\n");
            }
        else {
            delay(delay);
            //printf("Done!\n");
            }
        }

    return 0;
}

void setup_gpio()
{
    bcm2835_gpio_fsel(LED_RED, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(LED_GRN, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(LED_BLU, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(BTN_B1, BCM2835_GPIO_FSEL_INPT);

    bcm2835_gpio_set_pud(BTN_B1, BCM2835_GPIO_PUD_UP);
    bcm2835_gpio_len(BTN_B1);
}

As for your question, you say you want to kill the loop but not break out of it. I'm not exactly sure what you mean. But, perhaps you're looking for interrupts?


Once you've gotten your code into a ILookup you can just call Item property (which in C# is called with [...]) to get all values with a given key. So the Check can be entirely replaced by using the ILookup like this:

ILookup<int, string> plansLookup = ...
IEnumerable<string> plansForProvider = plansLookup[providerId]; // Finds all plans for this provider

However, it's not clear that you need to be creating the List<Tuple<int, string>> in the first place. You can just use Linq to generate your ILookup from scratch:

var plansLookup =
    (from plan in plans
     let productSummary = plan as OwnedProductSummary
     let serviceSummary = plan as OwnedServiceSummary
     let offeringDetail =
         (productSummary != null) ? _offeringBLL.GetById(productSummary.OfferingID) :
         (serviceSummary != null) ? _offeringBLL.GetById(serviceSummary.OfferingID) :
         new OfferingDetail()
     select new
     {
         offeringDetail.ProviderID,
         plan.Name
     })
    .ToLookup(x => x.ProviderId, x => x.Name);