A simple C WinAPI program for terminating processes via process image names - follow-up

Regarding:
size_t totalProcessesMatched = 0;
size_t totalProcessesTerminated = 0;
...
printf("Info: total matching processes: %d, total terminated: %d.\n",
       totalProcessesMatched,
       totalProcessesTerminated);

the printf() is trying to output a int, but the variables to output are size_t which should be output using a %zu format specifier.
If you compiler is not telling you about these kinds of problems, then enable the warnings until it does.
regarding;
fprintf(stderr, "processkiller.exe PROCESS_NAME");

This would be 1) left in the stderr output stream because the format string does not have a \n on the end of it.  2) any program can be executed via any name so hard coding the name is a bad idea.  Suggest:
fprintf(stderr, "%s PROCESS_NAME\n", argv[0] );

regarding:
fputs("Error: could not get the process snapshot.", stderr);

strongly suggest making use of the get_last_error() facility and printing the actual error text to stderr rather than some 'random' error message
regarding;
if (strcmp(entry.szExeFile, argv[1]) == 0) {

this does not compile because the statement:
#include <string.h>

is missing.


Naming

While it's usually not a big deal to have names like d and d' flying around, seeing d''' made me wonder: is there no better name for that?

Indentation

data Action
  = Add Int
        Int
  | Check Int
          Int
  deriving (Show, Read)

That seems.. unusal. Why is the second Int on a new line? Nice of you to seperate the constructors to their own lines, though.

data Action
    = Add Int Int
    | Check Int Int
    deriving (Show, Read)

Handling errors

You've said your error handling is atrocious. I wouldn't really call it that, because it simply does not exist. You never take any action on Nothing, which means the repl will stop as soon as something bad happens.

The glaring problem: The rat's tail

repl :: DisjointSet Int -> IO ()
repl d = do
  line <- getLine
  case (Read.readMaybe line) of
    Just action ->
      case action of
        Add k1 k2 ->
          case (merge k1 k2 d) of
            Just d' -> repl d'
        Check k1 k2 ->
          case (find k1 d) of
            Just (k1', d') ->
              case (find k2 d') of
                Just (k2', d'') -> do
                  if (k1' == k2')
                    then putStrLn "Together"
                    else putStrLn "Apart"
                  repl d''

Having lots of nested cases always yells: refactor me.

Let's follow the flow of repl for a second...

Get a line and read it to an Action. If that is possible, diverge on the type of action: if it's an Add, merge them and repeat on success. If it's a Check, find the first one. If it's found, find the second one. If that is found, show whether they are together or apart and repeat.

There are lots of actions and processes stuffed together here, so let's help the poor repl breathe by splitting it up into pieces.

Reading input

What should happen when the user types garbage, such as "Bananas are a fruit"? Maybe we should just try again... so let's do that.

getAction :: IO Action
getAction = case Read.readMaybe <$> getLine of
    Just action -> return action
    Nothing     -> putStrLn "Oops, try again..." >> getAction

We read a line of user input and Read.readMaybe it to form an Action (<$> is just the infix operator for fmap). If that succeeds, horray, we got ourselves an Action! If not.. say something to the user and try again.

Executing the action

What should happen on an error here? That is your decision to make. If anything goes wrong, I'll just return the old DisjointSet and do nothing. I like to indent the case-statements based on the indentation level on the case itself, so let's do that.

execute :: DisjointSet Int -> Action -> IO (DisjointSet Int)
execute d (Add a b)   = return $ maybe d id (merge a b d)
execute d (Check a b) = case find a d of
                          Nothing       -> return d
                          Just (a', d') -> case find b d' of
                                             Nothing         -> return d
                                             Just (b', d'') -> if a' == b'
                                                                then putStrLn "Together" >> return d''
                                                                else putStrln "Apart"    >> return d''

(Note to Editors: The long line is on purpose)
Damn, that's still long.

Monads to the rescue!

The beauty of Maybe as a monad is that it'll stop doing whatever it does and just return Nothing once it encounters one. So let's use that!

execute :: DisjointSet Int -> Action -> IO (Maybe (DisjointSet Int))
execute d (Add a b)   = return $ merge a b d
execute d (Check a b) = do
    (together, d'') <- (do
             (a', d')  <- find a d
             (b', d'') <- find b d'
             return (a' == b', d''))
    when together       (putStrLn "Together")
    when (not together) (putStrLn "Apart")
    return d''

Putting it together

Using these fancy new functions, your new repl would be:

repl :: DisjointSet Int -> IO ()
repl d = getAction >>= execute d >>= \c -> case c of
    Just d' -> repl d'
    Nothing -> return ()


Finding the lowest possible number of changes to turn one string into another

I would suggest making jas, but not mal, a LinkedList. You only perform get operations on mal, and get is O(1) with an ArrayList. Removal operations, however, can be very costly with an ArrayList, because all the subsequent elements have to be rearranged. The worst-case-scenario is, of course, if you remove the first element of the list, which you are doing here. So jas would benefit a lot from becoming a LinkedList. The trick is that removing an element from a LinkedList is only O(1) if you do it via Iterator.remove() instead of one of the two remove methods defined in List. So instead of calling jas.indexOf(Object) and then calling jas.remove(int), I would manually create an Iterator by calling jas.iterator() and use this iterator to find the first occurrence of mal.get(index) in jas. If you have found it, you can simply call remove() on the iterator and remove the element from jas in O(1).

Here is a summary of the advantages and disadvantages of ArrayList and LinkedList.

In fact, mal does not need to be a List at all. All you are doing with mal is retrieving a character at a specific index, and you can do that with a String too. The time complexity of String.charAt(int) is O(1), just like that of ArrayList.get(int), because String uses a byte[] internally to store the characters (or apparently a char[] before Java 9), so it should not be noticeably slower than ArrayList.get(int), and since you would not need to create the ArrayList mal from the String nazwiskoMal in the first place, you can even save a bit of performance.

Apart from that, here are some other suggestions for your code:

You don't actually need the if-else construct. If you deleted the else clause and just unconditionally executed the code inside the if clause, the effect would be the same, but the code would be a bit more compact.
Declare the two lists as Lists (interface), not as their implementation (ArrayList or LinkedList). Their usage doesn't depend on their implementation, only on their functionality. So instead, I would write:

List<Character> jas = new LinkedList<>();
List<Character> mal = new ArrayList<>();

By the way, you instantiated two raw types. This is not a big deal here because you used the no-argument-constructor, which means that there is no way for the List to contain any elements of another type than Character, but just for the sake of clarity, I would use the diamond operator in the instantiation of the two lists.

Edit

Here is a code sample to illustrate what I mean by using an iterator. By the way, I replaced your while(jas.size()>1) loop with a for loop, which I think is easier to read because it limits the scope of index to the loop itself, whereas in your code, index unnecessarily lives on even after the loop terminates.

int steps = 0;
for (int index = 0; index < nazwiskoMal.length() - 1; index++) {
    int distance = 0;
    Iterator<Character> jasIterator = jas.iterator();
    while (jasIterator.hasNext()) {
        if (!jasIterator.next().equals(nazwiskoMal.charAt(index))) {
            distance++;
        } else {
            steps += distance;
            jasIterator.remove();
            break;
        }
    }
}

This a bit more complicated to read than your code, because you have to manually find the element and keep track of the index (which you need to calculate the number of steps), but on the other hand, you only have to iterate over jas once per character from nazwiskoMal because the removal is accomplished via Iterator.remove(), whereas your code would require two (implicit) iterations if you make jas a LinkedList instead of an ArrayList: one for finding the first occurrence of the character, and a second iteration for removing it via List.remove(int) (if jas is an ArrayList, then List.remove(int) would be able to find the element in constant time without needing to iterate over the list, but the actual deletion would, as already mentioned, require all subsequent elements to be moved, which is not the case with a LinkedList).

Update

Inspired by your idea not to reset the iterator over jas when there are consecutive identical characters in mal, I've tried to apply this principle whenever the next character in mal has not yet occurred in jas during the last iteration over jas, and not only when the next character in mal is identical to the last character from mal.

The trick was making the check whether a character has already occurred in jas cheap enough so that the savings in loop iterations are not outweighed by the overhead of the check itself. I originally tried putting the characters encountered during an iteration over jas in a HashSet, which would be the easiest solution, but this turned out to be far too slow to be worth it. Then I tried using a boolean array that contains a value for every possible character that signifies whether this character has already occurred in jas, and this did indeed speed up the program, not in a groundbreaking manner, but definitely noticeable:

public static long calculateSteps(String nazwiskoJas, String nazwiskoMal) {

    List<Character> jas = new LinkedList<>();
    for (int i = 0; i < nazwiskoJas.length(); i++) {
        jas.add(nazwiskoJas.charAt(i));
    }

    char lowestChar = nazwiskoMal.charAt(0);
    char highestChar = nazwiskoMal.charAt(0);
    for (int i = 1; i < nazwiskoMal.length(); i++) {
        lowestChar = (char) Math.min(nazwiskoMal.charAt(i), lowestChar);
        highestChar = (char) Math.max(nazwiskoMal.charAt(i), highestChar);
    }

    ListIterator<Character> jasIterator = jas.listIterator();
    boolean[] characterHasBeenEncountered = new boolean[highestChar - lowestChar + 1];
    Arrays.fill(characterHasBeenEncountered, false);
    long steps = 0;

    for (int index = 0; index < nazwiskoMal.length() - 1; index++) {
        if (characterHasBeenEncountered[nazwiskoMal.charAt(index) - lowestChar]) {
            jasIterator = jas.listIterator();
            Arrays.fill(characterHasBeenEncountered, false);
        }
        Character nextCharacterInJas;
        while (!(nextCharacterInJas = jasIterator.next()).equals(nazwiskoMal.charAt(index))) {
            characterHasBeenEncountered[nextCharacterInJas - lowestChar] = true;
        }
        jasIterator.remove();
        steps += jasIterator.nextIndex();
    }
    return steps;
}

I tried an even hackier approach using a single int variable as a bitmask instead of a boolean[] in hopes that setting an int to 0 would be faster than filling a boolean[] of 26 elements with false. This was indeed a bit faster than a boolean[], but not much, and of course, it has the drawback that it only works for up two 32 different characters (or 64 if you use a long).

I also replaced the Iterator with a ListIterator, because by taking advantage of the method ListIterator.nextIndex(), the variable distance becomes obsolete.

Finally, you said that you need the program to work for strings of up to 1,000,000 characters, and while experimenting, I noticed that the number of steps for randomly generated and scrambled strings of length 1,000,000 containing only the characters A to Z were getting dangerously close to Integer.MAX_VALUE. While the number of steps for randomly generated strings so far have not exceeded Integer.MAX_VALUE, I constructed an extreme example where the result would indeed not fit in an int. Suppose you have a string that starts with 38461 A's, followed by 38461 B's, then 38461 C's etc., and the scrambled version would simply be the reverse of this string, i.e. 38461 Z's, followed by 38461 Y's etc. The string would have a length of 999986, and the number of changes needed to turn one into the other would be 480,755,769,325, which is greater than Integer.MAX_VALUE (2,147,483,647) by far. Ironically, the algorithm runs in under one second for this special case with the optimizations for repeated/already encountered characters, while without these optimizations, it seems to take forever (I've stopped the program after 40 minutes or so).

But seriously, I really doubt that it's possible to squeeze any more performance out of this algorithm, at least in Java. Maybe using a language that's not interpreted by a virtual machine but directly compiled to machine code would make the program faster, but I have no idea whether this is really true in this case. I don't know anything about this, but I've read that compilers today are so optimized that even a program in an interpreted language does not necessarily run slower than if it were written a compiled language. But this probably depends on the program, the language, the compiler and other things and cannot be generalized. Nevertheless, if the programm is still too slow, it might be worth a try to use a different language altogether, although I have no idea what language could be more suitable for this, and if it would actually make a significant difference.


I would just write

isPalindrome w = w == reverse w

Short, and very easy to understand! And in this case it's also a lot more efficient, but that's another story...


Setting the value of properties via reflection

You can use reflection to parse some common .Net types:

public static object Parse(Type type, string str)
{
    try
    {
        var parse = type.GetMethod("Parse", new[] {typeof(string)});
        if (parse == null) throw new NotSupportedException();
        return parse.Invoke(null, new object[] { str });
    }
    //or don't catch
    catch (Exception)
    {
        return null;
    }
}

It will basically allow you to replace this code:

        if (dataType.Equals(typeof(float)))
        {
            propertyValue = Convert.ToSingle(propertyValue);
        }

        if (dataType.Equals(typeof(double)))
        {
            propertyValue = Convert.ToDouble(propertyValue);
        }

        if (dataType.Equals(typeof(decimal)))
        {
            propertyValue = Convert.ToDecimal(propertyValue);
        }

        if (dataType.Equals(typeof(byte)))
        {
            propertyValue = Convert.ToByte(propertyValue);
        }

        if (dataType.Equals(typeof(string)))
        {
            propertyValue = Convert.ToString(propertyValue);
        }

        if (dataType.Equals(typeof(char)))
        {
            propertyValue = Convert.ToChar(propertyValue);
        }

        if (dataType.Equals(typeof(int)))
        {
            propertyValue = Convert.ToInt32(propertyValue);
        }

        if (dataType.Equals(typeof(long)))
        {
            propertyValue = Convert.ToInt64(propertyValue);
        }

        if (dataType.Equals(typeof(short)))
        {
            propertyValue = Convert.ToInt16(propertyValue);
        }

with this line:

propertyValue = Parse(dataType, propertyValue.ToString());

It will work for every other class, that has public static void Parse(string) method declared (most standart value types do). You can add Parse(string) method to your own classes, to make them support this kind of deserialization. You can also modify the above code to use Parse(string, IFormatProvider) instead, to avoid parsing issues related to different decimal separators in different cultures.


Once various responsibilites (functionality) is separated into appropriate classes, inheritance and using subclasses is not a problem.

Rethink your core classes. Don't make client code do the work - that's a guarantee of duplication. A good class hides state and exposes functionality. Even basic functionality like overriding Equals pays off. "Do not make client code do the work for that class". Repeat this a million times. Oh, I expect you will also avoid tons of debugging.

Some methods are overloaded. The point is when you see a need for something different put that in the proper class. Don't be lazy and write it in the calling class because it's easy and quick.

SPOILER: gear and gear collections are just data structures. Abstract things. A Warrior has his personal stuff (a gear collection) and an Armory (a really big gear collection) is where he buys his stuff.

Gear enum

Looks like you care only if some gear is a weapon, armor, etc. not a specific object.

public enum GearType { undefined, Weapon, Armor }

Make Gear abstract

And give it all the common gear behavior.

public abstract class Gear {
    protected decimal price { get; set; }
    public GearType Type { get; protected set; } // set only in a constructor

    public virtual bool IsSameKind( Gear otherGear ) {
        return this.Equals( otherGear );
    }

    // I thought of this as I was working on the collection class below
    public virtual bool IsSameKind( GearType thisKind ) { return this.Type == thisKind; }

    // any armor is armor. any weapon is weapon....
    /// <summary>
    /// Equates on Type property.
    ///</summary>
    public override Equals( Object otherGear ) {
       if( otherGear == null ) return false;

       otherGear = otherGear as Gear;
       if( otherGear == null ) return false;

       return this.Type == otherGear.Type;
    }
}

Use Constructors

To guarantee valid, complete, correct objects.

public class Armor : Gear {
   protected int blunt { get; set; }
   protected int slash { get; set; }
   protected int range { get; set; }

   public Armor ( decimal price, int blunt, int slash, int range ) {
      this.Type = GearType.Armor;
      // set other properties here
   }
}

Custom Collections

Solves your upcast issue.

Also higher level code will make more sense, is cleaner, clearer, and simpler.

publc class GearCollection {
   protected List<Gear> Armory { get; set; }

   public GearCollection() { Armory = new List<Gear>(); }

   public void Add ( Gear thing ) {
       if ( thing == null ) return;
       Armory.Add( thing );
   }

   // Passing in a Gear reference. The OBJECT itself will be
   // a "Weapon", "Armor", etc.
   public bool Contains( Gear otherThing ) {
       if ( otherThing == null ) return false;
       if ( Armory.Contains( otherThing ) ) return true;  // uses equals override.
       return false;
   }

   public bool Contains( GearType thisGear ){
      bool gotIt = false;

      foreach( var item in Armory ) {
         if( item.IsSameKind( thisGear ) {
            gotIt = true;
            break;
         }
      }
      return gotIt;
  }

   public GearCollection GetAll( GearType thisKind ){
      GearCollection sameGear = new GearCollection();

      foreach( var item in Armory ) {
         if( item.IsKind ( thisKind ) {
            sameGear.Add( item );
         }
      }
      return sameGear;
   }

   // this method makes THIS collection object mutable.
   // a discussion for another time.
   public GearCollection GetAll( Gear likeThis ){
      GearCollection sameGear = new GearCollection();

      foreach( var item in Armory ) {
         if( item.Equals( likeThis ) ) sameGear.Add( item );
      }
      return sameGear;
   }
}

Separation of concerns

Why would a button have its own gear? That's a code smell to me. I'd expect event handlers to call methods on domain objects like Warrior or AmmoDump or WeaponCache. Those are things I expect to have Gear, not the UI controls.

public class Warrior {
    protected GearCollection MyGear { get; set; }
    public Warrior() { MyGear = new GearCollection(); }
    public Warrior( GearCollection standardIssue ) {
       MyGear = standardIssue?? new GearCollection();
    }
}

// The Armory is where you buy your gear. A gear collection is just
// a data structure => separation of concerns.
public class Armory {
   protected GearCollection Inventory { get; set; }

   // optional parameter so I don't have to write
   // a contructor overload.
   public Armory( GearCollection newInventory = null ){
      Inventory = newInventory ?? new GearCollection();
   }

  // renamed "CanBuy".
   public bool IsInStock( GearType gearKind ) {
       return Inventory.Contains( gearKind );
   }

   public bool IsInStock( Gear likeThis ) {
      return Inventory.Contains( likeThis ) {
   }

   public Gear Buy( GearType something, decimal cashOnly ) {
      if( !IsInStock( something ) )  return null;

      Gear newBling = Inventory.Remove( something );  // didn't write that method yet.
      if( cashOnly < newBling.Price ) return null;

      return newBling;
   }

   public void AddInventory ( GearCollection newShipment ) {
      if( newShipment == null ) return;
      Inventory.AddRange( newShipment );
   }
}

P.S. Now that we defined the Armory class, I'd go back and rename the GearCollection.Armory property. Make it more general, more abstract sounding because it is. The collection is a data structure. We want names appropriate for the class they are in.

The methods defined in Armory class is what brings the armory concept to life - not it's properites.

Edit

  could you write an answer with your suggestion of "type checking". Id love to see how you would do it.

It depends on how specific you want to be. The keyword is:

  An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

If everything derives from Gear, that won't help too much looking into a GearCollection.

Keyword typeof returns a System.Type that you can compare to the typeof of other objects in a GearCollection. This is the specific type of your object.

Type Checking: typeof, GetType, or is?

end Edit


Using a class for reading config from files

Firstly, you state:

  I wrote a function but then I needed a class

Looking at the class you wrote, I would say you were incorrect there. The class has no __init__, holds no state, and only uses self to access other methods on the class. There is absolutely no reason for it to be a class.

Duplication is the programmer's arch enemy - every time you have the same thing written out more than once is an opportunity to reduce the amount of code you write, test and maintain. For example:

# reading user's config file
try:
    with open(cmd_parameter, 'r') as config_file_name:
        config_file = config_file_name.readlines()
except FileNotFoundError:
    print("File '", sys.argv[1], "' not exists or not available")
    exit(-1)

# reading global config file
try:
    with open(cmd_parameter_global, 'r') as config_file_global_name:
        config_file_global = config_file_global_name.readlines()
except FileNotFoundError:
    print("Global configuration file '", cmd_parameter_global, "' not exists or not available")
    exit(-1)

Note that these do more-or-less exactly the same thing, and should therefore be refactored to something like:

def extract_file(filename, message):
    try:
        with open(filename) as file_:
            return file_.readlines()
    except FileNotFoundError:
        print(message.format(filename))
        exit(-1)

and then called like:

config_file = extract_file(cmd_parameter,
                           "File '{}' not exists or not available")

You should apply this throughout your code - you have basically written the same program twice, with minor adjustments, for the two config files, which makes no sense.

The dict is a key data structure in Python, and would make all of your code vastly simpler. You could create a dictionary of the global configuration options, then update it with the local values. Lookups by name would then be O(1), rather than O(n), and you could get rid of all the indexing.

In terms of general structure, you have lots of code running at the top level of the script. This is generally a bad idea, and will give you problems if you later want to import this functionality elsewhere. You should define an entry point (usually, but not necessarily, called main) that takes the file locations as parameters and call it something like:

if __name__ == "__main__":
    if len(sys.argv) == 2:
        main('global.cfg', sys.argv[1])
    else:
        print("Error: there should be one argument after program name - config file name")
        exit(-1)


Building a list - why is this code inefficient?

It's inefficient because you're doing a lot of work to create a factorial l, iterating over it l times, each time REDOING all the work of sorting and joining each permutation, and then throwing away most of the results!

Here are some suggestions:

You don't need to extend permutations into an array in memory (loose the to_a), a generator is generally more efficient to iterate over.
You don't need to sort and join the permutations again for every length, this is probably the biggest waste of time. Once they've been sorted and joined you can uniqify them then and then create shorter strings from them (which will need uniqifying again but this will be less work).
Finally, if instead you split and sort the input string at the beginning then you can use the combination function to generate only valid combinations for each length.


A function that updates JSON disk object

You could define a default disk object, so you can show all fields on default values and document the values allowed for each:

var DiskSkelethon = {
    "componentTypeId" : "com.vmware.csp.iaas.blueprint.service",
    "componentId" : null,
    "classId" : "Infrastructure.Compute.Machine.MachineDisk",
    "typeFilter" : null,
    "data" : {
        "capacity" : -1,
        "custom_properties" : null,
        "id" : null,
        "initial_location" : "",
        "is_clone" : false,
        "label" : "",
        "storage_reservation_policy" : "",
        "userCreated" : true,
        "volumeId" : -1
    }
}

Then in your function you will make a copy of it and override just the fields you're changing:

function addDisk(disk, size) {
    var diskNumber = parseInt(disk.slice(-1), 10);
    if (isNaN(diskNumber)) {
       log("some error...");
       return false;
    }
    var diskLabel = "Hard disk " + diskNumber;
    var diskIndex = diskNumber - 1;

    //Updating JSON data object
    var diskData = Object.assign({}, DiskSkelethon)

    diskData.data.capacity = size;
    diskData.data.label = diskLabel;
    diskData.data.volumeId = diskIndex

    data.disks[diskIndex] = diskData
    log(diskLabel + " has capacity of: " + size + " GBs");
}


Before looking for efficiency, note that there is a logical error in the tail recursive version of your function: it does not terminate on negative values (while the first function does terminate).

A way of correcting this error is simply to perform the check before calling f-iter. For instance:

(define (f n)
  (if (< n 3)
      n
      (f-iter 2 1 0 n)))

(define (f-iter a b c count)
  (if (= count 0)
      c
      (f-iter (+ a (* 2 b) (* 3 c)) a b (- count 1))))

From the efficiency point a view, I performed a few (unscientific) tests in DrRacket and noticed the following facts:

If the auxiliary function is defined inside f, the execution is 30-35% faster (and I think this is also stylistically better!)
An additional speedup of 20-40% can be gained if we reverse the counter, making it starting from 0 and going to n.

The differences in execution times where noticeable with n greater than 15000.

And so this is the more efficient version according to those tests:

(define (f n)
  (define (f-iter a b c count)
    (if (= count n)
        c
        (f-iter (+ a (* 2 b) (* 3 c)) a b (+ count 1))))
  (if (< n 3)
      n
      (f-iter 2 1 0 0)))

Of course these differences can be accounted only to the compiler, not to a change of the algorithm, so that by using another compiler maybe no differences could be found, or they could even be reversed!


In my opinion, what you need is an enum.

Use an enum and I believe what you are looking for will be provided for you.

public enum Utils {
    PROVIDER_FOO, PROVIDER_MOO, PROVIDER_BAR, PROVIDER_FUR,
    PROVIDER_BOO, PROVIDER_ANOTHER_FOO, PROVIDER_YET_ANOTHER;
}

String to int:

Utils.valueOf(str).ordinal();

int to String:

Utils.values()[intValue].name();

Or if you want to be a bit more advanced, I suggest reading this answer of mine


Imperative code in R keeping track of state

R encourages vector-based operations instead of loops. But in this case, I don't think there's a good way around tracking the state of delta.

This might be a slightly better way to create a vector delta:

delta <- 0
vdelta <- c(0)
for (i in 2:nrow(db)) {
  row <- db[i,]
  prev <- db[i-1,]
  if (row$class != prev$class) {
    delta <- 0
  } else if (row$src != prev$src) {
    delta <- prev$end + delta
  }
  vdelta <- c(vdelta, delta)
}

Based on vdelta you can easily create the columns you need:

db$corr.start <- db$start + vdelta
db$corr.end <- db$end + vdelta
db$delta <- vdelta


Find the nearest (small) number x where x can be represented by sum of cubes

personally I would calculate that value like e.g. this:

/*
 * check the updated algorithm, please
 *
- (Float64)neareastSmallerSumOfCubes:(NSInteger)originalNumber {
    if (originalNumber > 1) {
        Float64 _firstAttempt = pow((Float64)originalNumber, 1.0/3.0);
        if (_firstAttempt == floor(_firstAttempt)) originalNumber--;
        NSInteger _a = pow((Float64)originalNumber, 1.0/3.0);
        NSInteger _b = pow((Float64)originalNumber - pow(_a, 3.0), 1.0/3.0);
        return pow(_a, 3.0) + pow(_b, 3.0);
    } else {
        return MAXFLOAT;
    }
}
*/

update

thank for @Szu, he has highlighted an issue with some large numbers;
thank for @Rob, he has highlighted an issue when input is already a pure sum of cubed;

I've updated the algorithm a bit according to the feedbacks, here is the final solution:

- (Float64) neareastSmallerSumOfCubes:(NSInteger)originalNumber {
    if (originalNumber > 1) {
        Float64 _firstAttempt = pow((Float64)originalNumber, 1.0/3.0);
        if (_firstAttempt == floor(_firstAttempt)) originalNumber--;
        NSInteger _a = pow((Float64)originalNumber, 1.0/3.0);
        NSInteger _b = pow((Float64)originalNumber - pow(_a, 3.0), 1.0/3.0);
        if (_b > 1) _b--;
        NSInteger _s = round(pow((Float64)originalNumber / 2.0, 1.0/3.0));
        Float64 _neareast = 0.0;
        do {
            Float64 _possibleNearest = pow(_a, 3.0) + pow(_b, 3.0);
            if (_possibleNearest > originalNumber) _a--;
            else if (_possibleNearest > _neareast && _possibleNearest != originalNumber) _neareast = _possibleNearest, _b++;
            else _b++;
        } while (_b <= _s);
        return _neareast;
    } else {
        return MAXFLOAT;
    }
}

random test values:

99998 returns 99937 (= 333 + 403) (runtime O(36))
4105 returns 4104 (= 163 + 23) (runtime O(17))
1023 returns 1008 (= 103 + 23) (runtime O(11))
999 returns 945 (= 93 + 63) (runtime O(6))
216 returns 189 (= 53 + 43) (runtime O(4))
3 returns 2 (= 13 + 13) (runtime O(1))

explanation

let us get the two essential conditions from the OP

y < x > 1;
y can be expressed with a3 + b3;
where x, y ∈ ℕ, a, b ∈ ℕ+ and a > 0, b > 0 (that last condition obviously has to be satisfied);

#1

we know 13 + 13 < x < (x+1)1/3 + (x+1)1/3, therefore the actual smaller value also must be in this interval.

if we can build a simple (x+1)1/3 by (x+1)1/3 matrix which holds every possible combination of sums of cubes, that matrix must contain the value we are chasing.

  COMMENT: after certain number of iterations (maximum number of iterations: ((x+1)1/3)2) the requested nearest smaller value can be extracted from that massive interval via e.g. brutal-force algorithms, but we are looking for a much efficient solution than that.

#2

we know the already the addition is commutative operand, so a+b=b+a, so we can drop the part under the diagonal of the matrix, so we can stop the iteration later when we reach the column s = (x/2)1/3. the s is rounded down to the nearest natural, s ∈ ℕ.

#3

the possible values are at certain locations in the half matrix, the possible elements are on an exponential curve, that helps to establish the actual logic of the iterations.

we need to find where this curve enters the matrix, and we walk through the values of the matrix what the curve intersects.

the enter row index is the whole part of a = x1/3 and the column index is the whole part of the b = (x - a3)1/3.

we know:

a > s > b is always true, therefore:
x > a3 + b3; that value also can be the possible nearest smaller, which we called y.
x < (a+1)3 + (b+1)3;
we don't know the relation between x and a3 + (b+1)3; that is what we will find out:

let b = b + 1 and check what we have got:

if the x > a3 + b3 > y, that is a another possible nearest smaller; if not, we ignore it;

if the x = a3 + b3, that is the same as input, we ignore it, according to the original y < x condition;

if the x < a3 + b3, that value is greater than the original number, so we ignore it; because the a > s > b and x ≧ 2s3 statements are always true, therefore x ≧ (a-1)3 + b3 will be true as well, so we can let a = a - 1 and start the next iteration with the new a, b values.

the iteration stops when the b reaches the intersection of the matrix diagonal and the exponential curve, that value was calculated above as s; so if we reach the intersection point, we can be sure that we have already checked all possible nearest smaller values which the matrix holds; and during making the iterations we always kept the largest one as y, thus when we stop the algorithm, the y will hold the only nearest smaller value.


According to the rules, you can only use each tile once per word.  You haven't attempted to keep track of tile usage.

Consider storing your dictionary using a trie, such as the implementation in Apache Commons.  It should provide an efficient .prefixMap(), which is like your dictionary.subSet().

You defined graph, but you never use it.

I think that an object-oriented interface would feel natural.  Create a new instance of Boggle by passing the char[][] matrix to the constructor.

Method names should be verbs, and shouldn't be redundant with the class name.  Therefore, .boggleSolver() should just be .solve().

The purpose of the loop…

for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
    for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
        if (i1 != i || j1 != j) {
            // loop body
        }
    }
}

… is to iterate through all the neighbours of tile (i, j).  A comment to that effect would be appreciated.  Also,  I would invert the if-condition to avoid a level of nesting:

// Iterate through the neighbours of tile (i, j)
for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
    for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
        // Skip the tile (i, j) itself
        if (i1 == i && j1 == j) continue;

        String word = prefix+ m[i1][j1];
        if (!dictionary.subSet(word, word + Character.MAX_VALUE).isEmpty()) {
            if (dictionary.contains(word)) {
                validWords.add(word);
            }
            solve(m, i1, j1, word, validWords);
        }
}

Note that the dictionary.contains(word) check can be moved inside the !dictionary.subSet(...).isEmpty() check.


I needed to find the largest amount of passengers

If you need just the largest amount, you don't need to sort the whole list (which is slow*), you can instead walk though the list, remember the largest amount found so far and update that as you iterate the list.

LINQ already contains a method that does just that, called Max().

* Sorting is \$\mathcal{O}(n \log n)\$ with a good algorithm, or \$\mathcal{O}(n^2)\$ with a trivial algorithm like the one you used; finding maximum is just \$\mathcal{O}(n)\$.


function to check if word matches search word

I don't know C, my code is not tested.

Having whitespace at the end of lines of code is really annoying to work with.
I'm not a fan of if without curvy brackets. I have previously been bitten by adding another expression in the if and neglecting to add the brackets.
I would much prefer using break over while (whileFlag).
I would much prefer using return ... over returnFlag.
By changing the above we can change the do while loop to just a while (true) loop.
If you've followed along with the changes we can see that searchNode will be null when we want to break from the loop. And so we can remove the inner ifs by moving them to the while.

bool check(const char *word)
{
    int nodeIdx = hash(word);
    if (nodeIdx < 0)
    {
        return false;
    }

    nodeWords * searchNode;
    searchNode = nodeArray[nodeIdx];

    while (searchNode != NULL)
    {
        if (strcmp(word, searchNode->word) == 0 )
        {
            return true;
        }
        else if (strcmp(word, searchNode->word) < 0 )
        {
            searchNode = searchNode->left;
        }else{
            searchNode = searchNode->right;
        }
    }
    return false;
}


Google Analytics tracking for HTML 5 video player

I would use a single bind:

$("#videoplayer").bind("timeupdate", function() {
    var currentTime = this.currentTime;
    if (currentTime > 0.75 * (this.duration)) {
        a = a + 1;
        console.log("watched 75%");
        ga('send', 'event', 'Videos', 'Watched 25%', 'Video 1');
    } else if (currentTime > 0.50 * (this.duration)) {
        b = b + 1;
        console.log("watched 50%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    } else if (currentTime > 0.25 * (this.duration)) {
        c = c + 1;
        console.log("watched 25%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    }
});

Unless there's a specific reason for you not to?


Custom implementation of the linq Zip operator for different length lists

public static class Impl
    {
        public static IEnumerable<TResult> ZipNew<TFirst, TSecond, TResult>(

Names? The class would be more descriptive as something like LinqExtensions; the method something like ZipLooped.

            using (IEnumerator<TFirst> iterator1 = first.GetEnumerator())
            using (IEnumerator<TSecond> iterator2 = second.GetEnumerator())
            {
                var i1 = true;
                var i2 = true;
                var i1Shorter = false;
                var i2Shorter = false;
                var firstRun = true;

The iterators have useful names, but what does i1 mean? And why five variables to track the state of two iterators? IMO it would be simpler as

                var firstEnded = false;
                var secondEnded = false;

                while (true)
                {
                    if (!iterator1.MoveNext())
                    {
                        if (secondEnded) yield break;
                        firstEnded = true;
                        iterator1.Reset();
                        if (!iterator1.MoveNext()) yield break;
                    }
                    if (!iterator2.MoveNext())
                    {
                        if (firstEnded) yield break;
                        secondEnded = true;
                        iterator2.Reset();
                        if (!iterator2.MoveNext()) yield break;
                    }

                    yield return resultSelector(iterator1.Current, iterator2.Current);
                }

and the almost repeated code might be worth pulling out as an inner method:

                var firstEnded = false;
                var secondEnded = false;

                bool advance<T>(IEnumerator<T> it, ref bool thisEnded, bool otherEnded)
                {
                    if (it.MoveNext()) return true;
                    // `it` has done a full cycle; if the other one has too, we've finished
                    if (otherEnded) return false;
                    thisEnded = true;
                    // Start again, although if `it` is empty we need to abort
                    it.Reset();
                    return it.MoveNext();
                }

                while (true)
                {
                    if (!advance(iterator1, ref firstEnded, secondEnded)) yield break;
                    if (!advance(iterator2, ref secondEnded, firstEnded)) yield break;
                    yield return resultSelector(iterator1.Current, iterator2.Current);
                }

I notice that you've decided to yield break if either of the enumerables is empty. Would an exception be a better choice?


Terser syntax for first-class functions needing a context bound

How about not having to specify the type at all?

implicit class SeqWithAction[T:Fractional](seq:Seq[T]) {
  def getAction( op : String ) : String =
    op match {
      case "add" => seq.sum.toString
      case "product" => seq.product.toString
      case "mean" => {
        implicit def intToFractional(i : Int) =
          implicitly[Fractional[T]].fromInt(i);
        (seq.sum / seq.length).toString
      }
      case "sqrt" => seq.map(i => math.sqrt(i.toDouble)).toString
    }
  }
}
Seq(4.0).getAction("sqrt")


Compute the probabilities of getting each of the possible sums when throwing 2 dice, n times

First thing to note is that since you only check up to s=12, your code won't work for more than 2 dice. What you really need is a list so how high you go can be a variable.  Also N*(float(M)/N) seems the same as float(M), so I'm not sure what you're trying to do there.

def freq_2dice(n, N):
    dice_list = [0] * (n*6+1)
    for reps in xrange(N):
        s = 0
        for dice in xrange(n):
            outcome = randint(1, 6)
            s += outcome
        dice_list[s] += 1
    return dice_list

I rewrote your freq_2dice using an list.  My version is a little different because it'll return 0 through 6*n instead of 2 through 12.  dice_list = [0] * (n*6+1) lets me start with a list populated with all zeroes that is n*6+1 long (since it starts with 0 but I still want to include 6*n in the list)

Next, you're running the really expensive part of your program (freq_2dice) 22 times! You're actually running it twice every line, so that the number of 2's won't match the corresponding probability because those are two different runs.  Running it the first time provides all of the information you need.

Instead of all your print statements, a loop would be good there too.  So first, I'm going to run each function just ONCE instead of repeatedly and I'll store the results. Then I'll use a loop for the print statement (which could let you make the print range dynamic for more than 2 dice as well, but I'll just keep it simple here)

freq_2_dice_results = freq_2dice(n, N)
dice_chance_results = chance_die()
for dice_value in range(2, 13):
    print 'No. of %d: %d, probability: %.2f, expected: %.2f' % (
        dice_value,
        freq_2_dice_results[dice_value],
        float(freq_2_dice_results[dice_value])/(N/100),
        dice_chance_results[dice_value]/.36)

I hope that gives you a good place to start.


Welcome to the world of OOP — hopefully there are a few things we can teach you. ;)

I'm going to show you an alternative implementation first, to help you see how OOP truly should be used, then I'll discuss your specific issues.

When building a calculator it's hard to effectively build something dynamic, you are always concerned about how things should relate (for example, how do we represent \$a+b+c\$, as \$(a + b) + c\$, as \$a + (b + c)\$, or some other way?), but it's often easiest if you consider each term and operation on it's own.

Let's take \$+\$, for example, we should have two terms: a left and a right. But what is a term?

A term can be any of the following:

A value (\$1\$, for example);
Another expression / operation (\$a + b\$, for example);

What do they have in common? They all have a Value property. So, in order to represent this we start with an interface:

Public Interface ITerm
    Property Value As Double
End Interface

Pretty simple, and we'll define a ConstantTerm:

Public Class ConstantTerm
    Implements ITerm

    Public Sub New(value As Double)
        Me.Value = value
    End Sub

    Public Property Value As Double Implements ITerm.Value
End Class

So far so good, we have a ConstantTerm which is just set to a value, so we can now build an AdditionTerm:

Public Class AdditionTerm
    Implements ITerm

    Public Sub New(left As ITerm, right As ITerm)
        Me.Value = left.Value + right.Value
    End Sub

    Public Property Value As Double Implements ITerm.Value
End Class

So now, to do our math, we just need to do:

Dim result As Double = _
    New AdditionTerm( _
        New ConstantTerm(CDbl(TextBox1.Text.Trim)), _
        New ConstantTerm(CDbl(TextBox2.Text.Trim))).Value

But even better: this sets us up for success later when we want to add a SubtractionTerm:

Public Class SubtractionTerm
    Implements ITerm

    Public Sub New(left As ITerm, right As ITerm)
        Me.Value = left.Value - right.Value
    End Sub

    Public Property Value As Double Implements ITerm.Value
End Class

And it also sets us up for parsing things later on down the road. (Since we don't care about values, we only care about terms, a parser just has to define a term as it goes and supply them as arguments to the next term.)

Regarding your specific code, there are a few things to take note of:

In .NET we pretty much always try to name classes, interfaces, enums, and properties PascalCase — instead of Cls_addition we would use ClsAddition;
When you set totalAddition.TermA and TermB, you should try to use a safer parsing system, via {NumericType}.TryParse:

Dim value As Integer = 0
If Integer.TryParse(TextBox1.Text.Trim(), value) Then
    'Parse was successful
Else
    'Show the user an error message, perhaps
End If

Always name things what they mean, and not what they are: TextBox1 is a bad name, it should be firstTermInput, etc.;
More recent versions of VB.NET support automatically-implemented properties, such as Property TermA As Integer, instead of manually specifying a Getter and Setter;

Overall, good start, and I hope you continue to learn and improve as you experiment and continue. :)


Filtering an array according to 7 checkboxes in a form

The first thing I notice is that this:

if (this.deliveryConcession[0].checked) {
  this.allItems = this.allItems.filter(fil => fil.deliveryconcession.readytoship === this.deliveryConcession[0].checked);
}

Is the same as

if (this.deliveryConcession[0].checked) {
  this.allItems = this.allItems.filter(fil => fil.deliveryconcession.readytoship);
}

As a second step I would refactor this to something like:

deliveryConcession = [
    { id: 1, name: 'Ready to ship(paper)', checked: false, key: 'readytoship' },
   ...
];

function filterItems(items, concessions, name) {
  for (let k in concessions) {
    let concession = concessions[k];
    if (concession.checked)
      items = items.filter(fil =>  fil[name][concession.key] )
  }
  return items;
}

this.allItems = filterItems(this.all Items, this.deliveryConcessions, 'deliveryConcession');

An alternative might be to define your hash as:

deliveryConcession = [
    { id: 1, name: 'Ready to ship(paper)', checked: false, filter: fil => fil.deliveryConcession.readyToShip },
   ...
];

function filterItems(items, concessions, name) {
  for (let k in concessions) {
    let concession = concessions[k];
    if (concession.checked)
      items = items.filter(concession.filter)
  }
  return items;
}


PHP code structure for string manipulation tasks

Yes, I think your variable names are a bit long.  While it is good to be expressive, you don't want to be pushing your line width beyond the recommended max width if avoidable.

I don't know if you need many custom functions here.  The shared calls which filter empty and duplicate strings can be a custom call.  Otherwise, everything else is single-use.

Consider this snippet which simplifies much of the script by grouping the multibyte and single-byte non-whitespace substrings from the start.  No extra exploding, and only one implode call.

Code: (Demo)

function uniqueNoEmpty($array) {
    return array_unique(array_filter($array, 'strlen'));
}

$original_string = 'one two three 喞 喝 four 刷囿 two 跏正 吁';

if (!preg_match_all('~(\p{Han}+)|(\S+)~u', $original_string, $out)) {
    echo 'no qualifying strings';
} else {
    $singleBytes = uniqueNoEmpty($out[2]) ?? [];
    $multiBytes = array_reverse(uniqueNoEmpty($out[1]));

    echo implode(' ', array_merge($singleBytes, $multiBytes));
}


Parsing pairs of a number or number range

Just answering this question since it is unanswered. Hope, it would help:

Since your code is mainly about RegEx, which you'd most likely know that you can use this tool:

Your original RegEx based on an exact match method takes 265 steps and 1ms to match your 10 inputs, which is good.

\s*(?:(\s*\d+\s*)|([\[\(]\s*\d+)\s*,\s*(\d+\s*[\]\)]))(?:,\s*(?:(\d+\s*)|\s*([\[\(]\d+)\s*,\s*(\d+\s*[\]\)])|(\s*>\s*=\s*0\s*)))?\s*

Sometimes, exact match may not be necessary, not sure about your case or if you might have certain boundaries, but maybe you could use a faster RegEx with a lower number of iterations, maybe something similar to this, if you are not looking for an exact match, which is pretty fast and might match your 10 inputs with only 50 steps:

^[0-9\,\[\]\(\) >=]*$

The drawback of this method is that it is based on your input characters, i.e., numbers, [, ], (, ), ,, space and >=.


You asked,

  Would it make it better if I had a function called PiApproximation?

The code in main does just one thing so it would not be an improvement to introduce a new function like this — the question would then be, what's the point of main?
There is a dependency between the initial value of n and the initial values of innerPoly and outerPoly. It would make sense to put all the initialization code together.
Because n can never be negative it could be unsigned.
The loop:

for (int i=3; n<=8192; n=power(i,2), i++)

is quite hard to follow because the loop variable is i but the termination condition is on a different variable n. Because the loop variable i is not used, it would be easier to follow the logic if you wrote:

for (; n <= 8192; n *= 2)

(This also avoids the need for the power function.)
The l modifier has no effect on the printf format specifier %f, and so should be omitted.


Performing the Lychrel algorithm in Rust

Use const instead of static if you don't need to take the address of the global.
Use for over a range instead of mutating a counter.
It's a little strange to return a value when the iteration runs out. Perhaps an Option would be better?
There's no need to take references just to compare for equality; eq takes &self.
Don't need &next or &rev when adding to get next because we no longer need these values.
reverse_str does more than just reverse; perhaps a better name is in order?
No need to collect all the arguments to an array, just use the iterator directly.

extern crate num;
extern crate time;

use num::bigint::BigInt;
use num::FromPrimitive;
use time::PreciseTime;
use std::env;

const LIMIT: u64 = 5000;

fn lychrel(number: u64) -> BigInt {
    let mut next = FromPrimitive::from_u64(number).unwrap();
    let mut rev;

    for i in 0..LIMIT {
        rev = reverse_str(&next);

        if next == rev {
            break;
        }

        next = next + rev;

        if i % 1000 == 0 {
            println!("{} iterations complete.", i)
        }
    }

    next
}

fn reverse_str(number: &BigInt) -> BigInt {
    let reverse_string: String = number.to_string().chars().rev().collect();
    let reverse_value: BigInt = reverse_string.parse().unwrap();
    number + reverse_value
}

fn main() {
    let arg = env::args().nth(1).expect("Usage: ./lychrel <number>");

    let start = PreciseTime::now();
    let input = arg.parse::<u64>().expect("Argument must be a number");
    lychrel(input);
    let end = PreciseTime::now();

    println!("Processed {} iterations in {} seconds.", LIMIT, start.to(end));
}

I think it would be interesting to convert the iteration to an iterator.


Classic DFS doesn't use any pruning. That means you should not have a list of visited nodes; Hence, my question in the comments. This means that for cyclic graphs DFS does not terminate by default which is why people commonly do pruning on visited nodes; however, revisiting nodes may be wanted, e.g. "list all paths from edge 1 to edge 5". Making the choice of using visited not only makes your graph acyclic, but rather "tree-ifys" (technical term ;-) ) it.

Assuming visited is an okay thing to do you don't want to check if node not in visited: after poping an element but rather before you insert it. It saves you the overhead of appending and popping visited nodes which can be quite substantial.

Further, visited should be a set (as stated in @Alex 's comment).

It could also be a good idea to use an actual queue object, be that collections.deque (for FIFO / LIFO) or a queue.PriorityQueue. The latter will slightly reduce performance (insert from O(1) to O(log(queue_size))), but offers a lot of added flexibility and easy scalability to graph search.

Setting the priority to: 1/depth is DFS, depth is BFS, sum(depth) (or sum(transition costs)) is Dijkstra's search, expected_cost_to_goal is greedy search, sum(transition costs) + expected_cost_to_goal is A*. I think that's a really cool property.


How to better indent multiline strings with many string formatting args?

How about this?

def log_exception(self, exc_info):

    msg = ''

    msg += 'Time:                 %s\n' % datetime.now()
    msg += 'Path:                 %s\n' % request.path
    msg += 'HTTP Method:          %s\n' % request.method
    msg += 'POST_ARGS:            %s\n' % request.form
    msg += 'GET_ARGS:             %s\n' % request.args
    msg += 'Client IP Address:    %s\n' % request.remote_addr
    msg += 'User Agent:           %s\n' % request.user_agent.string
    msg += 'User Platform:        %s\n' % request.user_agent.platform
    msg += 'User Browser:         %s\n' % request.user_agent.browser
    msg += 'User Browser Version: %s\n' % request.user_agent.version
    msg += 'Username:             %s\n' % current_user
    msg += 'Email:                %s\n' % getattr(current_user, 'email', 'no email')

    self.logger.error(msg, exc_info=exc_info)

I guess, logging an exception doesn't happen every often, so efficiency shouldn't be a concern.

Alternatively, you can emulate variable interpolation and avoid formatting altogether:

now = datetime.now()
email = getattr(current_user, 'email', 'no email')

msg = _('''\
    Time:                 {now}
    Path:                 {request.path}
    HTTP Method:          {request.method}
    POST_ARGS:            {request.form}
    GET_ARGS:             {request.args}
    Client IP Address:    {request.remote_addr}
    User Agent:           {request.user_agent.string}
    User Platform:        {request.user_agent.platform}
    User Browser:         {request.user_agent.browser}
    User Browser Version: {request.user_agent.version}
    Username:             {current_user}
    Email:                {email}
''')

self.logger.error(dedent(msg), exc_info=exc_info)


CAVEAT I am not a clojure programmer. (But hopefully you will agree with what I suggest ;))

Put all your code in functions such that all top level forms are defs. Similarly put your tests in deftest forms and run them with run-tests.

In clojure, too, extract meaningful expressions to their own functions and give them names.
Then promote baked in magic constants in them to parameters so that they are more testable, in REPL and elswhere.

You can use destructuring let to give meaningful names to a function returning a vector.

Applying these general rules

(defn longest-chain [limit]
  (loop [number 1 peak-len 0 peak-val 0]
    (if (>= number limit)
      peak-val
      (do (let [[curr-len curr-val] (count-collatz number)]
        (do (if (> curr-len peak-len)
          (recur (inc number) curr-len curr-val)
          (recur (inc number) peak-len peak-val))))))))))

(defn -main []
  (println "Longest chain is" (longest-chain 1e6)))

Here is how you can rewrite these functions using core library.

(= x 0) is (zero? x)
(zero? (mod num 2)) is (even? x)
repeatedly applying a function without explicit loop/recur is iterate.
You can use for comprehension of a range instead of loop/recur with incing a parameter.
You can also use core library functions that operate on sequences (map, reduce et al) for a more functional style.
You can use threading macros to reduce nesting levels as necessary; and to make your functions read top-down instead of more counter-intuitive inside-out.
You can use (apply max-key k coll) to get "the [value] for which (k x), a number, is greatest."

Code after above changes:

(defn count-collatz [n]
  (let [f (fn [n] (if (even? n) (/ n 2) (+ (* n 3) 1)))]
   (->> n
     (iterate f)
     (take-while #(> % 1))
     count
     inc)))

(defn longest-chain [limit]
    (->> limit
      (range 1)
      (map #(vector (count-collatz %) %))
      (apply max-key first)
      second)

Or using the fact that max-key can get arbitrary function as its first parameter, we get:

(defn longest-chain [limit]
  (apply max-key count-collatz (range 1 limit)))


I would abstract the animation logic into a high order function and the possible directions in an object, then just lookup the corresponding function for each direction, in other words:

function move(to, dir) {

  function animate(props) {
    return function() {
      $('#player').animate(props, 'slow', function() {
        $(this).attr('style', '').appendTo('#'+ to);
      });
    }
  }

  var dirs = {
    right: animate({ left: '+='+ scale }),
    left: animate({ left: '-='+ scale }),
    up: animate({ top: '-='+ (9*scale/10) }),
    down: animate({ top: '+=' + (9*scale/10) })
  };

  if (dir in dirs) dirs[dir]();
}

I fixed a few other things. You can use $(this) to refer to the element being animated in the callback and chain those methods.

Then (9*(scale/10)) is effectively the same as 9*scale/10; associative operators.

You probably need to abstract even more if you add more code; ideally you'd want separate all your logic from your DOM manipulation and create a clear data structure that you can reuse. Also think about using classes instead of IDs. Classes are more reusable and lead to simpler code.


Using Mutex to prevent multiple WPF application launches

Thing that make me more unhappy is mixing UI logic of your MainWindow class with this single instance logic that really belongs to process (and then Application).

First thing I'd do is to introduce an explicit Main() method (follow any tutorial out there) and leave MainWindow to deal with Window things. I'd then introduce a SingleInstanceApplicationLock class (pick a better name, nothing came to my mind in this moment). I'd like to use it like this:

public static void Main()
{
    using (var appLock = new SingleInstanceApplicationLock())
    {
        if (!appLock.TryAcquireExclusiveLock())
            return;

        var app = new App();
        app.InitializeComponent();
        app.Run();
    }
}

SingleInstanceApplicationLock will then be an internal sealed class implementing IDisposable (where you release resources you acquired). AcquireExclusiveLock() may even be lazy-load the mutex (I'd avoid to complicate things if unneeded but I like even less to put too much complex logic in constructors). Proof of concept:

sealed class SingleInstanceApplicationLock : IDisposable
{
    ~SingleInstanceApplicationLock()
    {
        Dispose(false);
    }

    void IDisposable.Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public bool TryAcquireExclusiveLock()
    {
        try
        {
            if (!_mutex.WaitOne(1000, false))
                return false;
        }
        catch (AbandonedMutexException)
        {
            // Abandoned mutex, just log? Multiple instances
            // may be executed in this condition...
        }

        return _hasAcquiredExclusiveLock = true;
    }

    private const string MutexId = @"Local\{1109F104-B4B4-4ED1-920C-F4D8EFE9E833}";
    private readonly Mutex _mutex = CreateMutex();
    private bool _hasAcquiredExclusiveLock, _disposed;

    private void Dispose(bool disposing)
    {
        if (disposing && !_disposed && _mutex != null)
        {
            try
            {
                if (_hasAcquiredExclusiveLock)
                    _mutex.ReleaseMutex();

               _mutex.Dispose();
            }
            finally
            {
                _disposed = true;
            }
        }
    }

    private static Mutex CreateMutex()
    {
        var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
        var allowEveryoneRule = new MutexAccessRule(sid,
            MutexRights.FullControl, AccessControlType.Allow);

        var securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);

        var mutex = new Mutex(false, MutexId);
        mutex.SetAccessControl(securitySettings);

        return mutex;
    }
}


Creating a python dataframe by parsing JSON API response

The only major thing I would change is that:

if len(item['vendors']) != 0

Is the same as:

if item['vendors']

Because an empty list will return back as False. If you want to try it out:

a = []
bool(a)      # False
b = [1,2,3]
bool(b)      # True

I would also be careful with what you have because those dictionaries that you are converting might have more than one value, in which case you would miss them. This is the line that I am referring to:

    paths = [item['paths'][0]['path_label'] for item in data]


Coding standard and Readability: Verbose/Redundant statements vs Short/Compressed

Version 1 has code duplication for one seemingly very important line:

addApp(DataStore.applicationsCache.get(bundle), preparedApps);

Duplicating this line is not a good idea if it can be easily avoided.

Version 3 is using && and || mixed in the same condition which makes it a lot harder to understand. Try to avoid mixing those two together, instead extract conditions into variables, as palacsint has done with boolean emptyQueryPub.

Version 2 is the one I like the best, but with some modifications.

Java Coding Conventions about braces is that they should be on the same line as the condition/loop and not on it's own line.

Adding a few spaces makes the code more readable.

Most IDEs has an Auto-format key-shortcut. Ctrl + Shift + F in Eclipse and Alt + Shift + F in NetBeans. I recommend using it.

The results of the above mentioned fixes:

for (int i = 0; i < resultsSize; i++) {
    bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD);
    app = DataStore.applicationsCache.get(bundle);
    if (app != null) {
        if (catalogRequest.filter.query_pub == null ||
                app.vendor.equalsIgnoreCase(catalogRequest.filter.query_pub)) {
            addApp(DataStore.applicationsCache.get(bundle), preparedApps);
        }
    }
}


In general, your idea is not bad.

The best solution, as far as I read, would be the algorithm Divide by 2 that uses a stack to keep track of the digits for the binary result.

As an intro, this algorithm assumes that we start with an integer greater than 0. A simple iteration then continually divides the decimal number by 2 and keeps track of the remainder.

The first division by 2 gives information as to whether the value is even or odd. An even value will have a remainder of 0. It will have the digit 0 in the ones place. An odd value will have a remainder of 1 and will have the digit 1 in the ones place. We think about building our binary number as a sequence of digits; the first remainder we compute will actually be the last digit in the sequence.

That said, we have:

from pythonds.basic.stack import Stack

def divideBy2(decNumber):
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString

print(divideBy2(42))

Comments regarding your code:

Why did you do this: dec_new = dec_number ? You could've just use dec_number. There's no need of assigning its value to another variable.
This: dec_new = dec_new // 2 could be as well as the above line of your code rewritten as: dec_new //= 2
The indentation should contain 4 spaces, not 2.

A version that better (than your solution) utilizes the memory would be:

def dec_to_bin(n):
    bits = []

    bits.append(str(0 if n%2 == 0 else 1))
    while n > 1:
        n = n // 2
        bits.append(str(0 if n%2 == 0 else 1))

    bits.reverse()
    return ''.join(bits)

What I did:

floor divide all the numbers by two repeatedly until we reach 1
going in reverse order, create bits of this array of numbers, if it is even, append a 0 and if it is odd append a 1.

Other ways of doing it:

Using recursion:

def dec_to_bin(x):
    return dec_to_bin(x/2) + [x%2] if x > 1 else [x]

The above solution returns the result as a list which you can later on .join() then apply int() to it.

Another idea that came to my mind is as simple as:

u = format(62, "08b")
>> 00111110


You could replace the dotimes/atoms with more functional loop/recur recursion.

(defn centroid [p]
  (let [six*area     (* 6 (polygon-area p))
        n            (count p)
        first-vertex (p 0)
        polygon      (conj p first-vertex)]
     (loop [i       0
            x-terms []
            y-terms []]
       (if (< i n)
         (let [point  (polygon i)
               point' (polygon (inc i))
               x      (point-x point)
               y      (point-y point)
               x'     (point-x point')
               y'     (point-y point')
               dxy    (- (* x y')
                         (* x' y))]
           (recur (inc i)
                  (conj x-terms (* (+ x x') dxy))
                  (conj y-terms (* (+ y y') dxy))))
         (make-point (/ (reduce + 0 x-terms) six*area)
                     (/ (reduce + 0 y-terms) six*area))))))

You could also do it through sequences entirely:

(defn centroid [p]
  (let [six*area         (* 6 (polygon-area p))
        polygon          (map (juxt point-x point-y) p) ;; turns the points in [x y] pairs
        ;; `juxt` applies each function in order and outputs the results in a list.

        polygon'         (drop 1 (cycle polygon))       ;; circular permutation of polygon
        ;; `cycle` lazily repeats and concats the input sequence.

        term           (fn [[[x y] [x' y']]]            ;; destructuring a pair of
                                                        ;; [x y] pairs
                         (let [dxy (- (* x y')
                                      (* x' y))]
                           [(* dxy (+ x x')) (* dxy (+ y y'))]))
        [x-terms yterms] (->> (map list polygon polygon') ;; makes the [point point'] pairs
        ;; when `polygon` is exhausted, the generated sequence stops, so the fact that
        ;; `polygon'` is infinite has no effect.
                              (map term)
                              (apply (partial map list)))] ;; turns the sequence of pairs
                                                           ;; into a pair of sequences
        ;; `apply` turns the list argument in an argument list that it feeds to the function
        ;; - here, a sequence of pairs. `partial` takes a function and some of its arguments
        ;; and returns it with its first arguments set - here, `map list ...`. `map list`
        ;; applied to a list of pairs will call `list` with the first elements of all pairs,
        ;; then with the seconds.

    (make-point (/ (reduce + 0 x-terms) six*area)
                (/ (reduce + 0 y-terms) six*area))))

EDIT: a(n unefficient) version with map galore:

(defn centroid [p]
  (let [six*area (* 6 (polygon-area p))
        polygon  (map (juxt point-x point-y) p)
        polygon' (drop 1 (cycle polygon))
        x        (map first polygon)
        x'       (map first polygon')
        y        (map second polygon)
        y'       (map second polygon')
        x**x     (map * x x')
        y**y     (map * y y')
        x**y     (map * x y')
        y**x     (map * y x')
        dxy      (map - x**y y**x)
        x-terms  (map * x**x dxy)
        y-terms  (map * y**y dxy)]
    (make-point (/ (reduce + 0 x-terms) six*area)
                (/ (reduce + 0 y-terms) six*area))))

A full loop/recur version:

(defn centroid [[h & t :as p]]
  (let [six*area (* 6 (polygon-area p))
        a        (point-x h)
        b        (point-y h)]
    (loop [x      a
           y      b
           t      t
           x-term 0
           y-term 0]
      (if-let [[h & t] t]
        (let [x'     (point-x h)
              y'     (point-y h)
              dxy    (- (* x y')
                        (* x' y))
              x-term (+ x-term (* dxy (+ x x')))
              y-term (+ y-term (* dxy (+ y y')))]
          (recur x' y' t x-term y-term))
        (let [dxy    (- (* x b)
                        (* a y))
              x-term (+ x-term (* dxy (+ x a)))
              y-term (+ y-term (* dxy (+ y b)))]
          (make-point (/ x-term six*area)
                      (/ y-term six*area)))))))


Question

Does the last line slow my program down?

This depends on what you intend to return when there are no pairs that sum to target.  If you leave the last line out, your program would invoke undefined behavior when control flow reaches the end of the function body, and the compiler will rightfully warn you about that.
Integer overflow
There is an edge case that your code fails to handle — integer overflow.  When the sum of nums[i] and nums[j] exceeds the range of int, undefined behavior is invoked.
Immediate improvements
Here are some improvements to your code:

nums should taken by const reference, since it is not modified inside the function.

A vector should be indexed with a std::size_t (or its size_type member type), because nums.size() might exceed the range of int.

When nums is empty, nums.size() - 1 will produce SIZE_MAX, which is typically \$2^{32} - 1\$ or \$2^{64} - 1\$.  This didn't cause a bug in this particular case, but it is definitely a logical mistake that should be fixed by, e.g., special-casing nums.size() < 2.

You don't need to construct an empty result at the beginning — construct it on the fly by using return {nums[i], nums[j]} for example.

Here's the result: (overflow check is omitted for simplicity)
#include <cstddef>
#include <vector>

std::vector<std::size_t>
find_numbers(const std::vector<int>& nums, int target) {
    if (nums.size() < 2) {
        return {};
    }

    for (std::size_t i = 0; i < nums.size() - 1; ++i) {
        for (std::size_t j = i + 1; j < nums.size(); ++j) {
            if (nums[i] + nums[j] == target) {
                return {i, j};
            }
        }
    }

    return {};
}

Generalization
The function can be made more flexible by taking an iterator pair and a functor:
#include <iterator>
#include <utility>

// returns a pair of iterators [it_a, it_b]
// such that it_a <= it_b && pred(*it_a, *it_b)
// or [last, last] if such a pair is not found
template <typename ForwardIterator, typename BinaryPredicate>
auto find_pair(
    ForwardIterator first,
    ForwardIterator last,
    BinaryPredicate pred
) -> std::pair<ForwardIterator, ForwardIterator> {
    if (first == last) {
        return {last, last};
    }

    for (auto next = std::next(first); next != last; ++first, ++next) {
        for (auto it = next; it != last; ++it) {
            if (pred(*first, *it)) {
                return {first, it};
            }
        }
    }

    return {last, last};
}

Optimization
The original algorithm runs in \$O(n^2)\$ time, which can be improved to \$O(n \log n)\$ for large inputs:

First, maintain a vector of indexes sorted by the numbers.

For each number, binary search for target - number.


Static class

As proposed by eurotrash I would not implement the class as static class because it has some disadvantages:

It is only possible to use one class per application
It is not possible to mock the class (e.g. for unit test / alternative implementations)
It is not possible to use it with DI.
It is not very common to have a statefull static classes - therefore it may confuse other developer

Naming

isLoading should be renamed to _isLoading
execute should be renamed to Execute or even better to some more descriptive name (e.g. StartConsumingTask)

Logic

  Is there any way to implement this without lock and isLoading?

Currently your solution uses up to 5 tasks that process the items from the _queue and put them into the _storageQueue. If the _storageQueue has more than 1000 items, one of the 5 tasks writes them to the repository.

If the last part (write the items to the repository) is executed by a separate single task, the lock and the isLoading flag could be dropped.

The lock and the isLoding flag can be dropped if the last part (writing the items to the repository)

Tasks

If you have long running tasks (like the one in the method Launch), it is better to start it with option TaskCreationOptions.LongRunning. Otherwise the thread for the task is taken from the threadpool and therefore blocks them for executing short-running procedures.
_queue.Add (in method AddRange) is such a fast operation. I don't see a reason why to use Parallel.For here - just add the item in the current thread.
Parallel.For in method execute makes sense if ExecuteVerificationRequest is realy time consuming - otherwise it adds only overhead and complexity.

Code with the suggestions above applied:

public class RequestQueue
{
    private BlockingCollection<VerificationRequest> _queue = new BlockingCollection<VerificationRequest>();
    private ConcurrentQueue<VerificationRequest> _storageQueue = new ConcurrentQueue<VerificationRequest>();

    private RequestQueue() { }

    public void Launch()
    {
        Task.Factory.StartNew(StartConsumingTask);
        Task.Factory.StartNew(StartPersistingTask);
    }

    public void Add(VerificationRequest request) => _queue.Add(request);
    public void AddRange(List<VerificationRequest> requests) => requests.ForEach(r => Add(r));

    private void StartConsumingTask()
    {
        Parallel.ForEach(_queue.GetConsumingEnumerable(), new ParallelOptions { MaxDegreeOfParallelism = 5 }, EnqueueSaveRequest);
    }

    private void EnqueueSaveRequest(VerificationRequest request)
    {
        _storageQueue.Enqueue(new RequestExecuter().ExecuteVerificationRequest(request));
    }

    private async Task StartPersistingTask()
    {
        while (true)
        {
            if (_storageQueue.Count > 1000)
            {
                var requestChunck = new List<VerificationRequest>();
                VerificationRequest req;
                for (var i = 0; i < 1000; i++)
                {
                    if (_storageQueue.TryDequeue(out req))
                        requestChunck.Add(req);
                }
                new VerificationRequestRepository().InsertRange(requestChunck);
            }
            else
            {
                await Task.Delay(100);
            }
        }
    }

    private static RequestQueue _instance = new RequestQueue();
    public static RequestQueue Instance => _instance;
}


Are there side-effects to having a generic Ninject factory?

Line-by-line I had exactly the same factory code. It smells, isn't it?

The correct solution would be to use Ninject Factory extension. I am happy since.


C code, rewritten to use a Person struct without pointers

This is an interesting problem. Removal of pointers can improve the safety of code. It's much more difficult in C than something like C++, though, as C doesn't have many other options like references or smart pointers. Regardless, here are some thoughts on your code.
Use Your typedefs
You've made a type definition for struct person named Who. But you only appear to be using it two of the five places where you need them. Many C programmers dislike using typedef with a struct. I am not one of those programmers. I think they make the code much nicer and easier to understand. You've made the typedef, so you should use it everywhere. Person_create() should return a Who not a struct person. Also in main() you should be creating 2 Whos, not 2 struct persons.
Removing pointers
You've said the goal was to remove pointers from your struct, but you're still using one for the name field. Why? You could make it a fixed-length array if you truly want to remove all use of pointers. You'll need to ensure that you don't copy anything too long into it, in that case, though. You could define a constant for the maximum length of a name in that case. Something like this:
const size_t kMaxNameBytes = 32;    // Maximum number of bytes including NUL terminator

struct person {
    char name [ kMaxNameBytes ];
    int age;
    int height;
    int weight;
};

typedef struct person Who;

Now you have a struct that has no pointers. It is bigger, however. The disadvantage with having no pointers is that every struct must carry all of its data within the struct leading to much larger pieces of data on the stack. If you want an array of thousands of persons, it may be too large to fit on the stack.
As mentioned above, you'll also need to be more careful with your copies of the name field, now, too. Instead of just calling w.name = strdup(name);, you'll have to do something like this:
size_t name_len = MIN(strlen(name), kMaxNameBytes - 1);
memcpy(w.name, name, name_len);
w.name [ name_len + 1 ] = '\0';

Note all the extra work you now have to do to ensure that the string doesn't go over the maximum length and that it is also properly NUL terminated. On the other hand, copying a whole person is easier because you don't have to manually copy the name string like you do in your version. You can simply memcpy() the bytes from one struct to the other because it's self-contained.
Handling Failure
Note that your code doesn't handle the failure of strdup(). If strdup() can't allocate the memory, it will return NULL. Your code doesn't check the return value and will happily set the name to NULL and keep going. This is likely to cause a memory error somewhere else in your program.


Copy Cell on Worksheet_Change event if some criteria is met

Indent everything one level inside of the Sub...End Sub block. Go one more inside of If blocks and loops.

Private Sub Worksheet_Change(ByVal Target As Range)
    ' all code starts at this level of indentation

    If condition Then
        ' one more level
    End If

End Sub

There shouldn't be more than one blank line between instructions.

Private Sub Worksheet_Change(ByVal Target As Range)
    'Conditional Formatting
    Application.ScreenUpdating = False

    If Target.Column > 6 And Target.Column < 8 And (Target.Value = "G" Or Target.Value = "Y" Or Target.Value = "R" Or Target.Value = "g" Or Target.Value = "y" Or Target.Value = "r") Then
    Sheets("Pending").Cells(1, 1).Copy

This condition can be simplified.

Target.Column > 6 And Target.Column < 8

means the same thing as Target.Column = 7. Same goes for

Target.Column > 4 And Target.Column < 6

That can simply be Target.Column = 5.
I don't normally advise using line continuations, but they can be justifiably used to reduce the amount of horizontal scrolling.

If Target.Column = 7 And _
    (Target.Value = "G" _
        Or Target.Value = "Y" _
        Or Target.Value = "R" _
        Or Target.Value = "g" _
        Or Target.Value = "y" _
        Or Target.Value = "r") Then

    Sheets("Pending").Cells(1, 1).Copy

    Call ChangeG
End If

That last change brought to light the fact that you want to match on upper or lower case versions of these letters. Using VBA's Like operator will help clean that up with some built in pattern matching.

If Target.Column = 7 And Target.Value Like "[GgYyRr]" Then

    Sheets("Pending").Cells(1, 1).Copy

    Call ChangeG
End If

Note that it cleans it up so well, that the line continuation isn't needed anymore.
Don't use the Call keyword. It's unneeded and archaic. It's simply a leftover from an ancient version of VBA.
The second condition is a little harder to clean up, but we can still use Like to make it better.

If Target.Column = 5 And _
    (Target.Value Like "[Hh]igh" _
        Or Target.Value Like "[Mm]edium" _
        Or Target.Value Like "[Ll]ow") Then

    Sheets("Pending").Cells(1, 1).Copy
    ChangeE
End If

You've hard coded the string literal for the "Pending" sheet twice. It would be better to initialize a Worksheet variable upon entering the event routine.

Dim sourceSheet As Worksheet
Set sourceSheet = Worksheets("Pending")

Note that I used the Worksheets collection instead of Sheets. That's because the Sheets collection can contain charts as well as worksheets. It's a rare issue, but it can be one.

And there ya go. All cleaned up.

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.ScreenUpdating = False

    Dim sourceSheet As Worksheet
    Set sourceSheet = Worksheets("Pending")

    If Target.Column = 7 And Target.Value Like "[GgYyRr]" Then
        sourceSheet.Cells(1, 1).Copy
        ChangeG
    End If

    If Target.Column = 5 And _
        (Target.Value Like "[Hh]igh" _
            Or Target.Value Like "[Mm]edium" _
            Or Target.Value Like "[Ll]ow") Then

        sourceSheet.Cells(1, 1).Copy
        ChangeE
    End If

    Application.ScreenUpdating = True
End Sub

One last thing that I have not addressed, but was mentioned in the comments by Tim Williams. There is a potential bug waiting to rear its ugly little head. Target can be a multi-cell range object and Range.Value is not available in multi-cell ranges. You need to be prepared to deal with that situation should it arise. Consider the example below.

Public Sub test()
    Dim Workbook As Workbook
    Set Workbook = ThisWorkbook

    Dim sheet As Worksheet

    'Set sheet = Workbook.Worksheets("Sheet1")
        Set sheet = Workbook.Worksheets(1)

    Dim rng1 As Range
    Set rng1 = sheet.Range("C2")

    Dim rng2 As Range
    Set rng2 = sheet.Range("C2:C10")

    Debug.Print rng1.Value ' prints the value stored in C2
    Debug.Print rng2.Value ' raises type mismatch error #13

End Sub


This is a very nice, well commented and well structured code!

Your comments in the start are exactly how they should be. You already know this, but I'll say it anyway. Writing a function where you have comments like this in the start aids the user because help functionName will provide the information needed in order to use the function.

There's is only one minor thing I would do differently. You know the end points, and how many steps there are. You have two options:

Calculate the step-size and use it to create a vector with the correct number of steps using colon
Just use what you know directly in linspace

Instead of calculating re_step and do reals = limits(1) : re_step : limits(2); you can use linspace:

reals = linspace(limits(1), limits(2), image_size(1));
imags = linspace(limits(4), limits(3), image_size(2));

The following comment is incorrect: "% Transpose so that plot will have reals on the x axis"

You are working with complex numbers, and in those cases, ' is the complex conjugate transpose, not the regular transpose. I don't know if you want the transpose or the complex conjugate transpose, but it's nice to keep in mind.


Looks pretty good! Here's a couple of pointers for you:

It's custom to declare jQuery variables with a $ prefix. This way it's easy to tell at a glance that it is a element collection. So your top variables would look like this:

var $secondsDiv = $("#seconds");
var $minsDiv = $("#mins");

Instead of:

  if (timer===false)

Consider:

if (!timer)

If you're looking for legibility there are probably a few other things I'd do differently.

Grouping your variables allows you to make a few shortcuts:

var time = {
  seconds: $("#seconds"),
  minutes: $("#mins"),
  hours:   $("#hours")
}

function getValue(timeStr) {
  return time[timeStr].html();
}

getValue('seconds')

And I'm not sure about the check59() implementation. I'm sure we could make that more efficient, and reduce the repetition.

But the next step for you is definitely to create a class for this and scope your variables, that way you'll be able to include multiple timers in the same page :)


Map coloring with MRV and Degree heuristics in Python

Although not familiar with MRV and degree heuristics, i can make some remarks about the Python code style:

Loops can be made more Pythonic

for i in range(len(self.adjacencyList[initialNode])):
    childNode = self.adjacencyList[initialNode][i]

should be written as:

for childNode in self.adjacencyList[initialNode]:

Conditionals

if(self.isSafe(childNode, c) == True):

should be

if self.isSafe(childNode, c):

method isSafe

def isSafe(self, node, c):
    for i in range(len(self.adjacencyList[node])):
        if(self.color[self.adjacencyList[node][i]] == c):
            return False
    return True

could be:

def isSafe(self, node, c):
    for adjacency in self.adjacencyList[node]:
        if self.color[adjacency] == c:
            return False
    return True

or even, more Pythonic, but a bit cryptic:

def isSafe(self, node, c):
    # return True if all node neighbours colors differ from c
    return all([self.color[adj] != c for adj in self.adjacencyList[node]])

Data structure

The repetition of the keys in the adjacencyList and color
suggest a data structure like the following, although this requires a
lot changes in the existing code:

nodes = {
    'WA' : {'color' : 0, 'neighbours' : ['NT', 'SA']},
    'NT' : {'color' : 0, 'neighbours' : ['WA', 'SA', 'Q']},
    'SA' : {'color' : 0, 'neighbours' : ['WA', 'NT', 'Q', 'NSW', 'V']},
    'Q'  : {'color' : 0, 'neighbours' : ['NT', 'SA', 'NSW']},
    'NSW': {'color' : 0, 'neighbours' : ['SA', 'Q', 'V']},
    'V'  : {'color' : 0, 'neighbours' : ['SA', 'T', 'NSW']},
    'T'  : {'color' : 0, 'neighbours' : ['V']},
}

Others:

self.nodeSequence is not used
self.totalNodes is not used
minCount = 0 was edited out in getNodeWithMRV but should be there, or if (countColor < minCount) should be if (countColor < 0)
pickNode is called only once with a constant argument '', and can therefor be made simpler
getNodeWithMRV will always return '' because countColor will never be smaller than 0.
the ; at the end of adjacencyList = ... and color = ... an origin in another language :-)


Zero-padding a number to have six digits

function foobar(n)
{
    var zeroes = "000000";
    return zeroes.substr(n.length) + n.toString();
}


Pretty way of keeping sensitive info out of a logged command string in Ruby?

I see two more security issues with this code.

Executing a string rather than an array of command and parameters

When building a command line programmatically, it is dangerous to build it as a string, especially when any of the parameters comes from user input.  When calling Kernel#system with a string, a shell interprets the command line; when calling it with an array, the operating system kernel executes the command directly.

In the benign failure case, the password might contain a space, in which case the shell would interpret it as two parameters, probably causing your command to be invoked incorrectly.  In the worst case, the user could trigger an arbitrary command execution vulnerability.

As an illustration, the following code will do more than just set your password to "hello":

password_file = '.htpasswd'
username = 'CHK'
password = 'hello; touch me; grep; unzip; strip; finger; fsck -y; more; yes; yes; yes; umount; sleep'
command = "htpasswd -b -c #{password_file} #{username} #{password}"
system(command)

Practice safer computing!  This is not vulnerable to arbitrary command execution:

command = ['htpasswd', '-b', '-c', password_file, username, password]
system(*command)

Passing sensitive information on the command line

Even if you manage to censor the logger within Ruby, it's still considered dangerous practice to pass any sensitive information as a command-line parameter.  Command lines are visible to all users on a machine.

For that reason, all reasonable commands should offer an alternative mechanism to accept secret information.  For example, the recommended way to use htpasswd, since Apache 2.4, is to read the password from standard input.

command = ['htpasswd', '-i', '-c', password_file, username]
IO.popen(command, mode='w') do |htpasswd|
  htpasswd.puts(password)
end

Similarly, here is an example of how to securely specify a passphrase to GnuPG (in Python).

In summary, by passing the secret information through pipes instead of the command line, you solve both the log censorship problem and the machine-wide command-line visibility problem.


Simple IPv4 and port validation for chat client

Naming

By convention, variables local to a method should be camelCased. You seem to have a mixture of PascalCased and alllowercase, making it hard to see at a glance what a variable is. All lower case has the additional disadvantage of being hard to read.

Your boolean check variables also seem to be named in the form 'VerbNoun'. This is rather confusing because it's usually how methods are named. It sounds like they're supposed to do something. ValidatePort for example sounds like something that validates a port. A name like portValid or perhaps isPortValid more clearly states what the variables are.

Extracting methods

Looking at both of your methods, they have the same structure: Check if something is valid, if it is then change the state of the form one way, if it isn't then change the state of the form a different way. Each of those are basically completely separate pieces of functionality, so I'd suggest separating them out. This would turn textBox3_Leave, for example, into:

private void textBox3_Leave(object sender, EventArgs e)
{
   bool ipValid = ValidateIP(textbox3.Text);
   if(ipValid)
       EnableControls();
    else
       DisableControls();
}

Here the new methods ValidateIP, EnableControls and DisableControls would be private methods containing the bits of code they replace.

This method now immediately states what it is doing: it's validating the text in textbox3as an IP, if it's valid then enable the controls, otherwise disable them. Potentially you could get rid of ipValid and just put that ValidateIP call directly into the if statement, it's up to you what you think reads better. You may also be able to improve on those names a bit (enable which controls, for example).

Repetition

Now look at the second method. You'll see that EnableControls can be used here too. This means that just by making the first method a clearer statement of what it's doing, we've discovered a valuable abstraction, and we no longer have to repeat that enabling controls means enabling button2 and button3.

We can almost use DisableControls too, but there's a slight difference- the messages. So to fix that, DisableControls should take the message as a string parameter:

private void DisableControls(string message);

Integer parsing

It's generally considered bad to use exceptions in normal control flow. That's what you're doing here when you try to check whether the text in textbox4 is a valid integer or not.

An alternative, which you may not have known about, is Int32.TryParse. This method is designed for this exact situation- where you want to check whether a string represents an integer, but don't want to throw an exception if it isn't. This allows you to get rid of that try...catch and clean that bit of code up a bit.

Simplifying if statements

If you ever have an if statement which reads:

if(condition)
{
    value = true;
}
else
{
    value = false;
}

You should simplify this to:

value = condition;

In your case, you can do:

ValidatePort = porttest > 1 && porttest < 65535


Why not use functools.partial to simplify further and avoid the if use_proxy a second time?

Something along the lines of

if use_proxy:
    func = functools.partial(
            LoadUrlProxy,
            proxy_client=CreateProxyClient(),
            proxy_params=GetProxyParams())
else:
    func = functools.partial(LoadUrl, timeout=_EXECUTOR_TIMEOUT)

with futures.ThreadPoolExecutor(max_workers=_MAX_WORKERS) as executor:
    future_to_url = {
            executor.submit(func, image): image
            for image in image_list
    }

    for future in futures.as_completed(future_to_url):
        image = future_to_url[future]
        try:
            images.append((image.master_id, future.result()))
        except Exception as exc:
            logging.exception('%r Generated an exception: %s', image.url, exc)


How to sort two array of objects using Underscore.js?

Or you can do it without a function at all:

sortBy   _.sortBy(list, iterator, [context])
Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iterator.  Iterator may also be the string name of the property to sort by (eg. length).

var sorted1 = _.sortBy(O1, 'name'),
    sorted2 = _.sortBy(O2, 'name');


Including a file (is this safe and effective?)

As it uses the basename function it should be safe enough.

One note though: I would personally always have a lookup table (PHP "array") for whitelisting files unless there is a very specific reason not to do so. That way I will have full control and the result should be the same for the user - as a side effect it is way way more easy to have shorter names and/or aliases for files later on.


Don't create a new process for every task. Put a loop in add_messages; q.get will wait for the next task in the queue.
receive_new_message is not doing anything useful in your example. Place q.put(new_message) right after raw_input instead.

:

def add_messages(q):
    while True:
        # Retrieve from the queue
        message_to_add = q.get()
        print "(Add to DB)"

if __name__ == "__main__":
    q = multiprocessing.Queue()
    p_add = multiprocessing.Process(target=add_messages, args=(q,))
    p_add.start()

    while True:
        input_message = raw_input("Type a message: ")

        # Add the new message to the queue:
        q.put(input_message)

        # Let the processes catch up before printing "Type a message: " again. (Shell purposes only)
        time.sleep(1)


Be the Man in the middle, and (ARP) Poison your network

The heredoc uglyness can be avoided with either:

The textwrap.dedent function; or
Using a module docstring such as

"""
Arp-poisening tool by @Ludisposed
Works on both Python2 and Python3
This tool is made for Unix(Kali) OS

Usage:
arper.py interface target_ip gateway_ip

Example:
python arper.py wlan0 192.168.1.70 192.168.1.1
"""

from scapy.all import *
import os

…

def main():
    try:
        interface = sys.argv[0]
        target_ip = sys.argv[1]
        gateway_ip = sys.argv[2]
    except:
        print(__doc__).strip()
        sys.exit(1)
    …

You could also improve your arguments parsing using existing tools: argparse in the standard library or click or docopt to name a few. Using argparse, your code could become:

"""
Arp-poisening tool by @Ludisposed
Works on both Python2 and Python3
This tool is made for Unix(Kali) OS
"""

import os
import sys
import signal
import argparse
import ipaddress
import threading

from scapy.all import *

…

def main(interface, target_ip, gateway_ip):
    packet_count = 1000

    # Sets the ipv4 to enable port_forwarding
    os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
    conf.verb = 0
    …

def parse_command_line():
    parser = argparse.ArgumentParser(
            description=__doc__,
            epilog='Example: python arper.py wlan0 192.168.1.70 192.168.1.1')
    parser.add_argument('interface', help='<some helpful description>')
    parser.add_argument('target_ip', type=ipaddress.ip_address, help='…')
    parser.add_argument('gateway_ip', type=ipaddress.ip_address, help='…')
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_command_line()
    main(args.interface, args.target_ip, args.gateway_ip)

However, usage of the ipaddress module makes it require Python 3.3 at least. You could stick with strings but would get less checks done on the input.


My proposal, please see also the comments in the code.

require 'zlib'
MAX_FILE_SIZE = 1024 #One KB

#Use a glob to get all log-files
Dir["#{Dir.pwd}/*.log"].each do |f|
  #skip file, if file is small
  next unless File.size(f) > MAX_FILE_SIZE
  #Make a one line info
  puts "#{f}: #{File.size(f)/1024}KB, created #{File.ctime(f)} modified #{File.mtime(f)} "

  # zipping the file - each log in a file
  Zlib::GzipWriter.open("arch_#{File.basename(f)}.gz") do |gz|
    gz.mtime = File.mtime(f)
    gz.orig_name = File.basename(f) #filename without path
    #File.read should be fine for log files. Or is there a reason for IO.binread
    gz.write File.read(f)
    puts "File #{f} has been archived"
  end

  #deleting the file
  begin
    #~ File.delete(f)
    puts "File #{f} has been deleted"
  rescue Exception => e
    puts "File #{f} can not be deleted"
    puts "       Error #{e.message}"
    puts "======= Please remove file manually =========="
  end
end

Remark:

This solution creates one gz-file per log file. Your old solution created one arch_log.gz. If there were two log-files, the 2nd would overwrite the 1st.