NodeJS broker between MongoDB and RabbitMQ

Interesting question, it was hard to find things I would do different.

To Malachi's point, there are a few strings you could put in a config object, I would definitely add also 10000 to that config object as config.delay and your statuses like 'ONGOING'.
Also, I would write this:

.then(function(results) {
    if (results.length > 0) return results[0];
    return null;
});

As

.then(function(results) {
    return results[0] || null;
});

In the bottom part, you have very stylized code, very functional except for the  2 blocks. I would create 2 named functions called logResults and logError and use those.
In produceTask, you are stretching quite a bit your horizontally, part of that is your atypical use of then on the same line ( different from the rest of your code ). I would counter-propose cutting the code a bit up:

TaskBroker.prototype.produceTask = function() {
  var sendOptions = { deliveryMode: true };
  var statusUpdate = { $set: { 'status': 'ONGOING' }};
  return function(message) {
    if(!message) {
      return;
    }
    message.status = 'ONGOING';
    var content = new Buffer(JSON.stringify(message));
    this.rabbit.channel.sendToQueue(this.queueName, content , sendOptions);
    return this.mongo.db.test.update({_id: message._id}, statusUpdate)
      .then(function() {
        return message;
      });

  }.bind(this);
};

I also declared sendOptions and statusUpdate outside of the returned function, there is no sense in re-creating these all the time.
I also return early if there is no message to reduce arrow pattern code
I renamed _message to message, more on that later

Anonymous functions; you are using a number of anonymous functions. This becomes a problem if you have to analyze stack traces, simply add well named function names, and your code becomes that much easier to support:

TaskBroker.prototype.connectRabbit = function() {
  return amqp.connect('amqp://localhost')

    .then(function onConnect(connection) {
      this.rabbit.connection = connection;
      return connection.createChannel()
    }.bind(this))

    .then(function onChannelCreated(channel) {
      this.rabbit.channel = channel;
      return channel.assertQueue(this.queueName, {durable: true});
    }.bind(this))
};

JsHint.com -> Use it, you have missing semi colons and bad line breaks
Commented out code -> Dont do that in production code
Console.log -> I would wrap this in a function where I can control whether I really want to log and where I can optionally also log into a file for later analysis
I am not sure why you prefix some variables and parameters with underscore, I would advise against it. I know that mongo does this, to distinguish between mongo properties and data properties on an object, which is okay. But I see no good reason in your code for you to prefix variables/parameters with _
Connection to Mongo db; your approach is okay for development, for quality and production I would get the details from the environment:

this.mongo.db = mongo('mongodb://'+ process.env.MY_APP_MONGODB_HOST + '/myapp' , ['myapp']);

You can write

if (results != null && results.length > 0) {
  url_array = this.get_url_array(results);
}

as

if (results instanceof Array) {
  url_array = this.get_url_array(results);
}

I dont like url_array, I tend to take whatever is in the array and an 's' in JavaScript, but urls does not read much better in my mind. All I can say is that you should have some deep thoughts about that variable name.
The usage of null; the usage of null is not idiomatic JavaScript. Consider converting your code to check for undefined instead. Since functions return undefined if you dont return something yourself, you can then avoid statements like return null

All in all, I wish could write code like that when I am a beginner in a new language ;) Sometimes the code feels a bit forced into the promise style, but all in all this is pretty good.


PE4: Largest Palindrome Product (Clojure)

A function's docstring must go before its argument vector. You've written your docstrings after your argument vectors, which prevents your :preconditions from being recognized and doesn't work when you try to retrieve the docstring with tools like doc:

(doc palindrome?)
;; -------------------------
;; user/palindrome?
;; ([arg])
;;   nil

Rather than explicitly calling seq in your palindrome? function, you could use clojure.string/reverse and then just compare the two strings. Also, in Clojure code, if when you have something that could be anything, or something that could be any number, it's conventional to name it x:

(require '[clojure.string :as str])

(defn palindrome?
  "Returns true iff x reads the same both ways in base ten."
  [x]
  (let [s (str x)]
    (= s (str/reverse s))))

In most cases, it's conventional to use lowercase instead of uppercase for names. Following from the rule of x above, if you have two things, each of which could be any number, it's conventional to name the second one y:

(defn pow
  "Returns x to the power of y."
  [x y]
  (reduce * (repeat y x)))

It's essential that the collection of :preconditions you give in a defn be a collection of preconditions (such as the vector you have in your pow function), rather than just a single precondition (such as in your other three functions with preconditions). This is because, due to Clojure's homoiconicity, (number? digits) is, in fact, a collection (a list, to be precise) containing two elements: number? and digits. In this case, you can use {:pre [(number? digits)]} instead.

Your local max and min bindings shadow the existing max and min functions in clojure.core, which is generally a bad idea because it can lead to confusion and forces you to use namespace-qualified names for those functions if you want to use them. Also, since you already use the name n in your function name (nums-with-n-digits), using n as your parameter name would allow you to simplify your function's docstring and body without sacrificing clarity:

(defn nums-with-n-digits
  "Return a lazy sequence of all positive integers with n digits."
  [n]
  (let [end (pow 10 n)
        start (/ end 10)]
    (range start end)))

If you move the docstring for products-of-nums-list and replace the condition map with {:pre [(list? nums)]}, you'll see that calls like (products-of-nums-list (nums-with-n-digits 2)) will fail. This is because range (and therefore nums-with-n-digits) doesn't return a list; it returns a sequence. All lists are sequences, but not all sequences are lists. While (range Long/MAX_VALUE) returns instantly and uses negligible memory, (apply list (range Long/MAX_VALUE)) will use all your computer's memory before it returns.

Your products-of-nums-list function is pretty scary, actually. Your use of distinct and sort causes first a set and then an array containing all of the distinct elements in nums to be held in memory. Try evaluating (products-of-nums-list (nums-with-n-digits 4)) while watching your CPU and memory usage.

Rather than delegating the task of sorting (which is overkill anyway) to a products-of-nums-list function that isn't particularly general anyway, it would be better to just put the for directly into solve-pe4 and use max instead of sort to get the final result:

(defn solve-pe4
  "Returns the largest palindrome made from the product of two n-digit numbers."
  [n]
  (->> (let [nums (nums-with-n-digits n)]
         (for [x nums
               y nums]
           (* x y)))
       (filter palindrome?)
       (apply max)))

This function is already quite readable, so I don't see a need to decompose it further. It significantly improves the performance of (solve-pe4 3) and, given enough time, can find solutions to larger problems:

(solve-pe4 4)
;;=> 99000099

Your :preconditions are an OK way to assert correct input types. Clojure 1.9 will bring the spec library, which is a far more powerful way to solve that problem (and others):

(require '[clojure.spec :as s])

(s/fdef pow
  :args (s/cat :x number? :y nat-int?)
  :ret number?)

(s/fdef nums-with-n-digits
  :args (s/cat :n pos-int?)
  :ret (s/coll-of pos-int?))

(s/fdef solve-pe4
  :args (s/cat :n pos-int?)
  :ret pos-int?)

You can use instrument to enable spec validation:

(require '[clojure.spec.test :as stest])

(stest/instrument)

(nums-with-n-digits 0)
;; clojure.lang.ExceptionInfo: Call to #'user/nums-with-n-digits did not conform to spec:
;;                             In: [0] val: 0 fails at: [:args :n] predicate: pos-int?
;;                             :clojure.spec/args  (0)
;;                             :clojure.spec/failure  :instrument


Basic python dice simulator with log function

There's some things I really like about your code. For one, you used str.format, which is in many ways superior to '%'-formatting. You also included docstrings, which help others better understand your code.

The other answers already covered most major problems. I'll be answering mostly in terms of design choice.

Object oriented programming (and why it doesn't apply here)

Classes should be thought of as containers that capture 'state'. Methods can act on that state and properties can be used to query it. A die, however, doesn't have any sense of state. A good rule of thumb is that if a class has only two methods, one of which is the constructor, then it shouldn't be a class.

I'd go further and say that you shouldn't consider creating a class if you are not confident that there is a sense of state in your program that could be grouped together. If you want to know more, there's this well known talk on when not to use classes.

Python 3!

Python 3 rocks, and you should definitely start using it right now. Python 2 only has so much time left, and switching to Python 3 isn't that hard. The only changes that affect this code:

Python 3 got rid of raw_input and replaced it with input.
print is now a function, not a statement.

If you absolutely, positively feel like you need to maintain backwards compatibility with Python 2:

try:
    input = raw_input
except NameError:
    # Python 3; `raw_input` is not defined
    pass


Should I use an intermediate variable in a complex C# expression?

Note that semantically these options are not equal.

There is a chance (very-very small) that first option will output smth like 2011,2012,2014, so second option is better at least because it will always generate consistent results (3 consecutive years).

But second option is also quite cluttered. There is a string.Join method that is able to combine different values with separator, so your code may look like:

internal static string GetLast3Years()
{
    int currentYear = DateTime.Now.Year;
    return string.Join(",", currentYear - 2, currentYear - 1, currentYear);
}

But the question is still why would you need a string representation of last 3 years, comma-separated. I would consider having a method that will return enumerable of last N years instead...


Keeping track of people's relationships using a people relation table

It seems fine for me for generic cases. Later you might need some denormalization or caching if it's too slow but it really depends on the usage. (If you have any special requirement you should share it, edit the question, please.)

Four things to consider:

varchar(32) for name could be too small.
Consider unique indexes for the person_relation(parent_id, child_id, relation_id) triplet and the people_relation.relation attribute. For example:

Currently, you can insert the same relation twice:

mysql> select * FROM person_relation;
Empty set (0.00 sec)

mysql> INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`)
    VALUES (1, 2, 1);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`)
    VALUES (1, 2, 1);
Query OK, 1 row affected (0.00 sec)

mysql> select * FROM person_relation;
+----+-----------+----------+-------------+
| id | parent_id | child_id | relation_id |
+----+-----------+----------+-------------+
| 23 |         1 |        2 |           1 |
| 24 |         1 |        2 |           1 |
+----+-----------+----------+-------------+
2 rows in set (0.00 sec)

An unique index could prevent that:

CREATE UNIQUE INDEX person_relation_uniq_idx
    ON person_relation
    (parent_id, child_id, relation_id);

For example:

mysql> DELETE FROM person_relation;
Query OK, 2 rows affected (0.00 sec)

mysql>         CREATE UNIQUE INDEX person_relation_uniq_idx
    ->             ON person_relation
    ->             (parent_id, child_id, relation_id);
Query OK, 0 rows affected (0.31 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`)
    VALUES (1, 2, 1);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`)
    VALUES (1, 2, 1);
ERROR 1062 (23000): Duplicate entry '1-2-1' for key 'person_relation_uniq_idx'

mysql> SELECT * FROM person_relation;
+----+-----------+----------+-------------+
| id | parent_id | child_id | relation_id |
+----+-----------+----------+-------------+
| 25 |         1 |        2 |           1 |
+----+-----------+----------+-------------+
1 row in set (0.00 sec)

people_relation.relation might not be NULL.
people_relation and person_relation are easy to mix up, these names are too similar to each other. I'd rename people_relation to relation_type.


Regex substitution using a variable replacement string containing backreferences in Perl

This is incredibly hackish and broken code. Input that contains the magic substitution string (ABCD) will lead to incorrect output, and no steps to guard against this were taken. Even worse, the documentation is misleading since it uses double-quoted strings.

If you perform some escape encoding, then you must also escape the escape mechanism whenever it occurs in the input. For example, in single-quoted or q()-style strings, the closing delimiter is a forbidden symbol and must be escaped with a backslash \. However, there must also be a way to escape the backslash itself so that we can express both the strings ' via '\'' and \' via '\\\''. An alternative encoding in languages where two string literals cannot be directly adjacent is to use the delimiter as an escape character. If ' is the delimiter then '' cannot occur naturally except when denoting the empty string, so ' can be encoded as '''' and \' can be encoded as '\'''.

In our case, dollar symbols are forbidden and are escaped by the sequence ABCD, but that sequence itself is not escaped.

Instead of figuring out a proper way to escape this so that you can cobble together a half-solution using successive substitutions, let's take a step back and treat your substitution syntax as a serious language of its own. And languages get a parser. In particular, your language is a concatenation of three elements:

literal parts that consist of anything that's not a backslash or a dollar sign,
escaped characters that must at least contain $ via \$ and \ via \\,
backrefs that are a dollar sign followed by a positive non-zero integer.

The point that backslashes need escaping as well follows directly from the discussion above.

The syntax for backrefs is problematic since there's no way to properly delimit the number. Assume that we want to surround the capture group 1 with the letter a, and we can use the replacement directive 'a$1a', but assume we want to surround it with the digit 4, and '4$14' would parse more sensibly as the digit 4 followed by the backref $14. Perl – following established shell syntax – offers a ${1} syntax for these cases, and we should as well. Your code tries to deal with this problem by looping through all possible backrefs starting with the largest number, but given ten backrefs we wouldn't be able to discern $10 from ${1}0!

Therefore, the backref syntax ought to be a dollar symbol followed by either a sequence of decimal digits not starting with zero or else by such a sequence enclosed in matching curly braces. Clearly specifying it like this allows us to die when there is an unknown backref such as $666 when we only have three matches.

If we want to parse this substitution language in Perl, m/\G.../gc-style parsing is a viable option since the language is regular. The below function takes a replacement string, parses it, and returns a function that given a list of captures returns the fully substituted string.

use Carp;
use Scalar::Util 'reftype';

sub parse_replacement {
  my ($replacement) = @_;
  my @tokens;  # literals are strings, backrefs are refs
  pos($replacement) = 0;
  while (pos($replacement) < length($replacement)) {
    # normal literals
    if ($replacement =~ /\G( [^\$\\]+ )/xgc) {
          # if the previous token was literal, concatenate rather than pushing
          if (@tokens and not defined reftype $tokens[-1]) {
            $tokens[-1] .= $1;
          }
          else {
            push @tokens, $1;
          }
        }
        # escapes
        elsif ($replacement =~ /\G [\\]/xgc) {
          if ($replacement =~ /\G ([\$\\])/xgc) {
            # if the previous token was literal, concatenate rather than pushing
            if (@tokens and not defined reftype $tokens[-1]) {
              $tokens[-1] .= $1;
            }
            else {
              push @tokens, $1;
            }
          }
          elsif ($replacement =~ /\G\z/xgc) {
            croak "Illegal trailing backslash";
          }
          else {
            $replacement =~ /\G (.)/smxgc;
            croak sprintf "Escape can only contain backslash or dollar sign, not U+%4X '%s'", ord $1, $1;
          }
        }
        # backrefs
        elsif ($replacement =~ /\G [\$]/xgc) {
      if ($replacement =~ /\G [{]/xgc) {
        if ($replacement =~ /\G( [1-9][0-9]* )/xgc) {
          my $n = $1;
          push @tokens, \($n - 1);
          if ($replacement =~ /\G [}]/xgc) {
            # all is OK
          }
          else {
            croak "Expected closing curly brace for \${$n} identifier";
          }
        }
        else {
          croak 'Expected ${123} style numeric identifier inside ${...}';
        }
      }
      elsif ($replacement =~ /\G( [1-9][0-9]* )/xgc) {
        my $n = $1;
        push @tokens, \($n - 1);
      }
      else {
        croak 'Expected $123 or ${123} style number after dollar sign';
      }
    }
    else {
      croak sprintf "Illegal state – expected literal, escape or backref at position %d", pos($replacement);
    }
  }

  return sub {
    my ($captures) = @_;
    my $buffer = '';
    for my $token (@tokens) {
      if (reftype $token) {
        my $i = $$token;
            if ($i < @$captures) {
              $buffer .= $captures->[$i];
            }
            else {
              croak sprintf 'Unknown backref $%d; there are only %d captures', $$token, 0+@$captures;
        }
      }
      else {
        $buffer .= $token;
      }
    }
    return $buffer;
  };
}

Note that this code handles any eventuality and is therefore clearly correct and tries to provide meaningful error messages. It could further be improved by including the exact position and context in the error message.

There are various other problems with your code – I immediately see minor stylistic problems and another large-scale logical problem – but I'll leave those to another answer to tackle.

Your development would benefit from using a stringent set of test cases that handles edge cases and deliberately difficult inputs in order to find out whether your code actually matches your implementation. The Test::More module is an excellent place to start testing with Perl.


This code does not work, right?

What you have is an infinite loop, because x >> 1; does not do what you think it does.

There are a number of things wrong in here....

if the input long value is negative, you will never reverse it (it's < 0).
you should read up on the zero-shifting operator >>>
you will need to do all the 64 bits of shift otherwise the you will only reverse the set bits .... i.e. 0x00000000000001 should reverse to 0x8000000000000000 and not 0x00000000000001

The code you probably want will look more like:

public long reverse(long x) {
    long r = 0;
    for (int i = 63; i >= 0; i--) {
        r |= ((x >>> i) & 0x1L) << (63 - i);
    }
    return r;
}

Of course, you could always do:

public long reverse(long x) {
    return Long.reverse(x);
}


This code is pretty much the most efficient it can be, so I will add some pointers on the coding style and convention.

Instead of calling your Binary Search Tree class a BST, define it as

class BinarySearchTree(object):
    # remainder of your code

Gives more meaning to the class name.
The preorder traversal is called like t.preorder(t.root). But wait, t already has the root node in it, so it would be much more readable if we could do t.preorder(). So modify the signature to:

def preorder(self, root=None):
    if root is None:
        root = self.root
    # remainder of your code

Same should be done for t.inorder() and t.postorder() as well.

Spaces: You need a space between your arguments, as recommended by PEP-0008. So do def inorder(self, root): instead of def inorder(self,root):. This goes for the inorder and postorder as well
Using root as the argument name is misleading - its better to call it as node, which has the default value of self.root. This is cleaner, since in the DFS, you would traverse all the nodes of the tree.

def preorder(self, node=None):
    # replace root with node in your code

Same should be done for inorder and postorder as well.
Comments and indentation: Your comments are currently not indented right. Instead of having

    def inorder(self,root):
## left, root, right

Try defing them in the form of docstrings

def inorder(self,root):
    """traversal order: left child node, current node, right child node"""
    # remainder of your code


Name comparison using fuzzy string matching

To apply the same function to each row of a dataframe column, you usually use pd.Series.map or pd.Series.apply. You can thus simplify your code to:

from functools import partial
from fuzzywuzzy import process

accounts_DB = pd.read_csv("file.csv") #65,000 rows and 15 columns
accounts_SF = pd.read_csv("Requested Import.csv") #5,000 rows and 30 columns

best_matches = partial(process.extractBests, choices=accounts_SF['Account Name'], score_cutoff=95)
accounts_DB['Company Name'].map(best_matches).to_csv("Matched Accounts.csv")


Style is generally ok, but I'd recommend a more object-oriented approach - especially if you want to learn Ruby, since Ruby is thoroughly object-oriented.

Things I noticed:

Global variables (apart from built-in ones like $ARGV) are rare in Ruby. They're rare because you'll usually want to encapsulate your data in objects.
No need to write return at the end of methods; the result of the last expression is always implicitly returned.
You've quite a few methods that take 3 arguments, and some that return tuples. This is a general code-smell, in my opinion, because it's not very descriptive. Long parameter lists aren't easy to remember or parse, and multiple return values are also a fairly opaque data structure.
Overall structure is indeed very script'y and procedural.

Basically, you're passing all your data around, letting the methods modify them. A bit of basic object modelling could make your code better by encapsulation all that.

For instance, here's one way to model the game itself (not the full simulation). Just to give you something to chew on.

# A really simple Door class
class Door
  def initialize
    @open = false
  end

  def open?
    @open
  end

  def open!
    @open = true
  end
end

# This class models 1 instance/round of the game
class Game
  attr_reader :doors

  # Init a new game with +door_count+ doors, and randomly
  # picks one of them to be the winning door.
  # Raises an exception if door count is less than 3
  def initialize(door_count)
    raise ArgumentError, "There must be at least 3 doors" if door_count.to_i < 3
    @doors = Array.new(door_count.to_i) { Door.new }
    @winning_door = @doors.sample
  end

  # Set a random door as the player's pick
  # Raises an exception if there are no doors left to pick
  def pick_door
    raise "No doors to pick" if pickable_doors.empty?
    @picked_door = pickable_doors.sample
  end

  # open +count+ number of doors
  def open_doors(count)
    shuffled = openable_doors.shuffle
    [count, shuffled.count].min.times do
      shuffled.pop.open!
    end
  end

  # Returns true if the player's pick is the winning door
  def won?
    @picked_door == @winning_door
  end

  # Array of doors that an be picked by the player
  def pickable_doors
    closed_doors - [@picked_door]
  end

  # Array of doors that can be safely opened by Monty
  def openable_doors
    closed_doors - [@picked_door, @winning_door]
  end

  # Array of closed doors
  def closed_doors
    @doors.reject(&:open?)
  end
end

The Door class may seem sort of pointless (and indeed there are many ways to do things), but instead of using, say, an array of plain booleans, an array of door objects allows us to reference specific doors. Not as array indices, but as the doors themselves.

Again, I'm not saying this is the only - or even a particularly great - way of doing things. But it reads pretty well, and is easy to use.

For instance, this code will play a basic game with 3 doors, of which 1 will be revealed, and the player changes their pick:

game = Game.new(3)
game.pick_door     # initial pick
game.open_doors(1) # reveal what's behind a door
game.pick_door     # change pick
game.won?          # => (~67% chance of a win)

You could make classes for Choice, Prize, or, heck, even Goat, if you want to completely model everything. But I'd at least make a SimulationRun (or similar) class.

This would encapsulate the notion of "a run" as in "N rounds of the game", and keep state out of the global scope.

I'd also consider modelling the actors (the player and Monty), and inject them into the simulation.

For instance, imagine being able to say something like:

sim = Simulation.new(3, Monty::Classic, Player::Fickle)
win_ratio = sim.run(1000)

i.e. create a simulation using 3 doors, run it 1000 times, using the "classic" Monty rules that leave two doors unrevealed, and a player that'll always pick a different door second time around.

Monty and the player could be classes or simply lambdas. For instance, the player can simply be a lambda that returns true/false when asked whether to change the pick. And "the Monty" could simply return the number of doors to open. Or you could make them a lot more complex, letting the player's reaction depend on, say, the phase of the Moon or something.

Again, I'm not saying that the above is the only way - or even a particularly great way - to do things, but I'd certainly encourage you to try doing object modelling of some kind.

All of this is of course presuming you don't just want to do the math, but actually want to be empirical :)


Implementation of the Selection Sort Algorithm

The use of L.index(smallest_num) makes neither of these implementations valid. Using the input list [1, 0, 1, 0, 1] as an example, both of your implementations give [1, 1, 0, 0, 1] as their result, and this is clearly not sorted correctly.

The reason your algorithm doesn't work on this input is that it contains duplicate elements, so the .index method doesn't always return the index you want it to; as the documentation says, the .index method returns the index of the first occurrence of the given value. That will not always be the index of the occurrence you want to find; sometimes, that index is in the "already-sorted" part of the list, so you end up swapping things back there where they don't belong.

A correct implementation of selection sort should search for the index of the minimum element in just the unsorted part of the list.


Social network queries for profiles, posts, and followers

I'm not surprised your script is slow. You are being really wasteful with resources.

You should rewrite your code to access the DB as few times as possible. Reading from the DB is an expensive operation, because it requires PHP to connect to DB, send execution instructions, wait for results, parse results and make them available to your script.  Notice for instance that in get(), your prepared $stmt2 and $stmt3 are identical. You're forcing your DB server to do the exact same work multiple times ($stmt2 is executed in a loop).  Why not call $this->db->prepare once and just bind different parameters to it before executing?  Better yet, can you compile all the fromUserIds you need and make the query once?  Start to think in this manner to reduce DB queries.
When you access the DB on every iteration of a loop, you're really paying a heavy price. For instance in count(), you execute a query to retrieve all the data for a particular follower, then for each result you execute another query to count the rows in posts table that belong to this follower. Look around SQL resources/forums to figure out how to do this in one query that will return followerId, count. Trust me, it can be done (hint: look into SQL Join operations).
Only select the data you need. For instance, instead of SELECT * FROM profile_followers in count(), if all you care about is the userId so you can match it against the same ID in posts table, then use SELECT userId.  The bigger your result set, the more memory your script will use.
NEVER sort if you don't need to. Sorting is really expensive. If you only care about the number of results (in count()), why are you sorting the results with ORDER BY x? Imagine if your boss asked you to sort all the words in this post alphabetically and report how many words there are.  I bet you won't bother to sort the words; you'll just count them and report the total.  Sorting is hard work.

Your intuition that your script is inefficient is right, so you have good instincts. Don't worry: once you're done optimizing you'll be amazed at the difference.


The solution for the exercise 1-22 from the book "The C programming language" K&R2

This looks pretty competent code to me.  Good to see that you've included handling for tabs.
I only have minor points to raise:

#define NON_BLANK(ch)   (ch != '\t' && ch != '\n' && ch != ' ')

If we include <ctype.h>, we should be able to use isspace() instead of this macro.  In any case, a function is preferred to a macro, especially a macro that expands its arguments more than once (we can't call this with an argument such as *++p, for example).

#define IN_NON_BLANK_SEQ 1

We only have two states, so we should use a boolean (with a better name than state).  Assuming we have <stdbool.h>, then I'd replace int state = !IN_NON_BLANK_SEQ; with
   bool in_blank_seq = false;

Actually, we might not need this at all - I think that when we have most recently seen whitespace, then index_non_blank is non-zero.

int column_pos = 0;
int index_non_blank = 0;

These two could be unsigned.  But that might not matter, given the small range of values they ever hold.

#define TAP_STOP_DIST 5
int get_next_tap_pos(int current_column) {

Spelling - that should be tab.  And what kind of terminal has tab stops every five characters?  Pretty much every terminal (and terminal emulator) I've ever used has tab stops every eight characters, at least unless specifically changed.

#define LINE_MAX_SIZE 21

Additional exercise - make this configurable, by command-line option.


Split Inputvalue into 2 hex encoded bytes if Input>255

Why try and manipulate the number as a string?

Personally I would convert the input to a number and then manipulate it and finally convert it back to a string, if you need to.  However I would have thought C# has a way of making a text box accept Hex numbers and returning an Int (I don't know I don't do GUIs.)

Using your example number 0x2ee.
If the number if greater than 0xFF then it will take more than one byte to store it.  So to split the value you can do lowerByte = number % 256.  The upper byte is simply upperByte = (number - lowerByte) >> 8

So putting this into code

static byte[] SplitNumber (Int16 number)
{
    byte[] returnValue = new byte[2];
    returnValue[0] = Convert.ToByte(number % 256);
    returnValue[1] = Convert.ToByte((number - returnValue[0]) >> 8);
    return returnValue;
}

Now you have your bytes, you can format them in the text box as you like,


Optimizing my 2D Ising model code in Julia

The biggest problem with this code is the amount of things in global scope. Rewriting it to make some things const, and passing in the rest from a main function brings the time down to .7 seconds (not including the using plots which takes 3.5 seconds, compared to ~10 seconds before. Here is the updated code, I hope it helps.

using Printf
using Plots

const L       = 20             # linear size of lattice
const n_sweep = 20             # number of sweeps between sampling
const n_therm = 1000           # number of sweeps to thermalize
const n_data  = 100            # number of data samples per temperature
const temps   = 4.0:-0.3:0.1   # temperatures to sample

function measure(i, energy, magnetization, s)      # measure i'th sample of energy and magnetization
    en = 0
    m = 0
    for x = 1:L
        for y = 1:L
            u = 1+mod(y,L) # up
            r = 1+mod(x,L) # right
            en -= s[x,y]*(s[x,u]+s[r,y]) # energy
            m  += s[x,y]                 # magnetization
        end
    end
    energy[i] = en
    magnetization[i] = abs(m)
end

function flip(x, y, T, s) # apply metropolis spin flip algorithm to site (x,y) w/ temp T
    u = 1+mod(y,L)   # up
    d = 1+mod(y-2,L) # down
    r = 1+mod(x,L)   # right
    l = 1+mod(x-2,L) # left
    de = 2*s[x,y]*(s[x,u]+s[x,d]+s[l,y]+s[r,y])
    if (de < 0)
        s[x,y] = -s[x,y]
    else
        p = rand()
        if (p < exp(-de/T))
            s[x,y] = -s[x,y]
        end
    end
end

function sweep(n, T, s) # apply flip() to every site on the lattice
    for i = 1:n
        for x = 1:L
            for y = 1:L
                flip(x,y,T, s)
            end
        end
    end
end

function main()
    e1 = Array(1:n_data)     # array to hold energy measurements (fixed T)
    m1 = Array(1:n_data)     # array to hold magnetization measurements (fixed T)
    et = []                  # array to append average energy at each T
    mt = []                  # "                      magnetizations
    s  = ones(Int32,L,L)     # lattice of Ising spins (+/-1)
    for T in temps              # loop over temperatures
        sweep(n_therm, T, s)    # thermalize the lattice
        energy        = e1      # reset energy measurement array
        magnetization = m1      # same
        for i = 1:n_data        # take n_data measurements w/ n_sweep
            sweep(n_sweep, T, s)
            measure(i, energy, magnetization, s)
        end
        en_ave = sum(energy)/n_data           # compute average
        ma_ave = sum(magnetization)/n_data
        push!(et,en_ave/(L*L))                # add to the list
        push!(mt,ma_ave/(L*L))
        @printf("%8.3f  %8.3f \n", en_ave/(L*L), ma_ave/(L*L))
    end
    plot(temps,mt) # plot magnetization vs. temperature
    #plot(temps,et)
end

main()


Loops to merge documents and renumber pages

One way to make it easier to follow is to construct your merged documents result separately from your input (above code is not tested).

Construct a dictionary to easily get the document to append to, based on type. It also ensures a fast operation. For each document from the input, append its pages in the dictionary:

// type => merged document mapping
var mergedDocsDict = new Dictionary<String, Document>();

response.documents.ForEach(doc =>
    {
       if (!mergedDocDict.ContainsKey(doc.docType))
          mergedDocDict.Add(doc.docType, new Document());

       mergedDocDict[doc.docType].pages.AddRange(doc.pages);
    };

Finally renumbering all the pages:

mergedDocDict.Keys.ForEach(key =>
   {
       var doc = mergedDocDict[key];
       int pageCount = doc.pages.Count;
       for (int i = 0; i < pageCount; i ++)
          doc.pages[i].pageNo = i + 1;
   };

You result can be obtain from the dictionary:

mergedDocDict.Values.ToList();

This solution should be easier to understand, but uses extra memory for the result.

This can be overcome, by reusing the same documents:

response.documents.ForEach(doc =>
    {
       if (!mergedDocDict.ContainsKey(doc.docType))
          mergedDocDict.Add(doc.docType, doc);
       else
          mergedDocDict[doc.docType].pages.AddRange(doc.pages);
    };

Also, page renumbering can be done in the first loop, obtaining a single foreach:

response.documents.ForEach(doc =>
    {
       if (!mergedDocDict.ContainsKey(doc.docType))
          mergedDocDict.Add(doc.docType, doc);
       else
       {
          int existingCount = mergedDocDict[doc.docType].pages.Count;
          mergedDocDict[doc.docType].pages.AddRange(doc.pages);
          int newCount = doc.pages.Count + existingCount;
          for (int i = existingCount; i < newCount; i ++)
            mergedDocDict[doc.docType].pages[i].pageNo = i + 1;
       }
    };

Complexity should be O(number_of_docs * number_of_pages) as all dictionary operations are done in O(1).

If your documents were copied from some other data structure to your response, I think it is better to construct the dictionary from that data structure and obtain respose.documents from the merged data. Otherwise, you have to use a for loop to remove documents already merged (somewhat more convoluted than foreach version).


Class names should be PascalCase (song99bottles -> Song99Bottles)
You should indent your code or you will end up with a long code and you don't understand the various { } pairs (and an horrible code!)

public class song99bottles {
public static void main(String[] args) {
// Declare a reference variable of type song99bottles - new object
song99bottles go = new song99bottles();
// calls the method "queston" for object "go".
go.question();
}
// [...]

if you want to follow Code conventions, you code should look like this

public class Song99Bottles {

    public static void main(String[] args) {
        // Declare a reference variable of type song99bottles - new object
        Song99Bottles go = new Song99Bottles();
        // calls the method "queston" for object "go".
        go.question();
    }

    // [...]

Personally i follow the new-line style, but you will see with time you will get "your style".

i hope you understand the concept. Read wikipedia page.
You should give to your variables a more descriptive name, you should understand the scope of the variable by just reading the name. (song99bottles go = new song99bottles(); go? What is? a countdown? I could call it song (example))

About your code:

You create two song99bottles objects, why? One inside main and one inside question(). You should move question code inside main because song99bottles class should just play the song, the main will take care if the user want or not to play the song. Then in your main, just call go.lyrics();
About lyrics() code, see Roger answer.


List comprehension for reading lists of integers

You can use a map to give you what you want in a single line:

with open('input.txt', 'r') as f:
    nodes = [list(map(int, line.split())) for line in f]

An explanation of how it works:

f.readlines() iterates over the lines, with line endings removed

line.split() gives you an iterable over the space-separated characters

map(int, ...) does the conversion to int for every element

list(...) converts it to a list to give you a list of lists


115 line brainfuck interpreter written in C++

I see some things that may help you improve your program.

Use all of the required #includes

The function std::strchr is used but its declaration is in #include <cstring> which is not actually in the list of includes.

Be careful with signed and unsigned

In the interpret routine, the code compares an int i to a size_t (because that's what is returned from source.size()) but size_t is unsigned and int is signed.  Instead, declare i as size_t.

Copy and filter in one step

It's not wrong, by any means, but I'd be inclined to copy and filter all at once rather than as two separate steps.  Here's one way to do that:

std::vector<char> source;
std::copy_if(std::istream_iterator<char>(std::cin), std::istream_iterator<char>(),
             std::back_inserter(source),
             [](char c) { return std::strchr("<>+-[],.", c); }
            );

It's not critical, of course, but this way it minimizes the number of times the vector is resized.  Also note that I've altered the program to read from std::cin instead of a file.  This way, it's possible to take input from a unnamed pipe, for example, adding to the flexibility of the program.

Fix the bugs

The current implementation doesn't check to see if it runs off the end of the vector while processing a brace and it doesn't check to see that h doesn't go out of bounds.


Sorting a numbered table of contents and the contents associated with it

Just a performance tip. The function section_sort is called multiples times and you are compiling the RegEx each time. Also you are using section.split() twice in the function to get the same value. You can save these values in vars. The code would be like this:

from collections import OrderedDict
import re

headers = ['4.2.10 Context 4', '4.2.11 Context 5', '4.2.0 Context 1', '4.2.1 Context 2', '4.2.2 Context 3']
sections = ['C4', 'C5', 'C1', 'C2', 'C3']
numbering_pattern = re.compile('\d.\d[.\d]*')

def section_sort(t):
    section = t[0]

    snbr = section.split(' ')[0]
    if numbering_pattern.match(snbr):
        return [int(_) for _ in s_nbr.split('.')]

contents = OrderedDict(sorted(zip(headers, sections), key=section_sort))

for k, v in contents.items():
    print('{header}\n\t{section}'.format(header=k, section=v))


Java Matrix multiplication using Multithreading

Your basic idea is right: you can multiply matrices with heavy multithreading because each new value can be computed as a scalar product of vectors independently from the others. But I heavily doubt you need three nested loops for a scalar multiplication. Here's my approach (it is not tested and you should assure that B.getRowDimension() == A.getColumnDimension() as well as the dimensions of C before):

public void multiply(int row, int col) {
    int sum = 0;
    for (int r = 0; r < B.getRowDimension(); r++)
        sum += A.get(row, r) * B.get(r, col);
    C.set(row, col, sum);
}

This should speed up things up a lot already. If you look at this implementation, this method is the inner loop of the multiplication. The outer ones can be done concurrently and normally you use an ExecutorService and Runnable to do this.

    ExecutorService executor = Executors.newCachedThreadPool();
    for (int x = 0; x < C.getRowDimension(); x++)
        for (int y = 0; y < C.getColumnDimension(); y++) {
            final int row = x, col = y;
            executor.submit(() -> multiply(row, col));
        }
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    display(C);

You already did the right thing to use a runnable and pass the position of the cell you want to calculate, but your Runnable shouldn't wait at the end. In my case, the Runnable is created implicitly through lambdas. After having submitted all tasks, the program waits for them to terminate and then prints the result.

I don't know your implementation of the Matrix, but please make sure it can be edited from multiple places concurrently without messing up. Modifying does not have to be completely thread safe because each cell is only changed from one thread. If you are using an array internally to store the data and the set(r, c, v) method does not modify any states apart from values in the array, it should be fine.


Wrapping an asynchronous generator in Python

"Correct" is nebulous. If it were to mean here something like "the semantics of any wrapped generator through the public API is the same as if it were not wrapped, apart from a print statement before the generator is created", then, no, the code isn't correct since it doesn't preserve the effects of raising an exception or closing the generator. For example,

import asyncio

class StopItNow( Exception ):
    pass

async def f():
    try:
        yield 0
    except StopItNow:
        yield 1

async def g( f ):
    x = f()
    print( await x.asend( None ) )
    print( await x.athrow( StopItNow ) )

asyncio.run( g( f ) )
asyncio.run( g( asyncgen_wrapper( f ) ) )

. I think it would be a non-trivial undertaking to "correctly" implement a wrapper. Interestingly, in the same PEP (525) that you've linked in your question,

  While it is theoretically possible to implement yield from support for asynchronous generators, it would require a serious redesign of the generators implementation.

https://www.python.org/dev/peps/pep-0525/#asynchronous-yield-from

. You might find that it's a whole lot easier to implement some sort of injection or parameterise the generator itself to accept callables.

Otherwise, from my experimentation and taking hints from PEP 380, there are implementation details that are omitted from PEP 525 that would be necessary to emulate the behaviour of an unwrapped generator.

This is the result of some toying around:

import functools
import sys

def updated_asyncgen_wrapper( generator ):

    @functools.wraps( generator )
    async def wrapped( *args, **kwargs ):
        print( "iterating wrapped generator" )

        gen = generator( *args, **kwargs )
        to_send, is_exc = ( None, ), False

        while True:
            try:
                do = gen.athrow if is_exc else gen.asend
                value = await do( *to_send )
            except StopAsyncIteration:
                return
            try:
                to_send, is_exc = ( (yield value), ), False
            except GeneratorExit:
                await gen.aclose()
                raise
            except:
                to_send, is_exc = sys.exc_info(), True

    return wrapped

. This isn't "correct" either, since it doesn't disambiguate between an attempt to close the generator and an explicit throw of an instance of GeneratorExit, which is, though, marked distinctly for usage by the former case. This might be good enough for internal use.


Doesn't look like you've done this:

  Explain the correctness of your code, and analyze its time and space complexities.

This is an anti-pattern:

    length = len(text)

    for i in range(length):
        # code using only `text[i]`, but never using `i`

You are computing the length of text, then using a for loop of over the range(length), assigning the index to i, but then never using i for anything other than fetching the character text[i].

Far, far better is looping over the letters of text:

    for ch in text:
        # use `ch` here.

Efficiency:

        if text[i] == '(':
           # ...
        elif text[i] == ')':
           diffCounter -= 1
        if diffCounter < 0:
           diffCounter += 1
           # ...

Will diffCounter ever be negative, without first subtracting 1 from it?  No?  Perhaps the next test belongs in the elif clause:

        if text[i] == '(':
           # ...
        elif text[i] == ')':
           diffCounter -= 1
           if diffCounter < 0:
              diffCounter += 1
              # ...

But that is still subtracting 1 and then (possibly) immediately adding 1 again.  Better: check for the underflow condition first.

        if text[i] == '(':
           # ...
        elif text[i] == ')':
           if diffCounter > 0:
              diffCounter -= 1
           else:
              # ...

While the diffCounter is an understandable variable name (barely), the variable named answer is completely mysterious.  Answer to what?  Why is it incremented when there is an underflow?  Why is it added to diffCounter at the end.  Not a comment in sight, and the code is anything but self documenting.

Follow PEP-8 coding standards, and use pylint or other style checker.  For instance, variables should not be camelCase, and answer +=1 needs an extra space.


Things you did well:

Overall the code looks very nice and well organized.
You used comments well.

Things you could improve:

Syntax:

typedef your structs.

struct Stack {
  int value;
  int is_empty;
  struct Stack *next;
};

The typedef means you no longer have to write struct all over the place. That not only saves some space, it also can make the code cleaner since it provides a bit more abstraction.

typedef struct
{
    int value;
    int is_empty;
    struct Stack *next;
} Stack;

You can simplify your NULL checks.

if (head != NULL)

Since NULL is defined as (void *)0, we can treat is as a comparison to 0, making the != NULL a redundant check.

if (head)

If you don't take in any variables as parameters, you should declare them as void.

int main(void)

Error handling:

Don't use abort().  The function raises the SIGABRT signal. This, if uncaught, causes the program to terminate returning a platform-dependent unsuccessful termination error code to the host environment. The program is terminated without destroying any object and without calling any of the functions passed to atexit or at_quick_exit.  It would be much better to return an error indicator and have the calling function handle it.

return -1; // we have an error

Memory usage:

You never free() your init value.

struct Stack *init = empty();

// within empty()
struct Stack *head = malloc(sizeof(struct Stack *));
return *head;

You should probably free() it before your program terminates.  Failure to deallocate memory using free() leads to buildup of non-reusable memory, which is no longer used by the program. This wastes memory resources and can lead to allocation failures when these resources are exhausted.

free(init);

Returning:

You don't return a value from main(), even though you state you do.

int main() {
    // no return value... no indication of successful exit
}

Returning 0 is usually a typical indication of a successful exit.

return 0;


Iterative Fibonacci sequence using standard library functions

I think it's clear enough, but would benefit from some changes.

Minimize initialization

There really isn't any need to call fill for this, and really only the first two array items need to be initialized:

arr[0] = 0;
arr[1] = 1;

Check numeric limits

The code does not actually work beyond around the 94th term in the sequence due to mathematical overflow.  I used this code to verify that:

std::uint64_t last = 0;
unsigned i = 0;
for (const auto &n : arr) {
    if (n < last) {
        std::cout << "broke at term " << i << " because "
            << n << " < " << last << '\n';
        exit(1);
    }
    ++i;
    last = n;
}

On my machine, this produces the following output:

  broke at term 94 because 1293530146158671551 < 12200160415121876738

Prevent numeric overflow

Better than checking for overflow after it happens is to prevent the problem from occurring in the first place.  Here's a way to do that, but first we have to do some mathematics.

First, there is a closed form way to calculate the Fibonacci numbers:

$$ F(n) = \left\lfloor{\frac{\varphi^n}{\sqrt{5}} + \frac{1}{2}}\right\rfloor $$

where \$\varphi\$ is the golden ratio:

$$ \varphi = \frac{1+\sqrt{5}}{2} $$

For large numbers, we can approximate \$F(n)\$:

$$ F(n) \approx \frac{\varphi^n}{\sqrt{5}} $$

If we want to know how many decimal digits are in \$F(n)\$, we can take \$\log_{10}(F(n))\$.  So to be pedantic, we can create a new function \$D_F(n)\$ which estimates the number of decimal digits in Fibonacci term \$n\$:

$$ D_F(n) = \log_{10}\left(\frac{\varphi^n}{\sqrt{5}}\right) $$

In this case, we want it the other way around.  That is, rather that starting with \$n\$ and calculating the number of digits \$d\$, we want to start with \$d\$ and find the largest term \$n\$ that uses no more than \$d\$ digits. This just requires a little algebra to create a function \$N_F(d)\$ that gives the largest term number that requires no more than \$d\$ digits to store:

$$ N_F(d) = \frac{\log_{10}\left(\sqrt{5}\right) + d}{\log_{10}(\varphi)} $$

Now we can actually use the result in code by inserting a few lines above main into your program like so:

constexpr int fibterm(unsigned digits) {
    return (digits + log10(sqrt(5))) / log10((1+sqrt(5))/2);
}

template <typename T>
constexpr int fiblim() {
    return fibterm(std::numeric_limits<T>::digits10)+1;
}

Now your array can be completely safe:

std::array<std::uint64_t, fiblim<std::uint64_t>()> arr;

On my machine std::numeric_limits<std::uint64_t>::digits10 = 19, so fiblim<std::uint64_t>() evaluates to 93 and we can verify that indeed, \$F(92)\$ is 19 digits long and the next term, \$F(93)\$ is 20 digits.

Remember that std::numeric_limits<T>::digits10 tells us the maximum number of digits that can always be stored in a T reliably, so std::uint64_t can hold any 19-digit number. It might be able to store some larger numbers, (as indeed it can correctly calculate \$F(93)\$ in this case) but it's not guaranteed.

Also note the +1 at the end of fibterm.  This is due to the fact that we're calculating storage space required, rather than the term number.  So even if we only wanted \$F(0)\$, it requires 1 storage slot.

Consider possible enhancements

Because the numeric range of std::uint64 is limited, as we saw above, if you wish to calculate more terms, you will need to use some other type.  One could imagine using one of the many multi-precision numeric libraries out there, or, if the intent is to simply print them, you may want to calculate them in place as arrays of decimal digits.  This latter approach would mean that the computationally costly step of converting from binary to decimal could be completely eliminated, greatly speeding the execution of the program.

Be strict about language conformance

The code currently uses std::plus<>() as the last argument to std::transform but that is actually not C++11.  It's new in C++14 and it's a good and handy feature, properly used here, but it's not strictly C++11.

Omit return 0

Your compiler will automatically generate return 0 at the end of main so there's really no need to manually insert it.


Serving a webpage that displays the HTTP request information sent by the client

Can I use other modules to make this job easier?

You can use some web framework like fastify or express.
This would ease the code a lot

For a job this simple, is it worth to work with HTML and CSS as separate files?

Assumig your project will grown, it is a good approach to move some "static text" in a separated file.

How are HTML and CSS normally handled inside JS files (edits, appends, etc)?

You have made a server side rendering (SSR) by your hand.
Since it would be hard to manage manually all those piece of strings and would be also dandgerous to
some script injection, you could use some fremework as vue
or other templating systems like handlebarsjs or others - here a list

How well am I handling the construction of HTML and CSS?

There could be some security issue for links like that if you start to process those values:
http://localhost:3000/?user=%3Cimg%20src=%27aaa%27%20onerror=alert(1)%3E
the framework protect you from these cases usually.
This code:
  const htmlTitle = '<title>Your Request Is</title>'
  const htmlEncode = '<meta charset="UTF-8">'
  const htmlHead = `<head>${htmlTitle}${htmlCSS}${htmlEncode}</head>`
  const htmlTop = `<html lang="en">${htmlHead}<body>`

produce every time the same output string, so you could do it once instead of every request:
this will stress less the nodejs garbage collector for high throughput site.

Can this be done more concisely?

You could write less code using some Object and Array functions:
function stringTemplates (request) {
  return `

<title>Your Request Is</title>

${Object.entries(request.headers).map(processLine).join('')}
${['httpVersion', 'httpVersionMinor', 'httpVersionMajor', 'method', 'url'].map(prop => processLine([prop, request[prop]])).join('')}

`
}

function processLine ([header, value]) {
  return `<tr><td>${header}</td><td>${value}</td></tr>`
}

What would you do differently to improve this in any way?

This shows only GET, but in order to learn the HTTP standard it would useful to show in:

query parameters
form parameter (with different encoding)


In my opinion, the const semantics in JavaScript are too weak to help static code analysis or to allow for compiler optimizations. Where const is (mis-)used to signal immutability, I'd go with e.g. declaring ALL_CAPS identifiers instead.

All const does is assure you that the value assigned to it is the same value throughout the scope. If it was assigned an array, it will be the same array and not suddenly change to another array or a different value altogether.

Mutation of the value, however, is a different story. JavaScript has no concept of immutability.Object.freeze does exist, and primitives are immutable, but that's about it.

For your code, if you're aiming to avoid mutation of your arrays, temporary values, counters and all, swap your loop for array.map and create a range function. Create a range, map through it, fill it with values, repeat.

function range(n){
  return Array(n).fill(0);
}

function matrix(dim, value){
  return range(dim).map(v => range(dim).map(v => value));
}

console.log(matrix(10, 2));


Cross-platform command line tool for finding files

Let's first dispense with PEP8: by and large, as far as I can tell, your code respects PEP8. On the other hand, I've been writing Python professionally for almost 20 years and have never read PEP8 before today.

This code does a number of things that I wouldn't do, however. First, it uses

if __name__ == "__main__"

when there's no way for this code to be run any other way; it parses its command arguments from the arguments of the invocation of Python. This idiom is used to distinguish script behavior from module behavior, and your script behavior is all over the file. If you want handle_files to be useable as an imported function, you'll want to pass it all its arguments, and you'll want the option of not processing command line arguments. So really, all your command-line argument processing should be inside the conditional instead of outside - that is, assuming you want to be able to import this module as well as run it as a script. If you don't care about importing it, don't use the if __name__ == "__main__" idiom.

If you're interested in importing as an option, you also won't want to call sys.exit() in any of your module-level code (e.g., the depth_check function). Raise an error instead, and when you're running the module instead of importing, catch and exit.

I don't see the reason for the cmd_args() function. It's called once, and it creates module-level information; why should it be in a function?

On the other hand, I don't like the references to the globals all over the code - a special no-no if you're worrying about using this module by importing it. If you intend to import, my preferred organization would be:

class HandleFileError(Exception):
    pass

def depth_check(link, depth = ...):
    ... raise HandleFileError ...

def handle_files(files, cat = False, ....):
    ...

if __name__ == "__main__":
    ... process cmd args ...
    try:
        find(options.root, cat = options.cat, ...)
    except HandleFileError:
        ... report the error...
        sys.exit(1)

And you've got enough options that I'd probably create a Finder class and initialize it with the parameters, to hold the state.

On the other hand, if you just want this to be a script, I don't see the point of the find() function - it's called exactly once, after the command line arguments are parsed. I'd get rid of it.

Have you tested this code? As far as I can tell from reading it, the cat option will cause handle_files to print out None for each file that's concatenated. It's an odd mixture, either printing the contents of the files or the filenames; but one way or another, either the cat function should print the filename, or it should return the file contents, but not print in one case and return in another.

A couple small inefficiencies. First, you call CMD_ARGS.magic.lower() every time you check a file. You should call it once, when the finder is initializing, and never again. Second, in aggragate_files, you create two lists, then create a third list by concatenating the two lists, and then turn the third list into a set. At the very least, you can do this:

s = set(_files)
s.update(_subfiles)

But more globally, combining these two elements is wrong in general, because cat will always fail on the directory. Have aggragate_files return a pair, and only call cat on the files; for the dirs, just print them.

Finally, aggragate_files is misspelled; it's aggregate.


The best OOP advice I can give for this code is: stop writing classes.

Ideally, watch the video first (it’s not that long) and come back later. But here’s the gist:

  A class that has only one publicly called method (or less) isn’t a legitimate class. It should be a method.

Consequently, Rock shouldn’t be a class. It should be a method.

The rest is detail criticism. Most importantly, read PEP8 (the Python style guide) and adhere to it. Notably, this includes naming conventions, and using meaningful names.

Next, separate concerns clearly. go_player shouldn’t print text, its sole task should be to generate a random game choice. The printing should happen elsewhere.

Similarly (i.e. still a separation-of-concerns problem), neither all possible choices (i.e. choices) nor the current choice (i.e. go) logically belong in the Player. They are separate entities.

self.winner = False is logically wrong. The variable doesn’t contain a boolean value later on, why does it contain one now? Same goes for check – it should return None, not False.

Next, use a standard entry point. The following is pretty much an established pattern in Python that all code should follow:

def main():
    …

if __name__ == '__main__':
    sys.exit(main())

This way, the code can be executed directly or reused as a module.

And a check like while done == False is like fingernails across a blackboard for professional programmers: explicit checks against boolean literals never (!) make sense. Use while not done instead.

In summary, here’s how I’d do it:

#!/usr/bin/env python

import sys
import random

# The extended, cool rules:
# http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock
CHOICES = ['rock', 'paper', 'scissors', 'lizard', 'Spock']

RULES = {
    'rock': {
        'scissors': 'blunts',
        'lizard': 'crushes'},
    'paper': {
        'rock': 'covers',
        'Spock': 'disproves'},
    'scissors': {
        'paper': 'cuts',
        'lizard': 'decapitates'},
    'lizard': {
        'paper': 'eats',
        'Spock': 'poisons'},
    'Spock': {
        'rock': 'vaporizes',
        'scissors': 'smashes'}
}

class Player:
    def __init__(self, name):
        self.name = name
        self.score = 0

    @classmethod
    def create(cls, num):
        name = raw_input('What shall we call player {}? '.format(num))
        return cls(name)

    def go(self):
        return random.choice(CHOICES)

    def scored(self):
        self.score += 1

    def __str__(self):
        return self.name

def get_winner(players, choices):
    """
    Determine winner of a rock-paper-scissors round.

    Returns a tuple of (winner, winning move) if exists, else None.
    """
    def get_rule(cs):
        return RULES[cs[0]].get(cs[1], None)

    move = get_rule(choices)

    if move is not None:
        winner = players[0]
    else:
        choices = choices[::-1]
        move = get_rule(choices)
        winner = players[1]

    if move is None:
        return None

    return (winner, (choices[0], move, choices[1]))

def game(how_many_rounds):
    if how_many_rounds % 2 == 0:
        raise RuntimeError('Rounds must be an uneven number')

    players = [Player.create(1), Player.create(2)]
    winning_score = how_many_rounds // 2 + 1

    print('Best of {} - let\'s play!\n'.format(how_many_rounds))

    while True:
        choices = [p.go() for p in players]
        for p, c in zip(players, choices):
            print p, c
        win = get_winner(players, choices)

        if win is None:
            print('No winner.\n')
            continue

        winner, move = win
        winner.scored()
        print('{} {} {}. {} won this round.'.format(
                move[0].capitalize(), move[1], move[2], winner))
        for p in players:
            print('{}: {}'.format(p, p.score))

        if winner.score == winning_score:
            break

        raw_input()

    print('The winner was {}!'.format(winner))

def main():
    game(99)

if __name__ == '__main__':
    sys.exit(main())

To be honest, I’m not entirely satisfied with this since I prefer having immutable objects as much as possible, and the player objects here are not immutable. In fact, I’d probably get rid of the Players entirely and store the game state inside the game, where it belongs.

(Proper documentation is left as an exercise for the reader. I’ve only documented get_winner since it would be incomprehensible without documentation.)


Reverse the words, move the vowels and downcase everything

One-liners are good fun, but the world doesn't really need more of them. That said, they don't have to be so unreadable. What will your future brain say a year from now if you have to maintain that function?
Here's an approach illustrating a scalable technique to make even long "one-liners" readable by (1) using lines generously, (2) indenting code in the manner of a pretty-printed data structure to convey the logic's hierarchy (code is data, after all), and (3) including comments to assist the reader with the logic and intent.
def funky_words(s)
  (
    # Split into words.
    s
    .split
    .reverse_each
    .map { |word|
      # Within each word, push vowels to the end, while preserving
      # original order within consonants and vowels.
      word
      .each_char
      .sort_by.with_index { |c, i| "aeiouAEIOU".include?(c) ? [1, i] : [0, i] }
      .join
    }
    # Rejoin the new words.
    .join(" ")
  )
end


*nix, *bsd, etc basic `tput` color setup

Self-review
Since no one replied thus far, I decided to re-think and re-write the code myself this morning.

terminfo (*nix) vs termcap (*bsd)
I never really thought about how important to make note of this actually is. For searching info online, one needs to know these keywords. So, I added them as comments.
Structure into functions
I believe this code should be structured into suitable functions where available.
Find a way for an exit code from those functions
It's needed to simply chain (&&) the commands like tput_bold=$(tput bold 2> /dev/null) && tput_reset=$(tput sgr0 2> /dev/null) in order for the imagined functions to return a reliable exit code.
The most basic test missing
command -v tput was missing in my code, which is remedied now.
No unset variables
Since I use set -u in my scripts, it's necessary to set variables empty in case of failure. This feature has been enhanced.

Modified code
#!/bin/sh

set -u

tput_setup_nix ()
{
    # terminfo
    tput_cmd_set_fg_color='tput setaf'
    tput_number_of_colors=$(tput colors 2> /dev/null) &&
    tput_bold=$(tput bold 2> /dev/null) &&
    tput_reset=$(tput sgr0 2> /dev/null)
}

tput_setup_bsd ()
{
    # termcap
    tput_cmd_set_fg_color='tput AF'
    tput_number_of_colors=$(tput Co 2> /dev/null) &&
    tput_bold=$(tput md 2> /dev/null) &&
    tput_reset=$(tput me 2> /dev/null)
}

tput_setup_none ()
{
    # no unset variables
    tput_cmd_set_fg_color=
    tput_number_of_colors=
    tput_bold=
    tput_reset=
}

if command -v tput > /dev/null 2>&1; then

    if tput setaf > /dev/null 2>&1; then

        if ! tput_setup_nix; then tput_setup_none; fi

    elif tput AF > /dev/null 2>&1; then

        if ! tput_setup_bsd; then tput_setup_none; fi

    else
        tput_setup_none
    fi

else
    tput_setup_none
fi

tput_capability_test ()
{
    [ -n "$tput_cmd_set_fg_color" ] && [ -n "$tput_number_of_colors" ] && [ -n "$tput_bold" ] && [ -n "$tput_reset" ] &&
    [ "$tput_number_of_colors" -ge 8 ] && { $tput_cmd_set_fg_color 1 && printf '%s' "$tput_bold$tput_reset"; } > /dev/null 2>&1

}

if tput_capability_test; then
    color_red=$tput_bold$($tput_cmd_set_fg_color 1)
    color_green=$tput_bold$($tput_cmd_set_fg_color 2)
    color_yellow=$tput_bold$($tput_cmd_set_fg_color 3)
    color_blue=$tput_bold$($tput_cmd_set_fg_color 4)
    color_magenta=$tput_bold$($tput_cmd_set_fg_color 5)
    color_cyan=$tput_bold$($tput_cmd_set_fg_color 6)
    color_white=$tput_bold$($tput_cmd_set_fg_color 7)
else
    color_red=
    color_green=
    color_yellow=
    color_blue=
    color_magenta=
    color_cyan=
    color_white=
fi


LINQ Query returning all original objects

As the other answers stated your given code does do the same thing, but could give performance issues for big collections since the entire collection is traversed when calling Count().

The following code should solve this:

var distinct = actions.Distinct();
uxButton.Enabled = distinct.Take( 2 ).Count() == 1;

Perhaps you could turn this into an extension method:

uxButton.Enabled = actions.Distinct().CountOf( 1 );

It seemed useful, so I added it to my library, along with a unit test.

/// <summary>
///   Returns whether the sequence contains a certain amount of elements.
/// </summary>
/// <typeparam name = "T">The type of the elements of the input sequence.</typeparam>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "count">The amount of elements the sequence should contain.</param>
/// <returns>
///   True when the sequence contains the specified amount of elements, false otherwise.
////</returns>
public static bool CountOf<T>( this IEnumerable<T> source, int count )
{
    Contract.Requires( source != null );
    Contract.Requires( count >= 0 );

    return source.Take( count + 1 ).Count() == count;
}


I think your code is difficult to read/understand because of:

Inexpressive or confusing naming
Lack of any documentation
Confusing indentation and spacing. Consider using an online code beautifier

Let's start from the top.

int T = in.nextInt();
int k[] = new int [T];
int n[]  = new int [T];
for(int  i= 0;i<T;i++){
 n[i] = in.nextInt();
 k[i]=in.nextInt();
}

Mathematical notation doesn't necessarily translate very well to code, where mathematical notation is meant to represent complex concepts in short form, code is meant to be concrete applications of concepts in a way that computers can process, and humans can hopefully understand.

I did a bit of renaming to make these clearer. Note that using underscore_case is not typical for Java naming, but I think casesN or nCases didn't read well at all.

int numCases = in.nextInt();
int[] cases_N = new int[numCases];
int[] cases_K = new int[numCases];
// Populate the cases from STDIN
for (int i = 0; i < numCases; i++) {
    cases_N[i] = in.nextInt();
    cases_K[i] = in.nextInt();
}

This for loop's iterator naming is misleading:

for(int karr =0 , narr=0;karr<k.length&& narr<n.length;karr++,narr++)

In reality, karr and narr are not arrays, so let's not call them arr. Furthermore, since they are always only ever incremented together, and you already know you'll have exactly the same number of \$K\$ and \$N\$ cases, there's really no point in having both.

Also, you already have a value \$T\$ (or numCases) so there is no need to get the length of the arrays.

for (int caseNum = 0; caseNum < numCases; caseNum++)

I also replaced each other occurrence of those two variables with caseNum.

This kind of reference is used a lot inside that big loop: cases_N[caseNum] and cases_K[caseNum]. Now would be a good time to just declare N and K with those values.

This makes the next section make more sense:

int N = cases_N[caseNum];
int K = cases_K[caseNum];
int a[] = new int[N];
for (int i = 0; i < N; i++) {
    a[i] = i + 1;
}

Now we can give this a array a meaningful name: intsUpToN

int[] intsUpToN = new int[N];
for (int i = 0; i < N; i++) {
    intsUpToN[i] = i + 1;
}

We can also replace the two instances of intsUpToN.length, since that value is already known (it's the current N value) and we are not adding or removing anything from the array.

The code is already much easier to understand now. I added little snippets of code comments to make it more clear. I also combined the last two if checks into one with &&.

I removed temp because it is assigned the value of max and never used for anything except comparison, so we can just use max in the comparison instead.

Note that I did not address the algorithm, as algorithms are not my forte. It is clearly a brute force algorithm, and chances are someone who is good with mathematics can suggest a more efficient algorithm.

The resulting code passes all tests cases.

public class Solution {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int numCases = in.nextInt();
        int[] cases_N = new int[numCases];
        int[] cases_K = new int[numCases];
        // Populate the cases from STDIN
        for (int i = 0; i < numCases; i++) {
            cases_N[i] = in.nextInt();
            cases_K[i] = in.nextInt();
        }
        // Outer loop for each case
        for (int caseNum = 0; caseNum < numCases; caseNum++) {
            int N = cases_N[caseNum];
            int K = cases_K[caseNum];
            // Fill in array integers from 1 to N
            int[] intsUpToN = new int[N];
            for (int i = 0; i < N; i++) {
                intsUpToN[i] = i + 1;
            }
            // Brute force method to logically "AND" all possible values,
            // returning with the maximum "AND" result at the end
            int max = 0;
            int andValue = 0;
            for (int i = 0; i < N; i++) {
                for (int j = 1; j < N; j++) {
                    if (intsUpToN[i] < intsUpToN[j]) {
                        // This is the logical "AND" calculation
                        andValue = intsUpToN[i] & intsUpToN[j];
                        if (andValue < K && andValue > max) {
                            max = andValue;
                        }
                    }
                }
            }
            System.out.println(max);
        }
    }
}


Copying files locally with rsync and subprocess

You're calling now() twice - what will happen if the month changes between those two calls?

Your code skips all files that exist, even though your linked question indicates that you need to update changed files.

Your code checks that file is non-empty, but rsync is already doing this for you with --min-size=1.

More generally, before you code up file-sync logic, it's best to read the rsync man page and see if your problem is already solved.   Syncing files is a task full of corner cases and gotchas; life is too short for you to find them all.  Just let rsync take care of it, whenever possible.

The code below will update changed files while skipping unchanged files (as in your problem description).  If you want to copy only new, non-existing files (as in your posted code), add --ignore-existing to the rsync options.

import datetime
import subprocess

def Copy_Logs():
    Sourcedir = datetime.datetime.now().strftime("/data1/logs/%B/%b_%d_%y/")
    Destdir = "/data2/logs/"
    subprocess.call(['rsync', '-avz', '--min-size=1', '--include=*.txt', '--exclude=*', Sourcedir, Destdir ])


Function for obtaining the 3 latest patient vital signs

I would just call the VitalSigns list, but I was thinking I could make that as private and create a GetAllVitalSigns, but that seems redundant.

That depends on what you want the users of your class to allow. As it is, any user can modify everything about the contents of your objects. Depending on how are you going to use them, that might not be a good idea.
Consider whether it would make sense to make (some of) your setters private or whether VitalSigns should be more something like:
private List<VitalSign> vitalSigns;
public IEnumerable<VitalSign> VitalSigns { get { return vitalSigns; } }

Now, to the GetRecentVitalSigns() method:
public List<VitalSign> GetRecentVitalSigns()
{
    if(VitalSigns.Count > 0)
    {
        var results = VitalSigns
            .Take(3)
            .OrderBy(x => x.DateTimeChecked)
            .ToList();

        return results;
    }
    return null;
}

This seems wrong to me on several levels:

Most importantly, I think it's wrong, because you first take the first 3 items from the list and then order those 3 items. You should do it the other way around: first sort and then take the last 3 based on that.
Depending on how many items are in the list, sorting the whole collection every time might be too slow. But it's hard to suggest the best solution without knowing how the class is going to be used.

You return null when there are no results. That's a bad practice, when you want to represent an empty collection, use empty collection, not null. It will make both the code that uses the result and the code in the method simpler and avoids NullReferenceException bugs.

You return List. I see no good reason for that here, just return IEnumerable. If the caller of this method wants a List that they can modify, they can easily do that by calling ToList() themselves.

When it makes sense, make even the variables in your lambdas at least a bit descriptive. For example, using vs for a VitalSign is better then just x.

Consider whether the number of items to return should be configurable. Are you sure 3 is always the right number? You could still make it the default. (On the other hand, don't do this if you expect that 3 will be always the right number.)

This means that I would probably write the method like this:
public IEnumerable<VitalSign> GetRecentVitalSigns(int vitalSignsCount = 3)
{
    return VitalSigns
        .OrderByDescending(vs => vs.DateTimeChecked)
        .Take(vitalSignsCount);
}

Also:
public decimal BodyTemperature { get; set; }

Yes. I think that most people would use double here (decimal is just for money, right?), but decimal is probably the right choice here. (Assuming the temperature is entered by humans. If it it were somehow read directly from the thermometer, then double would make sense.)


Clickable icon for expanding/collapsing content

I've refactored your code and added comments to explain certain things.

// We can shorten this from document.ready(...) to $(...)
// Internally, jQuery will add the passed in function to a list
// of handlers that will be invoked when the document is ready.
$(function() {
    // Since the $ function will query the document with the
    // specified selector we want to cache these.
    // Doing this from within the ready callback allows us
    // to keep these references hidden.
    // I've also added the 2 function variables to keep them
    // hidden as well.
    var expandAll, colapseAll,
        expandAllElement = $("#expandAll"),
        contElements = $(".cont"),
        triggerElements = $(".trigger");

    expandAll = function() {
        contElements.removeClass("hid");
        triggerElements.html("-");
        // Notice how we can chain these calls together?
        // jQuery was designed with a fluent interface.
        expandAllElement.html("Colapse All").one("click", colapseAll);
    };

    colapseAll = function() {
        contElements.addClass("hid");
        triggerElements.html("+");
        expandAllElement.html("Expand All").one("click", expandAll);
    };

    triggerElements.click(function(event) {
        // Always define a variable so the 'name'
        // is not defined in the global object,
        var $this = $(this);
        $this.html($this.text() == '+' ? '-' : '+');
        $($this.nextAll(".cont").get(0)).toggleClass("hid");
    });

    // Using the one function allows you to skip
    // unbinding the event handler for each click.
    expandAllElement.one("click", expandAll);
});


Optimize calculation of string self-similarly with its suffixes

As far as I can tell your solution is not only slow but incorrect because of your usage of sort. Dropping that single function from your pipeline nets an exponential improvement, and it stopped including the similarity of s to itself in the answer.

Make sure also you're compiling with -O2, otherwise sum won't be optimized into a strict fold and you'll blow up the stack with thunks.

I also came up with a version targeted toward readability, but it's ~3x slower than your (corrected) ByteString based version so I'll just include it here as a curiosity.

import Control.Monad (replicateM_)
import Data.List (tails)

main :: IO ()
main = do
        n <- readLn
        replicateM_ n $ do
            s <- getLine
            print $ sum $ map (similarity s) (suffixes s)

similarity :: (Eq a) => [a] -> [a] -> Int
similarity s = length . takeWhile id . zipWith (==) s

suffixes :: [a] -> [[a]]
suffixes = tail . tails


JavaScript and RxJS Password Strength Indicator

Each subscribe(...) invocation results in creating and returning a new Subscription unless special measures are taken (like .publish(), .share()...)

  Subscribing to observables

  Remember, observables are lazy. If you don’t subscribe nothing is going to happen. It’s good to know that when you subscribe to an observer, each call of subscribe() will trigger it’s own independent execution for that given observer. Subscribe calls are not shared among multiple subscribers to the same observable. — Luuk Gruijs

Each Subscription

eats up a bit of resources;
is processed separately from the others;
and needs to be unsubscribed separately to release the resources.

Therefore, if you have no special reasons, you should subscribe the least number of times. In your case, a single subscription is sufficient. You can still use separate functions to delegate them the actual work (setClassNames(), setWarning(), setStrength()).

const { fromEvent } = rxjs
const { map, filter } = rxjs.operators

document.addEventListener('DOMContentLoaded', () => {
  const passwordInput = document.getElementById('password')
  const passwordHelp = document.getElementById('passwordHelp')
  const passwordStrength = document.getElementById('passwordStrength')

  const passwordChanged$ = fromEvent(passwordInput, 'input')
    .pipe(
      map(x => x.target.value),
      map(zxcvbn)
    )

  const setClassNames = password => {
    const state = password.score > 2 ? 'success' : 'danger';
    passwordInput.className = `input is-${state}`
    passwordStrength.className = `progress is-${state}`
  };
  const setWarning = password => { passwordHelp.innerHTML = password.feedback.warning };
  const setStrength = password => { passwordStrength.setAttribute('value', password.score + 1) };

  passwordChanged$
    .subscribe(password => {
      setClassNames(password);
      setWarning(password);
      setStrength(password);
    });
})


I think it's a matter of taste and preference. In either case, you would have to duplicate something. But, there's something that drew my attention. I don't claim it to be correct or be a solution to your problem. Hard to say without knowing the context and data structures that you use. Anyways, here we go...

I noticed that in both cases, whether best == null or not, you pass the same arguments, though to different methods. I suspect that this checking might occur in many other places as well. So, what if we create a method (e.g. addOrModify()) and move this condition statement to that method. And the method would internally decide whether to add a new State or modify the existing one. Somewhat similar behavior may be observed in the java.util.Set.add(E e) method, where the method checks if the element has already been added to the Set and then returns false without adding it twice...

Then, we end up with something like this in the client code:

Double best = nodes.get(edge.getToNodeId());
if (best == null || (best > g+h)) {
    nodes.put(edge.getToNodeId(), g+h);
    open.addOrModify(new State(edge.getToNodeId(), g, h, top));
}


Socket.io Node.js Object Oriented Code Structure Approach

Just a few comments:

1:
The Room class can quickly become a place to throw in all sorts of functionality, even when it's not needed by all its children.
I would be careful to not put much there at all, and rather compose the different rooms with needed functionality.
For example, a GameRoom may be composed by a chat, game queue, lobbies, and even user management.
Using composition like this can make it much easier to build different types of rooms, without having to throw every bit of common code into Room. I would even consider removing Room altogether if possible.

2:
In your socket callbacks, I would only put in single function calls to methods in your class.
This way, if you want to test one of these functions, you don't need to go via the socket callbacks.
Also, when instantiating your classes, I would consider not running the listener immediately.
If you're testing this, you don't want the hassle of mocking up io if you don't need to.

But I think an even better way to do this would be to abstract away the socket stuff from these classes entirely.
This could be a bit too much though, depending on the complexity of the app.

3:
Consider replacing

this.lobbies.push(new Lobby(this.name ,lobbyId, participants, this.io));

with something like

this.lobbies.push(this.lobbyFactory.create(this.name, lobbyId, participants));

This is useful for testing, since you don't force the usage of one particular lobby.
It's also useful if you decide to have different types of lobbies later on.
Then you can just inject another type of lobbyFactory.


Some tips:

you'd probably better have a look at some jquery validation plugin that would do what you are looking for out of the box
to solve your "unknown parameters", you could probably use the jquery .serialize() function and loop through the array


Follow-up: Find number of times that difference of array values are equals to a number

Using a Set is problematic.

First, as pointed out on the original question in @Vogel612's comment, it restricts duplicate values. Second, it also makes your code a lot messier, as you're now grabbing an Iterator, calling .hasNext(), and testing in a while loop instead of using more concise syntax.

I'd just use a List<Integer>, get rid of all the casts, and use a for-each style syntax instead of using the Iterator. Finally, number and counter aren't very meaningful as variable names in the context of this snippet.  If they are meaningful in the wider context of wherever this came from so-be-it, but I find something more along the lines of difference and result much clearer.

Something more like this:

List<Integer> tchars = Arrays.asList(10, 21, 34, 45, 56);
int difference = 11;
int result = 0;

for (int test : tchars) {
    if (tchars.contains(test + difference)) {
        System.err.println(test + " " + difference);
        result++;
    }
}

System.err.println(result);

Dead simple, and you can see immediately what it is doing.


You can use a CASE statement in your SET to choose the operation to perform.  Not only will this make maintenance easier, it will improve performance as well since you'll only be touching the target table once.

UPDATE  #BalSheet
SET OBCr = CASE
             WHEN trialDeb.JournalCredit = 1 THEN OBDr + ISNULL(trialDeb.Amount, 0)
             WHEN trialDeb.JournalCredit = 0 THEN OBDr - ISNULL(trialDeb.Amount, 0)
           END
FROM  ( SELECT  v.AccountId,
                v.CompanyId,
                v.JournalCredit,
                SUM(ISNULL(v.Amount, 0)) AS Amount
        FROM  #vwJournalDetails AS v,
              #TempJournalHeader AS h
        WHERE v.JournalCredit IN ( 0, 1 )
          AND h.JournalId = v.JournalId
          AND h.CompanyId = v.CompanyId
          AND h.JournalDate >= @dtPrevFinUnclosedSDate
          AND h.JournalDate <= @dtLastFinUnclosedEDate
        GROUP BY v.CompanyId,
                 v.AccountId,
                 v.JournalCredit) AS trialDeb
WHERE trialDeb.Accountid = #BalSheet.AccId
  AND trialDeb.CompanyId = #BalSheet.CompanyID
  AND trialDeb.CompanyId = @intCompanyId
  AND #BalSheet.AcType = 'L' ;

Note that I don't know if you still need the v.JournalCredit filter so I just changed it to an IN clause to ensure only 0 & 1 were touched.  If those are the only two possible values, you can remove that predicate to improve the performance as well.


TDD svino Problem #4 - largest value from concatenated integers?

Style - good

The TDD is a great way to start. You can see the benefits already, especially in the fact that it was easy for me to copy your code and run it locally, and make sure it works (not that I doubted it, but it's nice to check).

There's a typo in a method name... I know that's a silly thing to point out, but it is the first thing I saw. My spelling (actually, my typing) is often criticised, and as a result I am sensitive to these things. The method getLargestLexiographcal is missing an i here: getLargestLexiographical.

Beyond that, though, the code is really neat, and well structured. Two nit-picks.... in your bracing style (yeah, yeah, I know, not the bracing....!) But, you should be consistent with the space before the opening brace. Sometimes you have a space before the brace, and sometimes, not. You should have a space. So, for example, the lines:

        if (firstVal != secondVal ){
            if (firstVal > secondVal){

should be:

        if (firstVal != secondVal) {
            if (firstVal > secondVal) {

The other nitpick is the newlines in the else block. Yeah, it's a real nitoick, but I prefer a single-line for the } else {, not 3 lines. Still, there is only one instance of this, so at least it is consistent ;-)

OK, enough about the trivials....

Minutia

String concatenation to get a String value of an Integer is overkill... things like:

 String first = "" + a;

Really, that should be:

 String first = a.toString();

The Integer.valueOf(...) in the following line should also probably be Character.getNumericValue(...):

Integer.valueOf(first.charAt(Math.min(i,first.length() - 1)))

should be:

Character.getNumericValue(first.charAt(Math.min(i,first.length() - 1)))

Sorting

Your sorting algorithm is simplistic, but effective. A bubble-sort, of sorts. The major drawback I see is the many comparisons, especially given that each comparison is performed from first-principles... calculating the lexographical value each time, instead of memoizing it.

All told, though, I really would have preferred to see a standard-library sort using a Comparator for the comparisons.... The comparator would look something like:

private static final Comparator<Integer> LEXIOGRAPHIC = new Comparator<Integer>() {

    @Override
    public int compare(Integer a, Integer b) {
        // same values compare the same.
        if (a.equals(b)) {
            return 0;
        }
        String first = a.toString();
        String second = b.toString();

        for (int i = 0; i < Math.max(first.length(), second.length()); i++){

            int firstVal = Character.getNumericValue(first.charAt(Math.min(i,first.length() - 1)));
            int secondVal = Character.getNumericValue(second.charAt(Math.min(i,second.length() - 1)));

            if (firstVal != secondVal ){
                if (firstVal > secondVal){
                    return -1;
                } else {
                    return 1;
                }
            }
        }

        return 0;
    }

};

Then, with that comparator, you can just sort the list:

public String largestNumberFromList(List<Integer> input){

    input.sort(LEXIOGRAPHIC);

    return getStringFromList(input);
};

The sort used will be the native sort in Java, an efficient TimSort, I believe.

When possible, use the library functions available....

Alternative

I would recommend creating a number class, that implements Comparable, then, when you process the system, just create a new instance of that class for each input value. The constructor should create the lexographical value at that time, and the comparator will then be much simpler too. If you add the values to an always-sorted collection, like a TreeSet, then you can just do it all in one go.

Hmmm... in retrospect, I played around with it, and came up with the following class, and a 'simple' lambda expression to arrange it.... Note, the compareTo function is a 'clever' trick of appendign each value in opposite orders, and then comaring them. It makes the relative order easy to compute. It may not be the fastest, but it sure is simple to read....

private static final class LexiVal implements Comparable<LexiVal> {

    private final String value;

    public LexiVal(int value) {
        this.value = Integer.toString(value);
    }

    @Override
    public int compareTo(LexiVal o) {
        final String usthem = value + o.value;
        final String themus = o.value + value;
        return themus.compareTo(usthem);
    }

}

public String largestNumberFromList(List<Integer> input){
    return input.stream()
                .map(i -> new LexiVal(i))
                .sorted()
                .map(x -> x.value)
                .collect(Collectors.joining());
};

Aas a side note, that same logic used in the LexiVal could be used in the Comparator instead.....

private static final Comparator<Integer> LEXIOGRAPHIC = new Comparator<Integer>() {

    @Override
    public int compare(Integer a, Integer b) {
        String ab = a.toString() + b.toString();
        String ba = b.toString() + a.toString();
        return ba.compareTo(ab);
    }

};

then your algorithm becomes:

public String largestNumberFromList(List<Integer> input){
    input.sort(LEXIOGRAPHIC);
    return getStringFromList(input);
};

Additionally, the getStringFromList(input) can be made in to a Jav8 stream, with:

return input.stream().map(i -> i.toString()).collect(Collectors.joining());


Your indenting is weird. In getdig, you deindent, then reindent.

Variables should always be camelCase or, if they're constants, UPPER_SNAKE_CASE -- int Max should be int max or final int MAX, depending on if you want to make it clear that it's a constant. I also think it should be a class variable, not a local variable in a method.

Put a space on either side of your binary (two-argument) operators -- so int n=x becomes int n = x, i<max becomes i < max, etc. Note that things like ++ and ! are not binary, since they only take one argument.

Method names are camelCase as well, where the humps are on word boundaries. isarmstrong should be isArmstrong.

Use meaningful names! sp, getdig, n, sp -- none of these mean anything. It's fine to have long names -- don't use any abbreviations but the most obvious ones. Id sit, getIP would be fine; you don't need to write getInternetProtocolAddress.

if (/* condition */) {
    return true;
}
return false;

is a pretty common way to add lots of characters with no meaning. Just write

return /* condition */;

replacing /* condition */ with the actual code. In this case, that's n == getDig(n).

You have a bunch of lines with nothing but whitespace; the convention I've seen is to separate methods and logically distinct blocks of code. You have a bunch of whitespace just before the method ends, or just after it begins.

In isArmstrong, you assign n to be equal to x, then never use x again. Why not ditch n and just use the original variable?

In getdig's for, a couple of things.

Firstly, a = a + b can be shortened to a += b and it's understood what that means.

Secondly, since none of the other code relies on the changing of d -- in fact, you moved one line to keep it from interfering -- why not visually separate it by moving it to the bottom and plopping a blank line between?

As for your actual math, though, it looks good. It's rather hard to tell, since your names mean absolutely nothing, but no matter.

With all of these applied (except the better names -- you should do that yourself, since you know what they are) here's how your code looks:

public class Armstrong {
    public static void main (String arg[]){
        int max = 2000000000;
        for (int i = 0; i < max; i++){
            if (isArmstrong(i)){
                System.out.println(i);
            }
        }
    }

    private static boolean isArmstrong(int n) {
        return n == getDig(n);
    }

    private static int getDig(int sp){
        int d = sp;
        int r = 0, dg = 0;
        int length = String.valueOf(sp).length();
        if (length > 1){
            for (int count = length; count >= 0; count--){
                dg = (int) (d / Math.pow(10, count));
                dg = (int) Math.pow(dg, length);
                r += dg;

                d = (int) (d % Math.pow(10, count));
            }

        }
        else {
            r = sp;
        }
        return r;
    }
}


String Matching w/o repeating the comparisons for common part of the two strings

Confirm if things work the way I explained. My tests seem to be working fine.

I'm afraid not. For example, for text hehehello and pattern hehello, the output is 0 instead of 2. You see, the algorithm prematurely exits after heheh, when it should continue searching from position 2.

With your modified version this test case passes, but fails for text heheehello and pattern hehello, incorrectly returning 3 instead of -1.
(In the future, please do not modify the code in the question after you received answers. Changing the code typically invalidates answers, as it did in this example too.)

See the Knuth-Morris-Pratt algorithm for something that actually works.

  What is the complexity of this approach? Is it worst case O(n⋅k) still?

The complexity of your algorithm is \$O(n + k)\$, same as that of KMP. Unfortunately it doesn't really matter, because it doesn't work correctly.

Usage

The usage of your class is a bit awkward:

int index = new ModifiedSearch(text).findPattern(pattern);

I recommend to rewrite to make it work this way:

int index = ModifiedSearch.findPattern(text, pattern);

That is, turn the class into a static utility method.
It will be lighter that you don't have to create an instance of the class.

Looking at the function name "findPattern" alone, it's not obvious what it returns. Since the function returns an index, like String.indexOf, I recommend to rename it to indexOf. Or, rename to contains and make it return a boolean.