Updated bash/zsh function that cd to the root of git tree

This is looking great.  Thanks for incorporating the previous improvements and coming back for another round of review.  I noticed a few new things this time:

What does printf '%s' do for you that echo -n wouldn't?  Using printf when you're just passing through a string seems a little odd to me.  It should work either way, but printf would be more idiomatic for C where echo is much more common in shell scripts.
Adding the x constants in the comparison [[ "x${git_root}" != "x./" ]] are not needed.  Using the double square brackets deals with the disappearing variables.  You would need the extra x for [ comparisons because empty arguments become non-existant arguments which causes an error when you try to compare the non-existant to something.
I would use -n in the if [[ "$super_root" ]]; then line like so: if [[ -n "$super_root" ]]; then to make clear what you're trying to do there.


It should be at least one .swf, .gif or .jpg processing to occur. If not, it's not an allowed file format.

The way try to check this is not so good:

    String files = allFiles.toString();
    if (files.contains("swf") || files.contains("jpg") || files.contains("gif")) {
        return false;
    }

You should not rely on the .toString() implementation to verify values.
You should use the values. I suggest to rewrite like this or similar:

for (String filename : allFiles.values()) {
    if (filename.endsWith(".swf") || filename.endsWith(".jpg") || filename.endsWith("gif")) {
        return false;
    }
}

This loop iterates over the values, and I replaced the .contains check with .endsWith, which seems to be more accurately matching what you really want to check. Another alternative to write the condition:

if (filename.matches(".*(\\.swf|\\.jpg)$")) {
    return false;
}

  I described the best in the code but I have cyclomatic complexity. Any idea on how I can reduce?

It seems you want to reduce cyclomatic complexity of the method.
The main contributors to the high cyclomatic complexity in your example:

many return statements
many if conditions
many && and || operators

One way to reduce cyclomatic complexity is to extract some parts of the method to another method, for example:

if (allFiles.isEmpty() && validacao.getSpec() == null) {
    return true;
} else if (validacao.getSpec() != null) {
    return false;
} else if (!allFiles.isEmpty()) {
    if (containsMediaFiles(allFiles)) {
        return false;
    }
}
return true;

I just invented the helper method containsMediaFiles,
and eliminated a for loop and some || conditions.

But in this particular example, there's an even easier way.
Realize that you don't really need to check if allFiles is not empty.
You can just loop over it, and if it's empty,
there will be nothing to loop over, so the empty case will be automatically handled, like this:

private boolean directoryIsEmpty(OldValidacao validacao) {
    Map<String, String> allFiles = validacaoService.getFilenameMap(validacao.getArquivoPath());

    if (allFiles.isEmpty() && validacao.getSpec() == null) {
        return true;
    }

    if (validacao.getSpec() != null) {
        return false;
    }

    for (String filename : allFiles.values()) {
        if (filename.matches(".*\\.(swf|jpg|gif)$")) {
            return false;
        }
    }

    return true;
}

@ismael-miguel made a good point in comments that probably you want to match extensions like "JPG", and even "JPg". An easy way to do that is to convert filename to lowercase before the .matches call above. And you might want to add more patterns, for example jpeg, or use the pattern jpe?g to take care of both "jpeg" and "jpg" at the same time.


Bash script to reconfigure the screen orientation when entering or exiting tablet mode

Good

I like most of what you've done so far as is:

Using [[ (double square brackets) for conditionals is a good practice.
Using $() for command substitution instead of the classic backticks is also a good modern shell practice.
Most of your variable substitutions are quoted.  This is a good habit in case the variable contains spaces it won't get broken up by shell parsing.

Could be better

There are some minor things I'd improve:

include the #! line at the top
typically you see folks add their thens to the end of the previous line like if [[ cond ]]; then.  Your outer loop could also be done as while true; do.
the comment gets sort of lost out on the right.  Why not put it on the line above?

Think about

The script is getting invoked every second and chewing up some amount of CPU.  There's probably not much CPU being burned in this case, but one thing to consider is whether this sort of polling could be avoided.  Linux includes inotify as a function to let processes known when a file has changed so they don't have to constantly check the file themselves.  This is available in the shell through inotifywait.  If the file you're checking works with inotifywait you could avoid the sleep.

A bonus you get beyond conserving CPU from skipping sleep is that the script should run with lower latency.  Instead of needing to wait for up to a second to detect the change your script would be invoked within a small fraction of a second.


Finding the maximum of an array to solve a rope-burning puzzle

Space complexity

In terms of space, you can solve this in \$O(1)\$ space.
In other words, you don't need upper, lower, and result arrays.
You can calculate the rolling max while parsing the values of upper and lower without storing them.

Time complexity

You are performing \$N\$ operations several times, where \$N\$ is the total length - 1:

scan the elements of upper
scan the elements of lower
find the max of upper - lower pairs
find the max of the max values

That looks like \$O(4N)\$. If you rewrite as I suggested, without extra storage and calculating the rolling max as you go,
this can be reduced to \$O(2N)\$, since only the first two traversals remain, which is inevitable to read the input.

That being said,
since \$O(4N)\$ and \$O(2N)\$ are of the same magnitude (linear),
I'd be surprised if this made a difference for the time limit exceeded result.
Usually TLE happens when there is a magnitude of difference between the expected solution and the actual (for example quadratic instead of linear).

Extra tips

Use an enhanced for loop when you don't need the value of the index.
For example instead of:

          for(int i = 0; i < result.length; i++){
            if(maxVal < result[i]){
                maxVal = result[i];
            }
          }

Write as:

          for(int val : result) {
            if(maxVal < val){
                maxVal = val;
            }
          }

These loop conditions are identical, but written differently:

         for(int i = 0; i < totalLength - 1; i++){
         // ...
         for(int i = 0; i <= totalLength - 2; i++){
         // ...

It's easier to read if you adopt a more consistent writing style.

Instead of doing all the work in the main method,
it would be better to decompose this to multiple methods.
In the decomposed solution you should have a method that takes some input (possibly even a Scanner),
and return some output instead of printing it directly.
When written that way,
unit testing becomes possible.
And then of course, add some unit tests.


Can this Google Hurdles code be made to run any faster?

There are some general notes about the code, not really performance improvements (however, I have not tested their performance). I guess the real bottleneck could be in the browser/OS/hardware which can't handle more key events.

Anyway, these do not need any other thread:

final long endTime = System.nanoTime()
    + TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS);
while (endTime > System.nanoTime()) {
    robot.keyPress(KeyEvent.VK_RIGHT);
    robot.keyRelease(KeyEvent.VK_RIGHT);

    robot.keyPress(KeyEvent.VK_LEFT);
    robot.keyRelease(KeyEvent.VK_LEFT);
}

final long endTime = System.nanoTime()
    + TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS);
while (endTime > System.nanoTime()) {
    for (int i = 0; i < 100; i++) {
        robot.keyPress(KeyEvent.VK_RIGHT);
        robot.keyRelease(KeyEvent.VK_RIGHT);

        robot.keyPress(KeyEvent.VK_LEFT);
        robot.keyRelease(KeyEvent.VK_LEFT);
    }
}

Maybe these were your first tries too.

Here is a 3rd one with a ScheduledExecutorService:

public static void main(final String[] args) throws AWTException {

    final ScheduledExecutorService scheduledExecutorService =
        Executors.newScheduledThreadPool(1);
    final Runnable stopCommand = new Runnable() {
        @Override
        public void run() {
            run = false;
        }
    };
    scheduledExecutorService.schedule(stopCommand, 10, TimeUnit.SECONDS);

    final Robot robot = new Robot();

    while (run) {
        robot.keyPress(KeyEvent.VK_RIGHT);
        robot.keyRelease(KeyEvent.VK_RIGHT);

        robot.keyPress(KeyEvent.VK_LEFT);
        robot.keyRelease(KeyEvent.VK_LEFT);
    }
    scheduledExecutorService.shutdown();
}

A final note from Clean Code, page 25:

  Classes and objects should have noun or noun phrase names like Customer, WikiPage,
  Account, and AddressParser. [...] A class name should not be a verb.

I'd name it HurdleRunner, for example.


Encoding special characters in URLs with Ruby

Unless you need the unencoded url (for logging?), I would just:

encoded_url = "http://somewiki.com/index.php?book=#{CGI.escape(author)}:#{CGI.escape(title)}&action=edit"


Select non-task workorders, but include the costs of the tasks

I know you say that

I plan to use the view for multiple reports. So I've included all 265 columns in the view via select *

but given the truly absurd column count in that table, I would consider a select-splat to be a very last resort. Are you able to narrow this at all?
Generally your query seems sane. Since you say that the following columns are non-nullable,
sum(actlabcost) + sum(actmatcost) + sum(actservcost) + sum(acttoolcost)

should be equivalent to
sum(actlabcost + actmatcost + actservcost + acttoolcost)


bool end_of_word;
    Node(): end_of_word(false) {}

This would be probably more idiomatic simply written as

    bool end_of_word = false;

Next,

    explicit Trie(std::vector<std::string>);

is probably more idiomatic written as

    template<typename Itr> Trie(Itr begin, Itr end);

Next,

    std::unique_ptr<Node> root;

Why is it allocated on heap? It's a private member owned by this object, by putting it on heap you simply get some (noticeable) dereference overhead, and that's all.

Same goes for branches: there's no point in keeping child Nodes on heap, std::unordered_map<char, Node> is quite sufficient for a tree, with no additional  overhead.

Trie::Trie() {
  root = std::unique_ptr<Node>(new Node());
}

Trie::Trie(std::vector<std::string> words) {
  root = std::unique_ptr<Node>(new Node());

Irrespective of what's said above about root's type, such initializations are better put in initialization lists:

Trie::Trie(): root(new Node) {}

And if you upgrade to C++14, recall that make_unique is the new new

Trie::Trie(std::vector<std::string> words)
  : root(std::make_unique<Node>())
{

Next,

  for (const char & key : word) {

char type is small enough to be bound by value. Scalar and small POD types, when passed by reference, can create unnecessary overhead so it is better written as

  for (char key : word) {

(or even

  for (auto key : word) {

which makes perfect sense if you ever decide to make character type a parameter to your Trie.)

    auto found = it->children.count(key);
    if (!found)
      return false;
    it = it->children[key].get();

In C++, even with unordered containers, it is better done as

    auto where = it->children.find(key);
    if (where == it->children.end()) return false;
    it = where->second.get();

And similarly for Insert().

Which, by the way, I would declare as

  Trie &Insert(const std::string &);

But that is more like a personal preference.

How about adding a method that searches for all the elements whose keys start with a given prefix, and returns them either as a subnode, or a fresh container, like list or vector?

And the final boss: define an iterator type for your trie.


You sort the cows, but you don't take advantage of the fact that they're sorted.  Instead of iterating over the cows multiple times (which leads to \$\mathcal{O}(n^2)\$ time w.r.t. the number of cows), iterate over the sorted list once.

Unfortunately, I can't think of an easy way to do this using Python's built-in data structures.  However, if we assume that CowTupleList is some list-like datastructure that has \$\mathcal{O}(\log{n})\$ or better performance for all operations (including del), then we can use binary search to find the largest cow that will fit in a cart's remaining capacity:

def greedy_cow_transport(cows,limit=10):
  # Sort cows from largest to smallest
  CowTupleList = sorted(cows.items(), key=lambda x: x[1], reverse = True)

  while CowTupleList:
    # Add first (largest) cow to a new cart
    name,weight = CowTupleList[0]
    cart = [name]
    remaining_capacity = limit - weight

    # Remove first cow from list
    del CowTupleList[0]

    # Find largest remaining cow that fits in remaining capacity (if any)
    idx = find_largest_fitting(CowTupleList, remaining_capacity)
    while idx is not None:
      # Add the cow at idx to the cart
      name,weight = CowTupleList[idx]
      cart.append(name)
      remaining_capacity -= weight

      # Remove cow at idx from list
      del CowTupleList[idx]

      # Find largest remaining cow that fits (if any)
      idx = find_largest_fitting(CowTupleList, remaining_capacity)

    # No more cows fit => yield the cart
    yield cart

Assuming find_largest_fitting is implemented as a binary search over CowTupleList (and an appropriate data structure is chosen for CowTupleList), this should take \$\mathcal{O}(n\log{n})\$ time.  If linear search is used for find_largest_fitting and/or Python's build-in list type is used for CowTupleList (so that del operates in \$\mathcal{O}(n)\$), then this algorithm will operate in \$\mathcal{O}(n^2)\$ time.


Handling lazy-loading webpages using vba

You may want to try this below. First is to try reduce loading times, especially images and videos when scrolling down. Then have a counter to count number of "StretchedBox" elements before the scroll down, then check up to a few more attempts until no more changes (I used 5 in code). You can remove the Debug lines in final version.

Note some "StretchedBox" isn't really an article headline (video related), you will need to work on those to filter out junk.

Option Explicit

Sub Web_Data()
    Const TITLES As String = "StretchedBox"
    Dim sh As Object, regval As String

    ' Change IE Options
    Set sh = CreateObject("WScript.Shell")
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\Display Inline Images"
    sh.RegWrite regval, "no", "REG_SZ"
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\Enable Browser Extensions"
    sh.RegWrite regval, "no", "REG_SZ"
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\Play_Animations"
    sh.RegWrite regval, "no", "REG_SZ"
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\EnableAlternativeCodec"
    sh.RegWrite regval, "no", "REG_SZ"

    ' Prepare IE
    Dim IE As New InternetExplorer, html As HTMLDocument
    Dim posts As Object, sText As String
    Dim TitlesCount As Long, NoChangesCount As Integer, Row As Long

    With IE
        .Visible = True
        .navigate "https://finance.yahoo.com/"
        Debug.Print Now, "Navigated Start"
        Do Until .readyState = READYSTATE_COMPLETE: Loop
        Debug.Print Now, "Navigate Complete"
        Set html = .document
    End With
    NoChangesCount = 0
    On Error Resume Next
    Do
        DoEvents
        Application.Wait Now() + TimeValue("00:00:02")
        ' Remove all the annoying video parts
        RemoveVideos html
        TitlesCount = GetClassCount(html, TITLES)
        Debug.Print Now, TitlesCount
        html.parentWindow.scrollBy 0, 99999
        If TitlesCount = GetClassCount(html, TITLES) Then
            NoChangesCount = NoChangesCount + 1
        Else
            NoChangesCount = 0
        End If
    Loop Until NoChangesCount = 5 ' If no changes for some attempts, assume end of dynamic page
    On Error GoTo 0
    Columns("A").ClearContents
    For Each posts In html.getElementsByClassName(TITLES)
        sText = WorksheetFunction.Clean(posts.ParentNode.innerText)
        'sText = Trim(posts.ParentNode.innerText)
        If Len(sText) > 0 Then
            Row = Row + 1
            Cells(Row, 1).Value = sText
        End If
    Next posts
    IE.Quit
    ' Restore IE Options
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\Display Inline Images"
    sh.RegWrite regval, "yes", "REG_SZ"
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\Enable Browser Extensions"
    sh.RegWrite regval, "yes", "REG_SZ"
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\Play_Animations"
    sh.RegWrite regval, "yes", "REG_SZ"
    regval = "HKCU\Software\Microsoft\Internet Explorer\Main\EnableAlternativeCodec"
    sh.RegWrite regval, "yes", "REG_SZ"
    Set sh = Nothing
End Sub

Private Function GetClassCount(Doc As HTMLDocument, ClassName As String) As Long
    GetClassCount = Doc.getElementsByClassName(ClassName).Length
End Function

Private Sub RemoveVideos(Doc As HTMLDocument)
    Dim oElement As Object
    For Each oElement In Doc.getElementsByClassName("yvp-main")
        oElement.innerHTML = ""
    Next
End Sub


This function will run every x seconds.

That's great. But without more context, there is no way we can identify any potential issues with the code you've provided.

Private Sub Start()

Depending on what the containing class is called, that method's name isn't very clear. And why is it Private? Who's calling it? A method like Start() sounds like something that belongs on the public interface; I'm confused.

If I were maintaining this code, I would remove every single comment you have there. Why? Because every single one of these comments is restating what the code does, and good comments should say why the code does what it's doing.

  I create the Objects Maker and Transmitter in a PAN namespace to group the functionality. Is this wise?

It looks like you have very specialized objects, and that is very good thing. Whether or not they deserve their own namespace isn't something that can be commented on, because we have no idea what other things you have here: for all I know every type involved in what you've shown could be in the same namespace, it depends on the scope of your application: if it's an ERP system with 4,327 other functionalities, then yes, definitely put that in its own namespace. If it's a specialized application that only deals with "PAN" files, I don't know.

  I decide to use a method to set the data it needs before it can create the PAN file, rather than using a constructor. What is the preferred method in this case?

I'm guessing you're referring to this line:

Baker.SetIngredients(GetAPIData)

What's GetAPIData? It looks like it could be a member call (a property getter?), or a field - in either case, the name is a bad one: GetAPIData would be a name for a method. Without seeing its declaration, it's very hard to tell what's going on here - heck, it could even be a delegate (in which case the name isn't too bad after all).

The point is, if it's just data, then there's no reason to not pass it through the constructor. If it's work to do, then you've done the right thing: constructors shouldn't do work.

  Am I using too many Objects to handle these tasks, when a more procedural structure would do?

That's primarily opinion-based, but VB.NET, like C#, has an object-oriented paradigm; procedural "script-like" code would work, but if you want SOLID code, it just won't do.

Again, we have no idea what your objects are actually doing, so it's not possible to give you an answer here, but if your objects essentially are made of one or two one-liner methods, OOP is probably overkill.

  Is the naming of the Baker and Transmitter confusing because they differ from the Objects name?

I'm confused here. Baker is an object name:

Dim Baker As New PAN.Maker

And Transmitter is a type name:

Dim PANSender As New PAN.Transmitter(GetFTPDetails)

PAN looks like it's a class name, and Transmitter would be a nested type - I don't like this. If PAN is a namespace, it's a bad name and Transmitter shouldn't be fully-qualified like this.

Dim PAN As PANv1 = Baker.GetPAN()

The local variable PAN confuses things even further - is it the same PAN as seen in PAN.Transmitter? That makes Transmitter a shared method, and that's starting to smell.


Reduce global variables

The game_type function can return the ship row and column, there is no need to modify them as global variables, my suggestion is easy to implement:

def game_type(game_input):
    if game_input == 1:
        ship_row = random_row(board)
        ship_col = random_col(board)
    elif game_input == 2:
        ship_row = int(raw_input("Choose a Row to place your battleship:"))
        ship_col = int(raw_input("Choose a Column to place your battleship:"))
    else:
        print "That is not a valid input.  Please try again"
        return game_type(int(raw_input("To play against the computer press 1, to play against a friend press 2: \n")))
    return ship_row, ship_col

ship_row, ship_col = game_type(int(raw_input(
    "To play against the computer press 1, to play against a friend press 2: \n")))

Also, columns is only ever used inside print_board so I would define it as a default parameter, to make it clear that the rest of the program does not need it:

def print_board(board, columns = ["  0", "1", "2", "3", "4"]):
    print "\t\t", "   ".join(columns)
    for row_num, row in enumerate(board):
        print "\t\t", row_num, "   ".join(row)

First define, then "do stuff"

Organization is a nice property  of code. Now you mix function definitions and code that "does things" (namely code that interacts with the user).

I would define at first all of the functions, and then run them.

Write a function for input checking

The main logic (now incorporated into main battleship_game function) is full of checks to make sure that the input is valid, abstracting the input checking to another function will condensate the top-level logic.

Costumize

After you define a battleship_game function, you can have fun customizing it by passing all kinds of different parameters: the board size, the number of turns, whether to run in debugging mode or not...

This will allow you to play slightly different battleship games by using the same code.

Use enumerate

99% of the times manually incrementing a counter is not needed in Python:

def print_board(board, columns = ["  0", "1", "2", "3", "4"]):
    print "\t\t", "   ".join(columns)
    for row_num, row in enumerate(board):
        print "\t\t", row_num, "   ".join(row)

Using built-ins is usually simpler than writing your own.

Avoid do-nothing lines

In Python the line:

value

Where value may be anything, does nothing. In your code the line

turn

Does nothing at all, remove it to simplify the code.

List comprehension + _

A list comprehension is preferred over append in simple cases, _ signifies that you are not interested in the value.

board = [["-"] * 5 for _ in range(5)]

Remove unused definitions

row_num is defined but never used, so delete the line:

row_num = ["0", "1", "2", "3", "4"]

Use the range that fits your needs best

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |
 |  Return a sequence of numbers from start to stop by step.
 ...

Using the second version of range will avoid incrementing afterwards:

for turn in range(1, 5):
    print "Turn", turn

I also find it more obvious this way that turns are 1-indexed.


You can use Array#min and Array#max to calculate the win/lose streak;
You don't need to use self on getters;
And you can use user.update instead of assigning and calling .save;
I would also rename the win_streak column to streak;

def adjust_streak
  streak = case result
           when 'Win'  then [user.streak, 0].max + 1
           when 'Loss' then [user.streak, 0].min - 1
           end

  user.update streak: streak
end


Project Euler Problem 12 - triangle number with 500 divisors

There is an error in your countDivisors() function, the result is one too large
for a perfect square, i.e. countDivisors(25) returns 4 instead of 3.
Also the loop variable i should be a long to avoid an integer overflow
when testing i*i <= number.
 A correct version would be

public static long countDivisors(long number) {
    long divisors = 0;
    for (long i = 1; i*i <= number; i++) {
        if (number % i == 0) {
            if (i*i < number) {
                divisors += 2; // i and number/i are (different) divisors
            } else {
                divisors += 1; // i == number/i is a divisor
            }
        }
    }
    return divisors;
}

The run() function can be simplified slightly, the boolean go variable
is not really necessary:

public static void run() {
    long number = 1;
    long nextNum = 2;
    int maxDivisors = 500;
    while (countDivisors(number) <= maxDivisors) {
        number += nextNum;
        nextNum++;
    }
    System.out.println("The first triangle number with over "+maxDivisors+" divisors is: "+number);
}

To improve the performance, use the fact that

triangle numbers are of the form \$ n \, (n+1)/2  \$, and
the "number-of-divisors function" \$ \sigma_0(n) \$ is multiplicative,
i.e. \$ \sigma_0(m \, n) =  \sigma_0(m) \, \sigma_0(n) \$ if \$ m, n \$
are relative prime (see Divisor Function).

If \$ n \$ is even then \$ n/2 \$ and \$ n+1 \$ are relative prime,
and if \$ n \$  is odd then \$ n \$  and \$ (n+1)/2 \$ are relative prime.
This leads to the following implementation

public static void run() {
    long n = 1;
    int maxDivisors = 500;
    while (countDivisors((n+1)/2) * countDivisors(n) <= maxDivisors) {
        n++;
        if (countDivisors(n/2) * countDivisors(n+1) > maxDivisors) {
            break;
        }
        n++;
    }
    long number = n*(n+1)/2;
    System.out.println("The first triangle number with over "+maxDivisors+" divisors is: "+number);
}

which is faster because the countDivisors() function is called with smaller
numbers. On my computer it reduces the time from 0.6 to 0.02 seconds.

A faster implementation of countDivisors() would use the prime
factorisation of the given number, as explained in the above referenced
Wikipedia article.


C# is not my main language, so I apologize for any mistakes that may exist in the following code.

There is quite a bit of duplication in this class. It seems like LogMessage(), EngineMessage() and ExceptionMessage() could all delegate to CustomMessage(). For example:

public static void LogMessage(string msg)
{
    CustomMessage("LOG", msg);
}

// etc ...

It also looks like the same string is being built twice in each function. It would be better to create the string once. Maybe something like this instead:

string logMsg = String.Format("[{0}][{1}]: {2}", EngineName, title, msg);
Console.WriteLine(logMsg);
logdata.Add(logMsg);

title.ToUpper();

Does this work? I would not expect this to modify the string in place, but rather return a new string. You probably need to do this:

title = title.ToUpper();

With the above changes:

public static void LogMessage(string msg)
{
    CustomMessage("LOG", msg);
}

public static void EngineMessage(string msg)
{
    CustomMessage("ENGINE", msg);
}

public static void ExceptionMessage(Exception e)
{
    CustomMessage("EXCEPTION", msg);
}

public static void CustomMessage(string title, string msg)
{
    string logMsg = String.Format("[{0}][{1}]: {2}", EngineName, title.ToUpper(), msg);
    Console.WriteLine(logMsg);
    logdata.Add(logMsg);
}


What is the expected behaviour if you add one weekday to a Saturday? Possible answers are: throw an exception, behavior is undefined, Monday, or Tuesday. Make a decision, and document it.

The use of var funcName = function(…) { … } is a bit unconventional compared to function funcName(…) { … }, but it's not wrong.

Other than that, I think that the code looks correct.  For a more efficient way to add large intervals, you could add a number of integral weeks (7 * Math.floor(days / 5)) and advance the remainder (days % 5) the slow way.


Tying the enablement of one checkbox to another using AngularJS and jQuery

Is there an obvious cleaner way of doing this [?]

Without knowing where the element(s) with class name inklogin exist, it can only be presumed that it exists as a child of the element with ng-controller="controller" (or however the controller is named). If that is incorrect, please update your post to include that HTML output (from the ASPX code).

Given the presumption above, jQuery can be eliminated by adding ng-disabled (bound to user.ExtraData.userPermissions.notary.allowed) to the input with class inklogin. Bearing in mind that you stated you attempted this, perhaps there was something wrong with the setup. Below is a working example of this:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.user = {
      Details: {},
      SignatureText: ''
    };
    $scope.amendNotary = function(value) {
      if (value === true) {
        $scope.user.Details.HasPassword = true;
      } else {
        $scope.user.SignatureText = "Signature:";
      }
    };
  }).directive("dwCheckbox", function($rootScope) {
    return {
      restict: 'E',
      require: 'ngModel',
      template: '<input name="name" type="checkbox" ng-model="model" />',
      scope: {
        model: '=ngModel',
        name: '=name'
      },
      link: function(scope, element, attrs, ngModel) {

        //render the field according to the mode and the current value of the model
        function render() {};
      }
    };
  });

  Enable INKWRX Login:
  <dw-checkbox class="notarylogin" name="UserHasPassword" ng-model="user.Details.HasPassword"></dw-checkbox>

  Notary:
  <dw-checkbox name="notary" id="notary" ng-model="user.ExtraData.userPermissions.notary.allowed" ng-click="amendNotary(user.ExtraData.userPermissions.notary.allowed)"></dw-checkbox>

Signature Text:

  Element with class "inklogin":
  <input type="checkbox" class="inklogin" ng-disabled="user.ExtraData.userPermissions.notary.allowed" />

  or is mixing jQuery with Angular generally regarded as okay?

Generally it is acceptable, though each library requires extra resources (e.g. download size, time, etc.). There are whole websites about removing the need for jQuery, like http://youmightnotneedjquery.com/. if you were working on a team, some teammates might prefer to have as few libraries as possible


chmod all .htaccess files under all website dirs under public_html dir

Instead of manually scanning each files and directory and testing if they are a directory using pushd, I would directly try to target .htaccess files using find:

find "$HOME"/public_html/*.{com,co.il} -name ".htaccess"

Then, to apply the proper permissions, you can use the -exec option of find:

find "$HOME"/public_html/*.{com,co.il} -name ".htaccess" -exec chmod 644 {} \;


Naming
QuickSort is not a simple algorithm, and naming things helps to make it more readable. Unfortunately, with descriptive names, if you name things wrong it makes it worse than if you you use cryptic names. Your recursive method is:

private static <T extends Comparable<? super T>> void quickSort(List<T> array, int start, int arrayLength){
    if(start < arrayLength){
        int q = partition(array, start, arrayLength);
        quickSort(array, start, q);
        quickSort(array, q+1, arrayLength);
    }
}

But, arrayLength does not mean array length, it means "end-exclusive", or "ignore-from" or something.
One of the common tricks in the quickSort is to use the actual index of the last element in the partition, instead of the length. For example, you call the method with:

quickSort(list, 0, list.size());

But, what if you called it with:
quickSort(list, 0, list.size() - 1);

Then named your parameters:
    private static <T extends Comparable<? super T>> void quickSort(
            List<T> array, int start, int end) {

Now you have start and end, and you do not need to do the immediate offset adjustment in the partition method.
Now, with that simple adjustment, the code becomes more readable simply because the variables do what they say, and don't lie to you.
Exchange
Your exchange method is good, no major problems there (with some caveats though... we will get to those...)
exchange is a decent name, but convention would call it swap...., give it decent index names, and common convention would be to put the indices after the reference:
private static <T extends Comparable<? super T>> void exchange(
        List<T> array, int left, int right) ....

Partitioning
Note, your current partition method is:

private static <T extends Comparable<? super T>> int partition(List<T> array, int end, int arrayLength){
    T last = array.get(arrayLength-1);
    int i = end-1;
    for(int j = end; j < arrayLength-1; j++){
        if(array.get(j).compareTo(last) <= -1 || array.get(j).compareTo(last) == 0){
            i = i+1;
            exchange(j, i, array);
        }
    }
    exchange(arrayLength-1, i+1, array);
    return i + 1;
}

Notice what happens if we give it decent variable names, and use the 'end' instead of the arrayLength
private static <T extends Comparable<? super T>> int partition(
        List<T> array, int first, int last) {
    T key = array.get(last);
    int smaller = first - 1;
    for (int test = first; test < last; test++) {
        if (array.get(test).compareTo(key) <= 0) {
            smaller++;
            exchange(smaller, test, array);
        }
    }
    smaller++;
    exchange(last, smaller, array);
    return smaller;
}

For a start, notice the condition:

if (array.get(test).compareTo(key) <= -1
        || array.get(test).compareTo(key) == 0) {

can be reduced to just:
if (array.get(test).compareTo(key) <= 0) {

All values up to smaller are smaller or equal to key.
Your code makes some sense to me now.
Note, the algorithm you use to partition the data is a little unconventional... though I can't see a real problem with it.
A conventional approach would have a left and right index that progress from the ends, and then swap values from each side, and meet in the middle somewhere. Your approach is OK, though.
Putting it together
With these changes, putting it all together, you will need to change the calling routines:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
    quickSort(list, 0, list.size() - 1);
}

private static <T extends Comparable<? super T>> void quickSort(List<T> array, int left, int right){
    if(left  >= right) {
        return;
    }

    int q = partition(array, left, right);
    quickSort(array, left, q - 1);
    quickSort(array, q + 1, right);
}

private static <T extends Comparable<? super T>> int partition(
        List<T> array, int first, int last) {
    T key = array.get(last);
    int smaller = first - 1;
    for (int test = first; test < last; test++) {
        if (array.get(test).compareTo(key) <= 0) {
            smaller++;
            exchange(smaller, test, array);
        }
    }
    smaller++;
    exchange(last, smaller, array);
    return smaller;
}

private static <T extends Comparable<? super T>> void exchange(int j,
        int i, List<T> array) {
    T temp = array.get(j);
    array.set(j, array.get(i));
    array.set(i, temp);
}

public static void main(String[] args) {
    List<String> data = new ArrayList<String>(System.getProperties().stringPropertyNames());
    sort(data);
    for (String d : data) {
        System.out.println(d);
    }
}

Foot Notes
Note that your code has horrible performance on List instances that are not random-access... Consider someone who feeds your code a LinkedList... it will perform badly because each time you get or set with an index, it has to scan the data for the value.
RandomAccess is an interface available on collections that support fast and easy index-based access.
The Java implementation solves sorting non-RandomAccess Lists by dumping all the data in to a different RandomAccess list, sorting that, and then copying it back again, something like:
if (list instanceof RandomAccess) {
    sort(list);
} else {
    List<T> toSort = new ArrayList<>(list);
    sort(toSort);
    list.clear();
    list.addAll(toSort);
}


Multiple if-statements with overwriting lists

You could do something like this:
possible_combinations = ["ABC", "AB", "A", "D"]
combs = [("A","C"),("A",),("C",)]

for comb in combs:
    chosen_comb = [x for x in possible_combinations if all([y in x for y in comb])]
    if len(chosen_comb) > 0:
        break

print(chosen_comb)


In my opinion, your method does not have too many lines, but the line calling Net::SSH.start is too long.

My terminals and text editors are 80 characters wide, so I would split the long line into 2 lines

      Net::SSH.start(@tunnel_ip, @tunnel_username, keys: @tunnel_key_name,
                     verify_host_key: false) do |ssh|

If you must reduce the number of lines, you can move some lines into new methods. The extra method calls will make spaghetti of the control flow, so the code will be difficult to read and understand, but it might satisfy your cop.

    def tunnel_run(cmd)
        retries = 0
        code = tunnel_run_command(cmd)
        abort ... if code != 0
    rescue Net::SSH::ConnectionTimeout
        ...
    end

    private
    def tunnel_run_command(cmd)
        code = nil
        Net::SSH.start(...) do |ssh|
            the_channel = ssh.open_channel do |channel|
                channel.exec do |ch, success|
                    code = tunnel_run_channel(ch, success)
                end
            end
            the_channel.wait
        end
        code
    end

    def tunnel_run_channel(ch, success)
        code = nil
        raise ... unless success
        ch.on_data { ... }
        ch.on_extended_data { ... }
        ch.on_request("exit-status") { ... }
        code
    end

Beware that the private methods tunnel_run_command and tunnel_run_channel will pollute the method namespace in all objects that extend Tunnelable.  Privacy in Ruby is by object, so the object inherits the private methods from Tunnelable, and Ruby allows the object to call those methods.

The names tunnel_run_command and tunnel_run_channel must not conflict with other methods of the object.


Replace each whitespace in a string with "%20"

This one really fits well for a regular expression:

public static string ReplaceAllSpaces(string str) {
  return Regex.Replace(str, @"\s+","%20");
}

The expression \s+ consists of the pattern \s that matches a whitespace character (which is more that just spaces, as noted by @tinstaafl), and the quantifier + which means "at least once".

The pattern matches "one or more whitespace characters", so it will match each group of whitespace characters (for example the six spaces between My and Name in the example) and replace it with %20.


ToString() and AddString() method without using .Net Collections

ListOfString = null; is useless, fields get initialized to default(T) which is null for reference types. So you can drop the constructor.

For simple initializations you can use inline initializers. e.g.

private string ListOfString = "";

You're hiding ToString() instead of overriding it.
You're ignoring empty input strings, the spec doesn't require that. Curiously you're not ignoring null input strings.
Using a string as accumulator leads to quadratic runtime since it has to create a new string which contains all current data for each append.

Use StringBuilder.Append in Add instead. Don't return a string from Add, else you lose the performance advantage. Call stringBuilder.ToString() in your ToString operation. This has linear runtime.
You're returning null if no value has ever been added. I'd expect the empty string instead.

I don't know what they meant by calling your code "not detailed enough". You could add documentation for corner cases, possibly in the form of unit tests. For my observations 3 and 5 it's not clear if your code is behaving like you intended. Documentation and/or unit tests would have clarified your intent.


I don't know Ruby, and cannot infer how similar are the algorithms (if they are significantly different, there is no sense to compare performance). However I can point some performance problems in the go code.

The range loop

    for i, v := range a {
        if v%factor == 0 && v > factor {
            a[i] = 0
            modified = true
        }
    }

does a lot of unnecessary tests. A (more controlled) for loop seems to suite better:

    for i := factor*factor; i < 10000000; i += factor {
        a[i] = 0
    }

The search for next prime starts from the very beginning of a - rendering the search effectively quadratic. There is no need to search an initial [0, factor] slice; start with factor + 1:

    for _, v := range a[factor + 1:] {


Permutations with repetitions algorithm in R

This is one of many instances where people would be tempted to say, "see, loops in R are slow".  And my response is, "loops aren't that slow, but you can put slow code in loops."

There's no reason res needs to be a data.frame.  Leave it as a matrix and your code runs in under a second on my laptop.

# initialize res
res <- matrix(rep(NA,totCombs*totChars),ncol=totChars)

The lesson here is:

  If you don't need the multi-typed columns of a data.frame, use a matrix.

You might look into factoradics as another possible algorithm. That would allow you to generate permutations in lexicographic order.


I think your initial analysis into classes and interfaces is not quite right. I go by the mantra "if you can kick it, then it should be a class instance" (apologies to the purists out there). You can definitely kick a door, so there should be a class Door which will have methods for open(), close() and lock(), plus listeners for onOpen(), onClose() and onAlarm(). A constructor like Door(int id) sounds about right, allowing you to give the door a primary key.

The manager class should maintain a list of doors, and do the work required to:

route incoming commands from the socket interface to the appropriate door instance
send outgoing events from doors to the socket interface.

The Door class should not know that the socket implementation exists. Your DoorConnectionIF interface is likely superfluous.

But it is good to see someone understanding why God invented listeners. Many experienced programmers misunderstand what listeners are designed for, and end up with tangled circular references between classes.


Calculating luma of a rect in an image of .yuv format

One of the reasons that large 2d data sets are often reduced to a single 1D array is so that you can process the data in a single loop and the memory is contiguous. The trick to processing this data efficiently in a single loop is to be able to fiddle the single pointer in a way that makes sense...... and to do that, we need some smart pointer skips...

Consider the following single loop. It starts at the right place, and then skips the areas outside the sample rectangle....

int startpos = top * imageWidth + left;
int lastpos = bottom * imageWidth + right;
// skip is the amount of unsampled data from the right-side of the sample
// rectangle to the left side of the next row.
int skip = imageWidth - right + left;

// limit is a moving limit that we use to break-process the samples.
// limit only applies if we actually need to skip data.
int limit = skip == 0 ? lastpos + 1 : (top * imageWidth) + right;
for (int i = startpos; i <= lastpos; i+= AVERAGE_LUMA_SAMPLE_SIZE ) {
    if (i > limit) {
        // take the loop-increment in to consideration.
        i += skip - AVERAGE_LUMA_SAMPLE_SIZE;
        limit += imageWidth;
    } else {

        // Do the sampling work here.....

    }
}

Normally I am against updating a loop-counter index inside the loop, but there are times when it makes sense. This is one of those times.

Note, the skip variable is being calculated naively in this code. It should be smarter about taking the sample-size into consideration, and making sure it hits the beginning of the sample rectangle properly on the next line.... as it stands, if the rectangle is an odd-size, it may cause the start position of the next row to not be on the rectangle boundary. On average, I don't think this will make a difference, but that is your call.


Your code actually isn't terrible, but there are a few places where it can be improved.

First, the ref. It's entirely unnecessary in this case. What I'd change to keep everything immutable:

Change your declaration at the top to just:

(def initial-state [[false false false false false]
                    [false false true  false false]
                    [false false true  false false]
                    [false false true  false false]
                    [false false false false false]])

This now defines, as the name suggests, the initial state of the game. This will no longer be used to store the running state.

Now, you can change tick to get rid of the need for ref-set:

(defn tick [state times]
  (loop [i 0 ; Moved the counter into a loop
         acc-state state] ; Keeping track of the running state
   (when (< i times)
     (println (str i ":"))
     (pretty-print acc-state)

     ; Recur into the loop instead of the function itself
     (recur (inc i) (next-state acc-state)))))

(defn -main [& args]
  (tick initial-state 5))

Note how I just made the running state an accumulator of a loop. I think the whole design should be rethought though. Really, you could just get the successive states by using iterate, and take as many as you want. Lets say you want to get the first five states after the initial-state:

(take 5 (iterate next-state initial-state))

Now, your entire tick function can basically be written as:

; Obviously, change 5 to however many states you want to produce
(doseq [state (take 5 (iterate next-state initial-state))]
  (pretty-print state))

I would change pretty-print to a format style function that returns a string instead of printing directly. That way, the caller can make use of your prettying, but decide how/when they want to display it.

Your count-true-neighbors function is huge. I'd break it down into a few discreet parts:

You have a part that produces a list of neighbors to check
You have a part that does bounds checking

I'd change it to something more like:

(defn neighbors-of [x y]
  (for [p (range (- x 1) (+ x 2))
        q (range (- y 1) (+ y 2))
        :when (not (and (= x p) (= y q)))]
    [p q]))

(defn inbounds? [x y size]
  (and (<= 0 x (dec size)) ; Comparison operators can be chained!
       (<= 0 y (dec size))))

(defn count-true-neighbours [state x y]
  (let [size (count state)]
    (->> (neighbors-of x y)
      (map (fn [[p q]] ; You can deconstruct here directly
             (when (inbounds? p q size)
               (get-state state p q))))
      (filter true?)
      (count))))

Your mapping function could be changed to:

(map (fn [[p q]]
       (and (inbounds? p q size)
            (get-state state p q))))

Although the benefit here is subjective.

Things to note:

<= and other comparison operators can be used to check more than two arguments! I'm making use of that in inbounds? to neaten it up a bit.
I reduced your bounds check in the map down to (when (inbounds? p q size) ...). when returns nil (falsey) if the condition fails, so you don't need to explicitly return false.

(or (= alive-neighbours 2) (= alive-neighbours 3)))

Can also be written as:

(#{2 3} alive-neighbors)

It's a matter of style which you prefer. I prefer the latter personally.

(nth (nth state y) x))

Can also be written as:

(get-in state [y x])

There's a few things to note in pretty-print:

(reduce str strings)

Isn't wrong, but a more idiomatic way of writing it would be:

(apply str strings)

With:

(mapv #(if %1 "■ " "□ "))

You add explicit spaces after the display characters. It may be cleaner to use join to add the spaces. This limits the repetition, and gets rid of the trailing space. This also lets you just use the character literals directly.

And when you use threading macros (->>), you put the expression being threaded on the next line. Personally, I prefer to put the threaded expression on the same line as the ->>. This makes it clearer what's being threaded.

Taking that all together, I'd write that whole bit as:

(->> (nth state i)
     (mapv #(if %1 \■ \□))
     (s/join " ")
     (apply str)))

Where s is an alias for clojure.string.


Increasing size of video thumbnail on mouseover

Why not use the :hover pseudo class and have that trigger the size change? Probably easier than having to worry about event binding.
http://jsfiddle.net/nhzNM/

<iframe class="videoPlayer" width="560" height="315" src="http://www.youtube.com/embed/90Omh7_I8vI?controls=0&rel=0" frameborder="0" allowfullscreen></iframe>
<style type="text/css">
.videoPlayer {
    width: 560px;
    height: 315px;
    -webkit-transition: height,width 1s ease;
    -moz-transition: height,width 1s ease;
    -ms-transition: height,width 1s ease;
    -o-transition: height,width 1s ease;
    transition: height,width 1s ease;
}

.videoPlayer:hover {
    width: 650px;
    height: 365px;
}
</style>

You could use the same setup for a thumbnail positioned in front of the video embed.


Node constructor

It seems odd that we can only provide rvalues as argument to the constructor.  I'd expect to be able to pass by copy, too.

The usual way to allow that is to accept a T by value, and move-construct data from that value:

Node(T value = T()) : data(std::move(value)) {}

Note two other changes there: I've added a default argument, so we don't need to write a default constructor, and I've omitted the initialization of next, as we wrote a suitable default initializer for it.

List constructor

If we provide an initializer for head, we don't need to write a default constructor.

We might want to accept a list of elements when creating a linked list.  That would look something like this:

LinkedList() = default;
LinkedList(std::initializer_list<T> elements)
{
    for (auto& e: elements)
         insert(std::move(e));
}

Pointer ownership

We need to be absolutely clear that every object created with new has exactly one owner, that knows when the object is no longer in use and will delete it at that point.  When moving nodes from one list to another, it is essential that the ownership is transferred - if both lists think they are owner of a node, it will be double-deleted, and if neither lists does, it will be leaked.

We can write code to do this manually, but it's easier and less error-prone to #include <memory> and then make use of the smart pointer types that are provided for us.


You do not provide a testable function that performs the task of returning the desired answer for a specific test case. It is the ace handling that you intermangled with your test code. The main structure of your program structure should look somewhat like

def calculate_player_hand(player_hand_input):
    #[...]
    return score

def read_tests():
    #[...]
    return testcases, answers

for test, answer in zip(read_tests()):
    assert answer == calculate_player_hand(test)

Completely separate the functionality you want to provide from the tests. even split into different files.


Positives

Your function docstring was informative and helped me understand the code better.
Good use of variables like cursor_up to manage the ANSI control characters

Small improvements

As long as you're bringin in colorama, can you use any of the named constants in provides instead of the control characters?
If you need to do something multiple times, I like to see if there's a good way to do n times instead. See if you can make the number of turns more configurable.
I'm not sure what you're doing with line = cursor_up_ask + answer_sz + cursor_up. This would be a good place for a comment or a function with a clear name.
You're taking len(answer), but shouldn't that always be 1? My understanding is that you're expecting a one-digit answer. It would be nice to have some error handling so that, e.g. 23 isn't treated as a valid guess.
You could eliminate the pool global by wrapping it and your functions together in a class. You could also eliminate the global by having more focused functions.
Instead of doing a find-replace on the * in MSG_TRY, you can do something like this:

MSG_TRY = '\033[91mTry again {}\033[0m'
msg_wrong = msg_wrong.format(hint)

Larger gripes

I'm finding the flow of the program hard to follow. Consider breaking it down into smaller functions so it's more clear what's going on. It could look something like:

def play_one_turn(final_turn = False):
    guess = get_player_input()
    if guess == right_answer:
        print(OK_MSG)
        return True
    if not final_turn:
        show_hint(guess)
    else:
        print(MSG_ANS)

(I'm not saying this is the best way to do things. It's showing how smaller well-named functions can give more clarity with the same structure)

exit() in the middle of a function is suspicious. (Is the code missing from sys import exit?) I'd expect to see it at the end of a main function to return a status code back to the user. It should not be used for control flow. It would make more sense to return True or False depending on whether the guess is correct, and let the caller manage things from there.


Does this unit test cover all edge cases?

As far as I can see the
@RequestParam
annotation can have a defaultValue parameter - once that's used the
method becomes a bit simpler:

@RequestMapping(method = RequestMethod.GET)
public List<Tags> getAllTags(@RequestParam(value = "query", required = false) String query,
        @RequestParam(value = "limit", required = false, defaultValue = "10") int limit,
        @RequestParam(value = "start", required = false, defaultValue = "0") int start,
        @RequestParam(value = "approved", required = false, defaultValue = "true") boolean approved,
        @ActiveLanguage Language language,
        @ActiveUser User user) {
    if (query != null) {
        return tagService.findTagsByQuery(user, query, limit, start, language, approved);
    } else {
        return tagService.findTags(user, limit, start, language);
    }
}

I'd also consider some edge cases for query, like the empty string or
a string with just whitespace for that matter.

Now for the unit tests, the naming could probably be improved, but I
also don't pay that much attention to it to be honest.

If the tagsList (or any other part like mocking methods etc.) is a
common thing in the tests consider moving it into the setUp method (or
equivalent) so it doesn't clutter up the test methods.

The assertSame is fine, you're basically just testing whether the
object is passed through directly, however the "not null" tests
afterwards are useless - tagsList shouldn't (can't) be null, so why
is it being verified here?

times(1) is default for Mockito, so leave it out.  Also the
verifyNoMoreInteractions is a bit discouraged in general since it
might make tests more brittle than they'd have to be, also since you're
not gaining much from it here I'd leave it out too.

IMO since this is at the outermost layer I'd rather have an integration
tests that actually checks the parameter parsing and validation too -
this particular test doesn't have that much value considering you're
just passing through values.


Reading a long file and getting sum of chars by multithreading

Before starting to talk about threads in Python, let's compare to a sequential implementation. I’ll start by building a test file using the following code:

import string
import random

with open('test.txt', 'w') as f:
    for _ in range(20000000):
        line = ''.join(random.choice(string.printable) for _ in range(random.randint(0, 10000)))
        print(line, file=f)

This is Python 3 syntax, and I could not recommend more to use it instead of the end-of-life Python 2.7.

Anyway, after a while, I have a 5.9G file of 64 or so million lines (yes, string.printable contains the newline character) so I stopped it. Let's read it and count the length of its lines.

For starter (and you may have noticed in the snippet above), you should use the with statement to open files so you don't accidentally forget to close them. You can also iterate directly over the content of the file instead of using next; and if you want to know the line number (to spawn a thread each 200000 lines, for instance), you can always delegate the task to enumerate. This way, you’ll avoid using range instead of xrange and consume memory where you don't need to.

Second, timing should be done using timeit for better precision and less boilerplate. Let's start by timing the reading of the file only to get a ballpark figure of how much time we can expect to gain. We’ll use part of the consume recipe from itertools:

from collections import deque

def read_file(filename):
    with open(filename) as f:
        deque(f, maxlen=0)

if __name__ == '__main__':
    import timeit
    time = timeit.timeit('read_file("test.txt")', 'from __main__ import read_file', number=1)
    print('execution took {}s'.format(time))

Result is execution took 41.8203251362s on my machine. This is roughly as fast as I can expect the file to be read… without taking caching into account. If we change the timing part to min(timeit.repeat('read_file("test.txt")', 'from __main__ import read_file', number=1, repeat=5)) we get somewhere around 3.5s.

Now, on to counting characters. As I read it, you want to remove the newline character that is found at the end of each line. You can, as you do here, subtract 1 from each line length; or, alternatively, sum each line length and subtract the amount of lines afterwards. The second approach is easier as we can use map to produce a list of all line lengths and then, sum it before subtracting its len:

def count_characters(filename):
    with open(filename) as f:
        line_lengths = map(len, f)
    return sum(line_lengths) - len(line_lengths)

Timings approaches the same 40s figure for a single execution, but is about 6.5s on repeated executions. This is only 3 seconds of counting characters in 64 million lines; that's somewhat acceptable, but map is building a list in memory which is 64 million items long, so maybe we could speed things up if we didn't:

def count_characters(filename):
    count = 0
    with open(filename) as f:
        for line in f:
            count += len(line) - 1
    return count

Unfortunately, a for loop in Python is slower than a for loop in C (which is what map does) so this code is not faster (albeit being roughly as fast).

Now, trying to speed things up. To parallelize tasks on chunk of data, we usually use map from multiprocessing.Pool. But serializing this much data to feed other processes takes time and isn't worth it. So we are left trying to use threading as you did. However, due to the GIL, you will not be able to run more than one thread in parallel and will be either reading the file or summing the lines; exactly as it is done in sequential code, but you’ll have more overheads due to using threads and helper data structures to move data around. So all in all, for this kind of problem, you’re better off sticking to the sequential implementation.

But let's analyze your code anyway:

The l parameter is useless, since it's an integer, it is immutable and the local version on each thread won't interfere with others so passing it as a parameter with seemingly a value of 0 and then resetting it to 0 after the computation is useless;
Contrarily, the length list as a global variable is more problematic, I’d rather pass it as a parameter, leading to the threaded functions being:

def count_characters_in_chunk(lines, accumulator):
    length = sum(len(line) - 1 for line in lines)
    accumulator.append(length)

As said previously, organizing lines into chunks without prior knowledge of its length can be done using enumerate but we need to account for the last chunk not being the full size, if any:

def count_characters_in_file(filename, chunk_size=200000):
    threads = []
    lengths = []

    with open(filename) as f:
        lines = []
        for line_number, line in enumerate(f, start=1):
            lines.append(line)
            if line_number % chunk_size == 0:
                t = threading.Thread(target=count_characters, args=(lines, lengths))
                t.start()
                threads.append(t)
                lines = []

        if lines:
            t = threading.Thread(target=count_characters, args=(lines, lengths))
            t.start()
            threads.append(t)

    for t in threads:
        t.join()
    return sum(lengths)

However, there is still two issues with this code:

The repetition of thread management is ugly and error-prone, plus the manual handling of the lines list is unnecessarily verbose. You can use itertools.islice to simplify all that;
The use of a simple list to store resulting lengths is a bad habit to have as threaded code is prone to race-conditions (although highly unlikely in this case) that can lead to loss of data. You should use a Queue.Queue instead.

Final code being:

import itertools
import threading
import Queue

def extract_from_queue(queue):
    while not queue.empty():
        yield queue.get()

def count_characters(lines, accumulator):
    length = sum(len(line) - 1 for line in lines)
    accumulator.put(length)

def count_characters_in_file(filename, chunk_size=200000):
    threads = []
    lengths = Queue.Queue()

    with open(filename) as f:
        while True:
            lines = list(itertools.islice(f, chunk_size))
            if not lines:
                break
            t = threading.Thread(target=count_characters, args=(lines, lengths))
            t.start()
            threads.append(t)

    for t in threads:
        t.join()
    return sum(extract_from_queue(lengths))

if __name__ == '__main__':
    import sys
    count_characters_in_file(sys.argv[1])

But timings using caching indicates 44 seconds on my machine, so not really worth it given the speed and simplicity of the sequential implementation.


Based on tapajos comment, I was able to to refactor the code using initializers. First I created one to load the configuration file:

APP_CONFIG = YAML.load_file(File.expand_path('../../config.yml', __FILE__))

Then I created another initializer, like this:

superfeedr_config =  {
      :host     => APP_CONFIG["general"]["hostname"],
      :login    => APP_CONFIG["superfeedr"]["username"],
      :password => APP_CONFIG["superfeedr"]["password"]
}

Rails.configuration.middleware.use Rack::Superfeedr, superfeedr_config do |superfeedr|
    Superfeedr = superfeedr
    superfeedr.on_notification {|notification| Article.create_from_raw_notification(notification)}
end

I also applied the logic described in this SO question to ensure the load order: How do I change the load order of initializers in Rails 3?.


I recommend practicing Python 3 rather than Python 2 these days.

According to PEP 8, isClean() should be is_clean().

One or more of your loops could be replaced by some use of the any() function.  Note that this suggests that an is_explicit() function would be a more natural concept than an is_clean() function.

I would expect song lyrics to contain a mixture of uppercase and lowercase.  Words may be delimited by punctuation as well as spaces.  Therefore, words = line.split(" ") is probably too naïve.  Furthermore, I would expect each song to be short enough to fit entirely in memory very comfortably, so processing each file line by line is an unnecessary complication.

I would rewrite the program to use a regular expression instead.

import re

explicit_words = [
    …
]

is_explicit = re.compile(
    r'\b(?:' +
        '|'.join(re.escape(w) for w in explicit_words) +
    r')\b',
    re.IGNORECASE).search

def main():
    with open(raw_input("Enter path to song: ")) as song:
        print("EXPLICIT" if is_explicit(song.read()) else "CLEAN")

if __name__ == '__main__':
    main()

The way I chose to write the is_explicit() function above might show too much Haskell influence for some Python programmers' taste.  Here's a more conventional way of writing it:

def is_explicit(text):
    return re.search(
        r'\b(?:' +
            '|'.join(re.escape(w) for w in explicit_words) +
        r')\b',
        text,
        re.IGNORECASE
    )


Sliding window over a 2D vector, implementation of Marching Squares algorithm

A couple miscellaneous things.

I don't think you need the vector<int> for the initialization. eg:

matrix.push_back({ 1, 1, 1, 1, 1, });

You can use references in the for loops, just for good measure. IMO using the type instead of auto makes it easier to read when it's a simple type too.

for (auto& contour_row : contourMatrix)
{
    for (int& element : contour_row)
    {
        std::cout << element << '\t';
    }
    std::cout << std::endl;
}

In CreateContourMatrix() the row vector can come out of the for loop. Use .clear() or .fill() on it inside the loop, then you aren't reallocating.


Rolling 100-sided "dice" until they are the same number

You have an off-by-one error.  If you get lucky and get a matching pair immediately, then you would report "Random number that matched was: …, after 0 rolls."  I would say that "after 1 roll(s)" would be the right way to report that.  (Alternatively, you could phrase it as "after 0 mismatched rolls".)

Naming could be improved slightly.  I suggest:

rollcountlist → roll_counts, because it's shorter and more readable.  Since englishisnotgerman, you should use an underscore, as recommended by PEP 8.
rollList → roll_values, because "values" makes it clearer what is being stored.  Watch your capitalization consistency.
averageroll → average_value and averagerollcount → average_count, for similar reasons.
totalrolls → experiment_count, because totalrolls sounds like it represents a cumulative sum of rollcount, which it isn't.  Introducing the term "experiment" makes it clear that you are counting something else.
roll → roll1 and rolltwo → roll2, for consistency.  Or, as I've done below, make one two-element tuple called rolls.

The if conditions after the while loops are superfluous.  The inner loop can only be exited when the roll values match.  The outer loop can only be exited after 500 experiments.

Counting loops can be more elegantly expressed.  For a fixed number of iterations, such as for the outer loop, use the idiom for i in xrange(n): ….  For an unbounded count, such as for the inner loop, use for i in itertools.count().

In Python 2, the / operator performs integer division (rounding down) when dividing an integer by an integer.  For a more accurate mean, convert at least one of the operands to a float first.

When interpolating an integer into a format string, use the %d placeholder instead of %s for clarity.

from itertools import count
import random

roll_values = []
roll_counts = []
for experiment_count in xrange(1, 501):
    for roll_count in count(1):
        rolls = (random.randint(1,100), random.randint(1, 100))
        if rolls[0] == rolls[1]:
            break
    roll_values.append(rolls[0])
    roll_counts.append(roll_count)
    print "Random number that matched was: %d, after %d rolls." % (rolls[0], roll_count)

average_value = float(sum(roll_values)) / len(roll_values)
average_count = float(sum(roll_counts)) / len(roll_counts)

print "Finished rolling %d times." % experiment_count
print roll_values
print roll_counts
print average_value
print average_count


For graphic part :

I think Gdi++ of .NET framework is very slow.
Mainly the Bitmap() construtor and Save() method.

If it's possible for screenshot, I recommend to use :
Either directly gdi32.dll or (maybe, im not sure that is good idea) direct2d (benefits on hardware acceleration).

For transfert :

For your upload, run the transfert in other thread. (async or Delegate with BeginInvoke).
After it depends on your internet connection speed.

However, i don't understand why you recreate your Bitmap object twice :

using (Bitmap bmp1 = (Bitmap)Image.FromStream(mem))
using (Bitmap bmpLast = (Bitmap)Image.FromStream(m))

Don't reload with Bitmap,
create only one Bitmap for your screenshot, save it with encoding in memory stream and send memory stream to your database. With your memory stream you can get directly byte array with no conversion.

MemoryStream.Read(byte[] buffer, int offset, int count)


Performance of hashmap-based session object

This is pretty simple code, with not a lot of room for improvement.

You can make the session variable final, and it's good to do so:

private final ConcurrentHashMap<String, ConcurrentHashMap<String, String>> session = new ConcurrentHashMap<String, ConcurrentHashMap<String, String>>();

You can simplify createSession a bit by dropping the pointless local variable:

public void createSession(String callId) {
    session.putIfAbsent(callId, new ConcurrentHashMap<String,String>());
}

Some of the comments are really pointless, for example these:

/** enum is used for Singleton instance  **/
public enum SessionObject {

    /** single instance  **/
    INSTANCE;

You're using spaces in a non-standard way. Instead of this:

private ConcurrentHashMap<String , ConcurrentHashMap<String,String>> session =  new  ConcurrentHashMap<String , ConcurrentHashMap<String,String>>();

Don't put a space in front of commas, but put one after, like this:

private ConcurrentHashMap<String, ConcurrentHashMap<String, String>> session = new ConcurrentHashMap<String, ConcurrentHashMap<String, String>>();

It's good that you comment your methods. But instead of this:

/** Used to create a new Map when new call ivr is established in the first vxml file**/
public void createSession(String callId){

The correct format for JavaDoc comments is like this:

/**
 * Used to create a new Map when new call ivr is established in the first vxml file
 *
 * @param callId the call id for which to create new session
 */
public void createSession(String callId) {

Discussion

Our discussion in comments is perhaps worth including in the answer itself.

  Is it necessary to make the method argument as final ?

In your code, it's not necessary. But it's recommended. By setting method parameters final, you can prevent reassigning the value by accident. It's a bad practice to reassign the values of method parameters, for example in here: void fun(int something) { something = 3; }

  Can you please tell me, why you put the session variable as final ?

It's a good practice to make member fields final, as much as possible. final variables cannot change, they are immutable. Being immutable makes a variable more reliable and robust: once created correctly, you cannot break it, for example by accidentally reassigning to a value that wasn't correctly validated.

  I have used the enum for singleton . So my class is thread safe. Also I declared a session variable as private . So, Is it necessary to use the concurrent hashmap instead of ordinary hashmap in this case ?

The enum singleton guarantees that all threads will see the same INSTANCE. However, if you have multiple threads, they might access the session map concurrently, which would not work with a regular hashmap. So yes, session should be a ConcurrentHashMap, unless the rest of your implementation guarantees single-threaded access.

  By adding the final, the session variable become immutable. But I am adding the key/value pairs in the 'cmap'. So the map will become mutable.

I meant in the more general sense. For example simple types like int would be truly immutable. With object types, only their reference, the variable pointing to them will be immutable. Although their content is still editable (why you mustn't forget), not being able to reassign them does give you some level of protection. So it's always good to make your members final whenever possible. When your solution requires some members to be not final, give it some thought to refactor your solution to make them final. This is not always possible, but you should at least try, always.


This seems to be a lot of code to say the same as this:

[AjaxOnly]
[Authorize]
public ActionResult Details(int id)
{
    User userToGet = _session.Get<User>(id);

    if (userToGet == null)
    {
        return PartialView("Partials/UserNotFound");
    }

    DetailsUserViewModel userToViewModel = Mapper.Map<User, DetailsUserViewModel>(userToGet);

    return PartialView("Partials/Details", userToViewModel);
}

What problem are you trying to solve here?

(or am I missing something?)


Bug
Your int to string conversion isn't working correctly when the number being printed is an exact power of the base.  Here is a program that demonstrates the bug:
int main(void)
{
    char buf[256];

    memset(buf, 'z', 256);
    my_snprintf(buf, 256, "abc%ddef", 1000);
    printf("%s\n", buf);
}

Expected output:
abc1000def

Actual output:
ab1000zdef

As you can see, the 1000 portion was written one too far to the left.  The problem is that your number length computation is off by one for exact powers of the base.
Unnecessary and unsafe floating point operations
The Floating Point Police™ would like to point out that the use of floating point in int_to_str() is both unnecessary and dangerous.  First of all, this line:
int length = (int)ceil(log((double)x)/log((double)base));

could be rewritten to use a loop to count the number of digits.  By using floating point, you open yourself up to rounding errors.  For example, if x were 125 and base were 5, you would expect length to be 3.  However, when I ran the above code using 125 and 5 on my x86 machine, I got a length of 4 instead.  This is because the division evaluated to something like 3.00000001 and ceil rounded it up to 4.  (Of course there is already an unrelated off by one bug mentioned in the previous section.  This floating point use is a separate cause of concern).
The same thing applies to this line:
    x /= (int)pow(base, (float)(length - size));

This could be rewritten to be a loop where you divide by base once per loop iteration.  By using pow() and casting to int, you run the risk of the result of pow erroneously rounding down to the previous int.


Just a quick heads up about your use of leading underscores. This is discouraged because they are reserved by the standard.
You should find another way to mark variables as members (if you find it's necessary). I've seen a lot of people using trailing underscores for this. In my opinion trailing indentifiers are smarter as otherwise you will have to type whatever prefix you picked everytime you want to address a member variable (which also slows down autocomplete).


Some things that might improve your code:

Use heapq rather than Queue.PriorityQueue. The latter does synchronization stuff that you don't need, so heapq will be faster.
Don't add neighbor to done in your inner loop. This will find incorrect routes on any graphs where some subpath A->B->C is shorter than A->C. Instead, you want to be be putting item[1] into done when you pop it off the queue. Since this means you will get some duplicated nodes in your queue, you'll also need to check if the newly popped node was already done before processing it. You might be able to save a little processing time by storing the cost of the path to the node in a dictionary, and only adding a new path if it's less than the previous one (but I don't think the improvement is very large).
This is a readability improvement (not a performance or correctness fix), but I suggest unpacking item into several values, rather than indexing it. cost, node, first_step = queue.get(), or something similar.
A terminology suggestion: Rather than being a basic breadth-first search, this is Dijkstra's Algorithm. If all the edge weights are equal, you'll examine nodes (roughly) the same order as in a BFS, but if you have different weights you'll go in a different order. It might be a good idea to use a function name that reflect what you're actually doing in the code.


There shouldn't be a speed issue (so far as I can tell), but there is an outright bug:

line.map do |x| x = x.to_i end

You're not storing the result of the map, you're just throwing it away. So line doesn't change, and you end up comparing the elements lexicographically, i.e. as strings. So "48" ends up being less "5" and such.

Other notes:

The Ruby convention is to use 2 spaces for indentation. Not 4 spaces, not tabs.
You don't need semicolons.
When writing a single line block, use {..} instead of do..end
When simply invoking the same single method on all elements in an array, you can use a shortcut: line.map(&:to_i)
You can exclude the last element in a range with 3 dots (...), so 1..arr.length-1 becomes just 1...arr.length

With that and a few other things you get:

def bubble(array, iterations)
  iterations.times do
    (1...array.length).each do |i|
      if array[i-1] > array[i]
        array[i-1], array[i] = array[i], array[i-1]
      end
    end
  end
end

File.open(ARGV[0]).each_line do |line|
  line = line.chomp.split(" ")
  iterations = line.last.to_i

  values = line[0...-2].map(&:to_i)
  bubble(values, iterations)

  puts values.join(" ")
end

Now, this is just a challenge, but for production code, I'd avoid the side-effects of bubble, and return a new array instead. But that's a different story.

Edit: Since it's still too slow, maybe it's because the input is crafted to trick you. For instance, a line that calls for billions of iterations on a relatively small set of values will, with the code above, cause waaay too many pointless iterations. I.e. the list may be sorted already, but the algorithm will keep loop through it the specified number of times.

A pretty simple solution would be something like:

def bubble(array, iterations)
  iterations.times do
    sorted = true
    (1...array.length).each do |i|
      if array[i-1] > array[i]
        sorted = false
        array[i-1], array[i] = array[i], array[i-1]
      end
    end
    break if sorted
  end
end

Additionally, you can skip stuff by checking the number of iterations before calling bubble. If it's zero, there's no need for the map:

File.open(ARGV[0]).each_line do |line|
  line = line.chomp.split(" ")
  iterations = line.last.to_i

  unless iterations.zero?
    values = line[0...-2].map(&:to_i)
    bubble(values, iterations)
  end

  puts values.join(" ")
end

Now of course it may just be that the input is just huge, and Ruby isn't the fastest thing. But one has to assume that the challenge can actually be solved.


Representation graph as Adjacency List in JavaScript

Strictly speaking, the list of vertices is not neccessary because the adjacency list already contains all (connected) vertices and disconnected ones can be represented as [x, null]. If you prefer to keep vertices, you'll have to synchronize them with edges:

in removeVertex you not only remove the vertex but also all edges connected to it
in addEdge you add input labels to the vertices list, if not already there (which makes one think that vertices should be a Set)

Minor notes:

In general, as of 2018, it's cleaner to use the class syntax to define classes.

In removeEdge you'd probably want &&, not ||: return startLabel === inputStartLabel && endLabel === inputEndLabel. If the graph is undirected, you also have to check for reversed edges (start == inputEnd && end == inputStart)

You didn't share the input data format and formatDataToAdjacencyList, but anyways, it would look better as a class member, not as an extra function.


AJAX request authentication to PHP script

Prefer mt_rand() to rand().
Just a comment: your usage of tokens is similar to using nonces. There are established nonce generation libraries for PHP, and I suggest you take a look into them.
HTTP_X_REQUESTED_WITH is in general not a 100% reliable way to detect AJAX-ness. However, jQuery sends this header with its AJAX calls, so you should be okay. I'd suggest getting rid of the is_ajax in your request data though.
Your input element is at best confusing, and at worst messy. Why is Deactivate paired with YES, and Activate with NO? I'd prefer just using deactivate and activate as the button values, and templating inline:

<input type="button" class="active_button" name="<?= $article_id ?>" value="<?= $article_active ? "de" : "" ?>activate" />

activateDeactivate isn't a very good name. Maybe setActiveStatus or something?


Before I begin, you should be aware tha petgraph has already implemented most of the graph algorithms people may need. Use well-tested existing code whenever you can.

Cleanup

General

Run rustfmt. It will automatically tell you such things as:

There's no space between a function name and the parenthesis (fn dfs_visit ()
When a function signature gets too long, arguments start on the subsequent line:

fn dfs_visit(
    graph: &Graph,
    vertex: Vertex,
    time: &mut u64,
    seen: &mut HashSet<Vertex>,
    state: &mut DFSResult,
) {

Run clippy. It will automatically tell you such things as:

Don't use return on the last expression in a function.
To avoid or_insert with a function call as the argument (although it's acceptable in this case).

Use curly brackets to group imports from the same path.
There's no need to directly use the AddAssign trait; just use the operator +=.
I appreciate the usage of type aliases as a first step to organizing your code.
It's not common to use /* */ style comments; idiomatic Rust uses // instead.

from_pairs

You document that this accepts a sequence, but it actually takes a slice. Taking an Iterator is more flexible and better fits the documentation.
Be consistent about your usage of the type alias; you have places that still say u64. This is why a newtype can sometimes be a better choice.
Instead of calling HashMap::new, call Graph::new and avoid the redundant type specification.
I'd convert the insertion into the graph into a single expression instead of introducing a temporary variable.

dfs

When nesting a helper function, it's important to not split up the flow of the surrounding code. Declaring all your variables before the helper and using them after seems very confusing.
The initializer for DFSResult should be a method on it, not just stuck in the dfs method.
In fact, you can just derive Default and avoid any of the implementation yourself.
Why are there comments on the fields in the initializer? They seem awfully redundant with the names of the fields... Either way, they should be on the struct definition.
It's worth checking your comments for typos ("verticies" => "vertices", "bave" => "have", etc.)
Why populate parents with None? Wouldn't absence in the HashMap be enough to know there are no parents?
Don't use Option::None / Option::Some. None and Some are imported as part of the prelude and can be used directly.
If you have to document a variable like time with "current time", consider renaming the variable.
Don't redundantly specify types (seen: HashSet<Vertex> = HashSet::new();)
There's no need to pop_back and then push_back a value; just use back_mut.

topological_sort

You don't need to store the result of dfs into a variable to pull out just one field, you can directly call .topologically_sorted .

use std::collections::{HashMap, HashSet, VecDeque};

type Vertex = u64;
type Graph = HashMap<Vertex, HashSet<Vertex>>;

/// Constructs a graph from a sequence of parent child pairs
pub fn from_pairs<I>(pairs: I) -> Graph
where
    I: IntoIterator<Item = (Vertex, Vertex)>,
{
    let mut graph = Graph::new();
    for (parent, child) in pairs {
        graph
            .entry(parent)
            .or_insert_with(HashSet::new)
            .insert(child);
    }
    graph
}

#[derive(Debug, Default)]
pub struct DFSResult {
    /// all the starting times for each vertex
    starting_times: HashMap<Vertex, u64>,
    /// the finishing times for each vertex
    finishing_times: HashMap<Vertex, u64>,
    /// the parents of each vertex
    parents: HashMap<Vertex, Option<Vertex>>,
    /// The DFS forest
    forest: VecDeque<HashSet<Vertex>>,
    /// the topologically sorted list of verticies
    topologically_sorted: VecDeque<Vertex>,
}

/// Returns the starting and finishing times and the parents of every node
/// found with dfs as well as the dfs forest
pub fn dfs(graph: &Graph) -> DFSResult {
    fn dfs_visit(
        graph: &Graph,
        vertex: Vertex,
        time: &mut u64,
        seen: &mut HashSet<Vertex>,
        state: &mut DFSResult,
    ) {
        *time += 1;
        state.starting_times.insert(vertex, *time);
        seen.insert(vertex);

        state
            .forest
            .back_mut()
            .expect("The Forest should not be empty!")
            .insert(vertex);

        for neighbor in graph.get(&vertex).unwrap_or(&HashSet::new()) {
            if !seen.contains(neighbor) {
                state.parents.insert(*neighbor, Some(vertex));
                dfs_visit(graph, *neighbor, time, seen, state);
            }
        }

        *time += 1;
        state.finishing_times.insert(vertex, *time);
        state.topologically_sorted.push_front(vertex);
    };

    let mut state = DFSResult::default();

    for vertex in graph.keys() {
        state.parents.insert(*vertex, None);
    }

    let mut seen = HashSet::new();
    let mut current_time = 0;

    for vertex in graph.keys() {
        if !seen.contains(vertex) {
            state.forest.push_back(HashSet::new());
            dfs_visit(graph, *vertex, &mut current_time, &mut seen, &mut state);
        }
    }

    state
}

fn topological_sort(graph: &Graph) -> VecDeque<Vertex> {
    dfs(graph).topologically_sorted
}

fn main() {
    let pairs = [(1, 2), (2, 1)];
    let g = from_pairs(pairs.iter().cloned());
    println!("{:?}", g);
    println!("{:?}", dfs(&g));
    println!("{:?}", topological_sort(&g));
}

Abstraction

Now that everything is cleaned up, let's turn to abstracting it a bit. The most important thing is to notice which pieces of code are core to the DFS algorithm and what is incidental. Luckily, your code already shows that to some degree. Everything in DfsResult is incidental, so we comment it out. There's some collateral damage (like current_time) which also gets commented out.

The only data that's truly required is the seen variable. Everything else can be boiled down to a set of actions that can be taken sometime during the DFS lifecycle.

To that end, we create a trait with methods for each lifecycle event. We provide default implementations which are empty; this makes end implementations much nicer. Naming and documentation are key for this trait, and I didn't do a good job. You should definitely improve upon my names.

#[allow(unused_variables)]
pub trait DfsAction {
    fn initial_visit(&mut self, graph: &Graph, vertex: Vertex) {}
    fn start(&mut self, graph: &Graph, vertex: Vertex) {}
    fn pre_visit(&mut self, graph: &Graph, current: Vertex, next: Vertex) {}
    fn end(&mut self, graph: &Graph, vertex: Vertex) {}
}

pub fn dfs<A>(graph: &Graph, action: &mut A)
where
    A: DfsAction,
{
    fn dfs_visit<A>(graph: &Graph, vertex: Vertex, seen: &mut HashSet<Vertex>, action: &mut A)
    where
        A: DfsAction,
    {
        action.start(graph, vertex);

        seen.insert(vertex);

        for neighbor in graph.get(&vertex).unwrap_or(&HashSet::new()) {
            if !seen.contains(neighbor) {
                action.pre_visit(graph, vertex, *neighbor);
                dfs_visit(graph, *neighbor, seen, action);
            }
        }

        action.end(graph, vertex);
    };

    let mut seen = HashSet::new();

    for vertex in graph.keys() {
        if !seen.contains(vertex) {
            action.initial_visit(graph, *vertex);
            dfs_visit(graph, *vertex, &mut seen, action);
        }
    }
}

We can implement the trait for each of the distinct pieces, instantiate one of the pieces, then pass it in:

#[derive(Debug, Default)]
struct TopologicalSort(Vec<Vertex>);

impl DfsAction for TopologicalSort {
    fn end(&mut self, _: &Graph, vertex: Vertex) {
        self.0.push(vertex);
    }
}

fn topological_sort(graph: &Graph) -> Vec<Vertex> {
    let mut topo = TopologicalSort::default();
    dfs(graph, &mut topo);
    topo.0.reverse();
    topo.0
}

This continues for all of the other pieces:

type Times = HashMap<Vertex, u64>;

#[derive(Debug, Default)]
struct Timer {
    time: u64,
    starting_times: Times,
    finishing_times: Times,
}

impl DfsAction for Timer {
    fn start(&mut self, _: &Graph, vertex: Vertex) {
        self.time += 1;
        self.starting_times.insert(vertex, self.time);
    }

    fn end(&mut self, _: &Graph, vertex: Vertex) {
        self.time += 1;
        self.finishing_times.insert(vertex, self.time);
    }
}

fn times(graph: &Graph) -> (Times, Times) {
    let mut times = Timer::default();
    dfs(graph, &mut times);
    (times.starting_times, times.finishing_times)
}

#[derive(Debug, Default)]
pub struct Parents(HashMap<Vertex, Option<Vertex>>);

impl Parents {
    fn new(graph: &Graph) -> Self {
        let mut parents = HashMap::new();

        for vertex in graph.keys() {
            parents.insert(*vertex, None);
        }

        Parents(parents)
    }
}

impl DfsAction for Parents {
    fn pre_visit(&mut self, _: &Graph, current: Vertex, next: Vertex) {
        self.0.insert(next, Some(current));
    }
}

fn parents(graph: &Graph) -> HashMap<Vertex, Option<Vertex>> {
    let mut parents = Parents::new(graph);
    dfs(graph, &mut parents);
    parents.0
}

#[derive(Debug, Default)]
pub struct Forest(Vec<HashSet<Vertex>>);

impl DfsAction for Forest {
    fn initial_visit(&mut self, _: &Graph, _: Vertex) {
        self.0.push(HashSet::new());
    }

    fn start(&mut self, _: &Graph, vertex: Vertex) {
        self.0
            .last_mut()
            .expect("The Forest should not be empty!")
            .insert(vertex);
    }
}

fn forest(graph: &Graph) -> Vec<HashSet<Vertex>> {
    let mut forest = Forest::default();
    dfs(graph, &mut forest);
    forest.0
}

If you want to get back to your "do everything" set, you can implement a BothAction that takes two actions and calls both, combining those into a Both(Both(A, B), Both(C, D)).

Splitting up all of the actions also makes it easier to see that further simplifications can be made. For example, you don't really need a VecDeque — I've changed to a simple Vec in the code above.


Preventing SQL Injection in user registration routine

It is safe.

You can improve your code like this:

no need to use closing ?> in case that you are not outputting any HTML / or something else after your PHP code
no need to use "" to wrap strings in case that you don't have any variables inside a string, you can use '' instead, PHP interpreter does not need to check in that case whether there are any variables in the string or not
you can replace echo $e->getMessage; die() by simplier exit($e->getMessage());
I added salt generation to your code $salt = md5(uniqid(null, true));
I added password hashing to your code by $password = hash('sha256', $password . $salt);

The whole code hereunder:

<?php

try {
    $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    exit($e->getMessage());
}

$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

$salt = md5(uniqid(null, true));
$password = hash('sha256', $password . $salt);

$sql = '
    INSERT INTO userinfo
        (name ,username, email, password, salt)
    VALUES
        (:name,:username,:email,:password, :salt)
';

$query = $handler->prepare($sql);

$query->execute(array(
    ':name' => $name,
    ':username' => $username,
    ':email' => $email,
    ':password' => $password,
    ':salt' => $salt
));


If you need to store a result of a method you should just create a method for it.

private bool IsInRange(DateTime dateTime, decimal min, decimal max)
{
    decimal totalMinutes = Math.Round((dateTime - DateTime.Now).TotalMinutes, 0);
    return totalMinutes > min && totalMinutes <= max;
}

now your expression looks like so

.Where(m => IsInRange(m.DateAndTime, 0, 30));

but the values 0 and 30 are still magic numbers which should be extracted to meaningful constants.

The choosen method name is not the best like @Falco has correctly pointed out in his comment

  UhhOhhh Horribly wrong named Function.... AreMinutesInRangeFromNow or something like this would be better - with your Method-Name I would expect no Magic happening with DateTime.Now - or pass the already substracted value, but don't hide this!

so you should change it to a better name.  I don't like the name @Falco suggested either but couldn't come up with a different one. So it is up to you to choose one.


Bug: String escaping

In C, "foo \" bar" is a legal string, but it will confuse the state of your program (so " bar" will be seen as not in a string, while everything after the end of the string will be seen as inside a string). You need to handle at least the escape sequence \" within strings.

Bug: Comments as token separators

If you have the (admittedly weird) C:

int/**/bar;

That will parse as int, bar, ; (declaration of an integer called bar). With comments removed as by this program, it will come out as:

intbar;

Which is probably a parse error.

C syntax should always allow arbitrary whitespace around comments, so this could be fixed by always emitting some whitespace after removing a comment. That could make the output rather ugly, so if you wanted to be 'clever' you could try to only insert extra whitespace when necessary.

Bug: potentially out-of-bounds access through arr[1]

c should be checked to make sure it's greater than 1 before accessing through arr[1].

Suggestion: State machine

The above-mentioned bug is part of a larger issue: there's a lot of "hidden" state to do with things like "what was the previous character" etc.

The nice thing about most programming languages (including C) is that they are designed so that lexical analysis (which is what you need to do to remove comments) is very simple, and can be done with a finite-state automaton (often just called a state machine).

In some sense your program is already a finite-state machine, with the state being the combination of the String flag, the prev variable, and which function you're in---but it's a little hard to keep track of. Introducing an explicit state machine will make the code clearer, and make it easier to handle cases like escaped quotes in strings.

There are various implementation patterns for state machines; a common one for small/simple state machines, such as this one, is to use an enum to name some states:

enum { START, COMMENT_START, COMMENT, COMMENT_END, LINE_COMMENT, STRING, STRING_ESCAPE, };

and then use a switch statement to behave differently depending on the state:

int state = START;

...

switch (state) {
case START:
    if (c == '/') state = COMMENT_START;
    /* other branches */
    break;
case COMMENT_START:
    if (c == '*') state = COMMENT;
    else if (c == '/') state = LINE_COMMENT;
    /* other branches */
    break;
    .
    .  /* etc */
    .
}

Convention: standard names for arguments to main

The almost universal convention is for the signature of main to be

int main(int argc, char *argv[])

There isn't anything inherently wrong with using different names for those variables, but using argc/argv makes it slightly easier for other people to read.

Pedantry: whitespace

The use of whitespace around punctuation seems a little...haphazard. (For example, some parentheses have spaces around them, while others have none; some commas have spaces both before and after, some have one, some have none). Regardless of which style you prefer (which is an opinion thing), the inconsistency makes it more difficult to read.

Feature: not-in-place modification

A useful behaviour (and the behaviour I'd expect) would be to be able to call

commentremover foo.c

and have it print the comment-removed version of the program to STDOUT, without clobbering foo.c.


You can define left and right in merge_sort this way:

n = m.length
if n <= 1
  return m
end

left = merge_sort(m[0 ... n/2])
right = merge_sort(m[n/2 .. -1])

Depending on your Ruby version, Array#shift can be O(n). You could keep 2 indices for a and b:

def merge(a, b)
  result = []
  i, j = 0, 0
  na, nb = a.size, b.size

  while i < na && j < nb do
    if a[i] <= b[j]
      result << a[i]
      i += 1
    else
      result << b[j]
      j += 1
    end
  end

  return result + a[i..-1] + b[j..-1]
end

With those changes, the code becomes twice as fast with input = [*1..100000].shuffle.


Multiple inheritance pattern for vehicle information

Very interesting concept, I could see this turning into a "Pimp my Ride" game. A few things before this is sent off to gamers:
OOP
It seems like you've kind of misunderstood what OOP is about. As it is, you have a lot of variables (not objects) which then are smushed together into a final concept (the car).
If you want this to be more OOP oriented, here's some things I suggest:
Get rid of all the variables, except car. Keep this, as it will represent your "object". Instead of the manufacturer having his own variable (who knows, maybe some car will be custom built or have various manufacturers), use getters and setters to define a property of car. Picture it this way:
Car object {
    Initialize the object here

    get manufacturer() {

    }
    set manufacturer(string or array or object) {

    }
}

Now your code might get a big here if you implement each detail with a getter and setter. Sometimes you can manage this, other times not, which then you might break things apart: have the manufacturer get/set in an engine object, and the car will only have the get/set for engines.
Like one of the comments said, you should research object prototyping. For a fresh start on JavaScript programming in an object oriented style, read Mozilla's documentation.
Misc.
I'm not convinced having a Ferrari variable and a lotus variable are the best way to accomplish creating cars. I suggest a new object, maybe CarColection or Garage and create/retrieve/store/pimp your cars their. It will allow for later changes, or dynamic modification of the cars.
Purely for fun and for homework: add in the ability to specify exhaust, transmission, tires, driving skill, etc. and then compute horsepower/car level. Pretty soon you could challenge cars up against each other in races! :)