Assignment Branch Condition size for fetch_images is too high. [22.41/15]

What that warning is saying is that, according to rubocop's standard, you have too many assignments, branches, and conditionals (ABCs) in that method. ABCs are associated with code that is complex and harder to reason about. It can also indicate that a method is trying to do too much, as I would say it is telling you about this method.

Looking over the method in question, we can clearly see it has several responsibilities:

Guard clauses for validity
Tokenizing a proxy string into a hash data structure
Setting a proxy with the data from that data structure
Tearing apart and rebuilding a URL
Fetching a page over HTTP
Parsing markup for image tags, and shoving them on an array
Filtering that array of images
Returning that array

That's a lot of responsibilities for one method. It's dealing with several different types of objects/behaviors at several different levels of abstraction. We can, and should, break it up to make it easier to manage.

Before I do that, I'm going to look at the rest of the class (the initialize method). In the initializer, I see a lot of state assignment, and I see some work beyond just state assignment.

@agent = Mechanize.new

Here you are getting a new instance of Mechanize, but you are doing it directly in the constructor. I would recommend injecting this as a parameter instead. You could even use a default parameter to give you flexibility:

def initialize(agent = Mechanize.new)
  @agent = agent
  ...

This gives you the ability to change this dependency at runtime, and to mock or stub this dependency in your tests.

@agent.user_agent_alias = Mechanize::AGENT_ALIASES.keys
  .reject { |agent| agent == 'Mechanize' }.sample

Here is some more of the extra work being done in the initialize method. Ideally, you should get a fully initialized object injected, and you should not need to to any extra configuration with it. In this case, you might want to create a MechanizeFactory class to encapsulate the construction and initialization of Mechanize objects so you don't have to worry about any of this in your constructor:

class MechanizeFactory
  def self.get
    mechanize = Mechanize.new
    mechanize.user_agent_alias = Mechanize::AGENT_ALIASES.keys
      .reject { |agent| agent == 'Mechanize' }.sample
    mechanize
  end
end

...

class WebCrawler
  def initialize(agent = MechanizeFactory.get)
    @agent = agent
    ...

@tumblr = URI('http://www.tumblr.com')

Here you are setting the URL to the Tumblr main site as an instance variable. The way you use it does not really make it appropriate to be an instance variable. I will discuss why and alternatives further down, but for now I am going to say that this line is unnecessary.

@images = []

You are creating an instance variable to hold the list of returned images. I don't see any reason that this object needs to hold this state; the list of images can simply be returned from the fetch_images method. This line is also unnecessary.

Now onto the fetch_images method.

fail Exceptions::InvalidBlog unless valid_blog?(blog)
fail Exceptions::InvalidProxy unless valid_ip?(proxy)

Here are your guard clauses. For now, I'm going to just leave them as they are.

tokens = proxy.split(':')
proxy_addr = { ip: tokens[0], port: tokens[1].to_i }
@agent.set_proxy(proxy_addr[:ip], proxy_addr[:port])

Here is one place where a lot is happening. We are doing string tokenization, data structure juggling, and setting more properties on @agent. I would first have to ask if the proxy really changes with each request. I think it would probably be better to simply set the proxy in the MechanizeFactory.get method by passing it in by parameter. If it does need to change, there are other strategies to deal with it, but for now I'm going to go on my assumption. This means those three lines are effectively gone, with their functionality relocated. The proxy parameter and proxy validation guard clause are also gone.

@tumblr.host.gsub!(/^w{3}/, '').insert(0, "#{blog}")

Now we are statefully changing that URL instance variable, which I said we no longer need. We can use a local variable, but this still deals with a lower level of abstraction than the rest of the method. We should extract it to a private helper and call that from our code. We can also just combine it with the following line to avoid the need for a temporary local variable.

class MechanizeFactory
  def self.get(proxy = '') # Or some logical default for proxy
    fail Exceptions::InvalidProxy unless valid_ip?(proxy)

    mechanize = Mechanize.new

    mechanize.user_agent_alias = Mechanize::AGENT_ALIASES.keys
      .reject { |agent| agent == 'Mechanize' }.sample

    proxy_ip, proxy_port = proxy.split(':')
    mechanize.set_proxy(proxy_ip, proxy_port)

    mechanize
  end
end

...

class WebCrawler
  def initialize(agent = MechanizeFactory.get)
    @agent = agent
  end

  def fetch_images(blog)
    page = @agent.get(get_blog_uri(blog))
    ...
  end

  private

  def get_blog_uri(blog)
    fail Exceptions::InvalidBlog unless valid_blog?(blog)
    URI("http://#{blog}.tumblr.com/")
  end
end

page.search('img[src$="jpg"], img[src$="png"]').each do |img|
  @images << img['src']
end
@images.keep_if do |img|
  img =~ %r{^https?://\d+|media} && img !~ /avatar/
end

Here you are doing an XPath search, shoveling the results onto an array, and then filtering the array. This is also at a different level of abstraction, and it can be optimized. We can move it into it's own private helper method. We don't have the @images instance variable, but page.search returns an Enumerable object that we can call map on, and then manipulate. The final product looks like:

class MechanizeFactory
  def self.get(proxy = '') # Or some logical default for proxy
    fail Exceptions::InvalidProxy unless valid_ip?(proxy)

    mechanize = Mechanize.new

    mechanize.user_agent_alias = Mechanize::AGENT_ALIASES.keys
      .reject { |agent| agent == 'Mechanize' }.sample

    proxy_ip, proxy_port = proxy.split(':')
    mechanize.set_proxy(proxy_ip, proxy_port)

    mechanize
  end
end

...

class WebCrawler
  def initialize(agent = MechanizeFactory.get)
    @agent = agent
  end

  def fetch_images(blog)
    page = @agent.get(get_blog_uri(blog))
    extract_images_from_page(page)
  end

  private

  def get_blog_uri(blog)
    fail Exceptions::InvalidBlog unless valid_blog?(blog)
    URI("http://#{blog}.tumblr.com/")
  end

  def extract_images_from_page(page)
    page.search('img[src$="jpg"], img[src$="png"]').map do |img|
      img['src']
    end.keep_if do |img|
      img =~ %r{^https?://\d+|media} && img !~ /avatar/
    end
  end
end

There is more that can be done, I am sure, but this at least starts to break the code down into smaller, more focused pieces.


Less-repetitive code for document-analyzer

To my eyes, there should really only be one class: Document.

As you noticed, the methods in DocumentAnalyzer all use @document. The analyzer class is so tied up in Document (and its methods are so simple) that it probably shouldn't be a wholly separate class.

But if there's a reason for it to be separate class (I can't think of any), then there's nothing inherently wrong in referencing the same variable in several places.

DRY does not mean "Don't ever repeat anything, ever!". It means "Don't duplicate logic". Accessing a variable isn't in itself logic; logic is what you do with it.

So if you want to always upcase all the words (or something), you should make a method to do that for you, instead of repeating that bit of logic everywhere you need it. But even so, you'd still have to call your upcased_words method in all those places, so it's not like you can avoid any and all repetition.

And no, don't collapse your methods. A single line is still a method body. Collapsing code is practically only used when you make a completely empty method or class on purpose, and want to really highlight that it's intended to be empty. E.g. def no_op; end.
You'll also see it in code that defines custom exception classes. The classes just inherit from an existing exception class, but they neither add or override anything; the point is just to define them as distinct classes. Hence, they're usually defined with class CustomError < ExistingError; end

Other things I noticed:

Fix your indentation. Sometimes it's 2 spaces, sometimes it's 4. Stick to 2.
Your Document class could - in its current form - be replaced by a plain array, really. It doesn't really do anything as it is right now. I'd expect a class named Document to (for instance) have methods to load/read a file or something. Instead, you give it an array, and it stores that array. But if you already have that array, why bother?
You don't need Set. You can just do words.uniq
Your total_characters method is odd. Why does total start out as a float? It'll always be an integer (unless you've discovered fractional characters)
Speaking of, the summing up can be done with inject (aka reduce)

def total_characters
  @document.words.inject(0) { |sum, word| sum += word.length }
end

Also, the method should probably be called character_count to stick to the convention established by word_count and unique_word_count. Neither of those is called total_...
You should probably memoize your methods. That is, store the return value after calculating it the first time, so it doesn't have to be calculated again later:

def total_characters
  @total_characters ||= @document.words.inject(0) { |sum, word| sum += word.length }
end

This code will return the instance variable immediately unless it's nil or false. Otherwise, it'll actually evaluate the right-hand expression (i.e. sum up the character count), assign the result to the instance variable, and then return the value.
If you want to memoize return values, you should also freeze the words array. Otherwise you can do something like some_document.words.fill("foobar") after which your previously computed values stop making sense.
I might just skip the *_count methods, since they're not even shortcuts. Anyone can call some_document.words.count or some_document.unique_words.count. Heck, you could even skip unique_words since it's the same as words.uniq (which is even shorter!).
Basically, if the class itself doesn't rely on a method, and the logic is trivial, there's no reason to add that method (i.e. unique_words isn't used by the class, and is very trivial).
Edit As jwg points out in the comments, memoization might be a good reason to add a method "ahead of time". Still, if the class itself doesn't have an obvious use for the method, think twice before adding it.

Here's what I might write

class Document
  attr_reader :words

  def initialize(words)
    @words = words.dup.freeze
  end

  def characters
    @characters ||= words.flat_map { |word| word.chars.to_a }.freeze
  end

  def average_word_length
    return 0 if words.empty? # avoid division by zero
    characters.count / words.count.to_f
  end
end

Again, I don't think the *_count methods add anything, since you can just write .count anyway:

doc = Document.new(%w(here are some words))
doc.words               # => ["here", "are", "some", "words"]
doc.characters          # => ["h", "e", "r", "e", "a", "r", "e", "s", "o", "m", "e", "w", "o", "r", "d", "s"]
doc.average_word_length # => 4.0
doc.words.count         # => 4
doc.characters.count    # => 16
doc.words.uniq          # => ["here", "are", "some", "words"]
doc.words.uniq.count    # => 4

As you can see, I've also left out the unique_words method, because it's so simple. However, if the words array is very long, it might be more efficient to provide a memoized method for people to use. I.e.

def unique_words
  @unique_words ||= words.uniq
end


Looks to me like there's a lot of duplication here. I.e. boilerplate stuff you'd probably end up copy/pasting (and having to deal with the consequences of that later).

I'd just pare it way down for now: All that really changes is the URL. A really simple version might be:

ta.api = (function ($) {
  // private helper function
  function get(url, success, error) {
    return $.ajax({
      url: url,
      success: success || ta.callbacks[url].success;
      error: error || ta.callbacks[url].error;
    });
  }

  return {
    heartbeat: function (success, error) {
      return get('/rs/heartbeat', success, error);
    },

    version: function (success, error) {
      return get('/rs/version', success, error);
    }
  };
}(jQuery));

There are two assumptions/changes here:

You'd use the url as the property name for default callbacks to avoid having to maintain a separate callType variable, and
It assumes that you either pass a function or a false'y value (e.g. null or just nothing) for the callbacks. I.e. don't pass something truthy that's not a function.

Similarly, it assumes that ta.callbacks[url].* is either undefined or a proper function.

However, there's a potential bug if ta.callbacks[url] itself is undefined. So a safer option would be:

  function get(url, success, error) {
    return $.ajax({
      url: url,
      success: success || (ta.callbacks[url] ? ta.callbacks[url].success : null);
      error: error || (ta.callbacks[url] ? ta.callbacks[url].error : null);
    });
  }

If you want to keep your setDefaultIfNeeded, there are few issues with it. For one it's name is not terribly decriptive: Set a default what? A string? A number? It's very specifically a type-checking function that only looks for functions, but given the name, I might think I could use it for anything. And despite its name, it doesn't actually set anything. It just returns, so it should rather be called get....

Secondly, it can be shortened considerably:

ta.utils = {
  getValidCallback: function (providedHandler, defaultHandler) {
    if(jQuery.isFunction(providedHandler)) return providedHandler;
    if(jQuery.isFunction(defaultHandler)) return defaultHandler;
    return function () {};
  }
};

I honestly don't have a good idea for a name (getValidCallback is ok, but not great), because I'd just stick to the first option of using || and simply not have this function.

As for using promises/deferreds instead, the above code allows for that automatically. The result of $.ajax is itself a promise object, and since this code returns it (your function didn't return anything), you can use it both ways:

ta.api.heartbeat(foo, bar);
// or
ta.api.heartbeat().then(foo, bar);


When should I call set_exception_handler with this exception handler class?

Some general things to consider:

As stated in the docs, the handler's signature is: void handler ( Exception $ex ), note the type-hint. Below is a lengthy explanation as to why this type-hint is important.
Your handler is not static (nor should it be). set_exception_handler expects the argument to be callable: set_exception_handler ( callable $exception_handler ). What if I destroy your class? The handler is not unregistered. I'd like to have a method that calls the restore_exception_handler function. Removing the handler this class registers.
Add properties that capture the exception handlers' state prior to registering your handler, so you can restore it correctly, and allow users to pass arguments to the contructor that allow them to control the behavior of your handler
Whenever you're writing echo in a class method, take a step back. Think of a case where you really don't want to echo everything to the end-user. If your handler catches an unhandled PDOException instance, do you really want the end-user to see everything about how, when and where you're trying to connect to the DB? Probably not.

There are a lot of things you should think about when writing something like an exception handler. It's a component that plays a vital part of any sizable application. Therefore, it should allow a lot of customization, and it should be extendable. This, in turn, implies that your base handler is as generic as is humanly possible. Generic code is hard to get right, so it's a very good exercise. I'll leave you with these critiques for now. If you want to, apply them to your code, and perhaps submit the result for another review here later.
Also take a peek at how other projects implement exception handling (Symfony2, Zf2, Codeignitor, ... they're all open source. Copy-pasting their code is not allowed, but you can look at them for inspiration)
Am I calling set_exception_handler in a suitable place?
IMHO, not really. If I use an exception handler class, I'd expect to be able to set it up some more. I want to customize a thing or two like: where does the exception handler send its output to, how should the exception handler format the exceptions. I may want to set the handler up differently depending on the environment (production behavior vs development).
When I see a handler as minimalist as yours (minimalism is a good thing in code), I'd probably think about extending it, to best suite my needs. I might add a logger property, which I can use to write output to (instead of echoing it). I could also choose to log the exceptions to the DB, or have the handler call a webservice. Your class makes this rather difficult to do:
You've probably come across references to the SOLID principles. An important part of this, and one that is too often overlooked or not understood, is the Liskov principle. This states that, in order for a child to comply with the substitution principle, it is not allowed for that child to strengthen the contract it inherits from the parent. What does that mean, well let's look at your handle method's signature:
public function handle($exception)

If I extend your class, but I don't want this handle method to handle objects that aren't instances of the Exception class, I might want to add a type-hint:
class MyHandler extends ExceptionHandler
{
    public function handle(Exception $exception)//only accepts Exception instances
    {}
}

This, according to the Liskov principle is not allowed. Because MyHandler extends your class, any code using my child class has to be able to assume that the contract (number of arguments, type requirements and visibility of members) is the same. Meaning: public properties remain public, protected properties have to be at least protected, too (public is allowed, private is not).
By my adding this simple type-hint, I'm breaking this rule. To clarify, take this example:
class Model
{
    public $data = null;
    public function setData($value)
    {
        $this->data = $value;
        return $this;
    }
}
class ArrayModel extends Model
{
    protected $data = [];//<-- reduce visibility
    public function getData($offset = null)
    {
        if ($offset === null)
            return $this->data;
        if (!isset($this->data[$offset]))
            return null;
        retrun $this->data[$offset];
    }
    public function setData(array $value)//strengthen argument restrictions
    {
        $this->data = $value;
        return $this;
    }
}

Now, at first glance, you may not see the problem: I'm using a generic Model class as a data container, and extend it to create a data container that only deals with arrays. But let's say there's a piece of code that looks like this:
function initData(Model $model)
{
    if ($model->data === null)
        $model->setData('initialized');
    return $model;
}

This function uses a type-hint to ensure that the $model argument will be an instance of the Model class. Because this is guaranteed to be the case (if not, PHP will generate a fatal error), it should be safe to assume that the data property is public, and the setData method accepts a string as an argument. However, if I were to pass it an instance of ArrayModel, these assumptions are false: data is protected, and setData only accepts an array argument.
Bottom line
Your ExceptionHandler class is too permissive to be extended in a safe, meaningful way.
Now this wouldn't be much of a problem if I were able to do everything I wanted with your class as it stands, but like I said in the beginning: I can't.
Because you simply have to add customization support to your class, and rethink the contract this class imposes, you simply can't call set_exception_handler in the constructor. I want to be able to extend this class, set up everything I need to set up, and then register a handler when, where, and how I want to register it.
I also want to be able to register several handlers, and perhaps unregister them if I need to. Your class seems to have been written under the assumption that no other handlers are registered, and no other handlers will be registered after your handle method. That's just not right.


DRY. queue_push assigns queue_back to the input_node no matter what. Consider
  if (input_queue->front == NULL) {
      assert(input_queue->back == NULL);
      input_queue->front = input_node;
  } else {
      assert(input_queue->back != NULL);
      input_queue->back->next = input_node;
  }
  input_queue->back = input_node;

(asserts are there only to clarify the logic).
Ditto for queue_pop.

Usually we don't want the client code to be aware of the containers, neither depend of them. If perchance you'd eventually decide to keep the weighted coordinates in a tree rather than a list, you'd need to redesign struct Weighted_coord_node, and the surrounding code. I strongly recommend to have struct Queue_node keeping the pointer to the actual data
  struct Queue_node {
      struct Queue_node * next;
      void * client_data;
  };


Given a binary tree, find the maximum path sum

If you want \$−∞\$, just write float('-inf').
The names could be improved by removing the common prefix max_path_, using to instead of from, and node instead of current. (The replacements are shorter than the originals, so reduce the size of the code without reducing readability.)
The computation of max_path_from_current (which becomes to_node after my renaming), can be simplified by pulling the addition of node.val out of the call to max:

to_node = node.val + max(0, to_left, to_right)

Since max_path is only called from maxPathSum it makes sense for it to be a local function there. Then you could avoid the unnecessary use of self.

Revised code:

def maxPathSum(self, root):
    def max_path(node):
        if node is None:
            return 0, float('-inf')
        to_left, in_left = max_path(node.left)
        to_right, in_right = max_path(node.right)
        to_node = node.val + max(0, to_left, to_right)
        in_node = max(in_left, in_right, to_left + node.val + to_right, to_node)
        return to_node, in_node
    return max_path(root)[1]


AngularJS services for APIs in large applications

it seems more and more impractical with as interconnected as the app is

You mentioned 30+ APIs. Let's start with that. If all of a sudden, someone from the API team decides to change the semantics for several of the APIs, where would you be starting your end of the change?

Another scenario would be if your manager told you to scrap your code because you'll have to start a new project... using the same API. You'll of course throw away the template and controller because they're app-specific. But the way you wrote your code, you'll also be throwing away all your API. Nothing is spared.

The Angular Way™ of doing this is that anything data-related should live in factories/services while anything UI related lives in the controller, templates and directives. Reasons for doing so includes:

You write the data source just once.
You can easily share data sources across different controllers.
You can easily throw away the UI layers without involving the data layer.

I normally start writing Angular apps by defining my data sources. Once that's done, I build the UI layers and just pull in the dependencies I need. If I want user info in this controller as well as another controller, I don't have to write 2 AJAX calls. All I would need is to pull in the same factory and call the same function in both controllers.

In your app, start by writing every single one of those APIs in its own factory . This means the following code should be gone from the controller:

$http.get('/api/qryListingAPI/?project=' + $scope.project.ProjectID)

Now if you were thinking of writing every single API as an $http call, that's where you got it wrong. Angular has this thing called $resource. Hand it a REST-compliant endpoint and it provides you an object with REST methods. A factory could even be as simple as:

app.factory('QueryListing', function(){
  return $resource('/api/qryListingAPI/');
});

If you did it with factories, no matter how many grids you have, you only need to write the API just once in the service, and just pull in the service. Additionally, resources expose promises. You can easily pop in a then.

app.controller('MainController', function($scope, ..., QueryListing){
  QueryListing.get(...).$promise.then(function(){
    ...
  });
});


While I agree with most of what's been said in the comments, I do think that writing your own linked list is a worthwhile exercise. (Though so is learning about reallocating arrays.) So I'll go with that premise - that it's worth your time to write a linked list. And I think you've done a pretty good job to start with! Here are some suggestions.

Don't Reinvent The Wheel

You've written your own functions for count_to_next() and string_copy(). There are functions in the standard C library that do these same things, so you don't need to write your own. Instead, you could use strpbrk() and strdup() or memcpy(). strdup() actually allocates the memory for you, if you want to go that route.

Edit: Also, instead of calling malloc() and then manually setting each field to 0, you can use calloc(sizeof(Node), 1); to both allocate and clear the memory.

Use Types

You should create type definitions for your structures to make it easier to read and save some typing. I'd do this:

typedef struct Node {
    void* value;
    struct Node* next;
} Node;

Then, whenever you declare one, you can simply write:

Node *root;

instead of:

struct Node *root;

Avoid Magic Numbers

Instead of just putting the number 20 into your code, you should either have a named constant telling you what the value 20 represents (something like const int TEST_STR_LENGTH = 20;, or get the value from the string so you can change the string without having to update the value in the code. Like this:

int remaining = strlen(raw);

Name Your Variables Appropriately

The variable names raw, pointer, and buffer aren't very informative. I recommend naming them something like input_string, next_line, and string_copy or something along those lines.

Bugs

I think the last line is incorrect. I think it should be:

lines = root;

Otherwise you're starting with the second line.

Also, you were starting with an empty node with an uninitialized string, and ending with an empty node with an uninitialized string. I fixed the first by setting the value field of last before allocating a new node. I fixed the second by only allocating the next node if we have some characters remaining in the string.

Edit: I also realized that both of our implementations have another bug in them. If the file (or input string) is empty, we end up with a list containing an empty node, whereas we probably should not have a list at all. You could fix that by not allocating a node until you know you have a string. So root would start out as NULL and could end up as NULL if there are no lines in the input. I'll leave that as an exercise for the reader. :-)

So putting it all together, your function might look something like this:

#include <stdlib.h>
#include <string.h>

typedef struct Node {
    void* value;
    struct Node* next;
} Node;

int main() {
    char *input_string = "Line 1\nLine 2\nLine 3";
    long remaining = (long)strlen(input_string);
    long chunk_size;
    char *next_line = input_string;
    char *string_copy;
    Node *root = calloc(sizeof(Node), 1);
    Node *last = root;
    Node *lines = NULL;

    while (remaining > 0) {
        char* next_new_line = strpbrk(next_line, "\n");
        /* If the string doesn't end with "\n", we need the rest of the string */
        if (next_new_line == NULL) {
            chunk_size = remaining;
        }
        else {
            chunk_size = next_new_line - next_line;
        }

        /* This allocates and copies the string */
        string_copy = strndup(next_line, chunk_size);

        last->value = (void *) string_copy;

        /* + 1 bc the '\n' is ignored */
        remaining -= chunk_size + 1;
        next_line += chunk_size + 1;

        /* If there's more, then allocate another node for the next go round */
        if (remaining > 0) {
            last->next = calloc(sizeof(Node), 1);
            last = last->next;
        }
    }

    lines = root;

    /* do something with lines */
}

Oh, and don't forget to free() all those strings and Nodes after you've used them!


Svick is right

Use the AggregateException class to collect all exceptions you need. With AggregateException everyone can prepare it's own code to handle the multiple exception situation but with your original solution they have to handle a huge string in a stock exception class. How can be this usefull?

Storing exception.Message

It's bad. If you store only the exceptions' messages you will loose a lot of information and the types of the exceptions. How would you handle an exception if only the Message is what you have? Parsing it? And we havent talked about the specific properties of specific exceptions like some validation exception which can contain the unvalid property name and value for an object.


Connect Four game without diagonals check or validation

Magic values

The implementation is mostly fine, except for the widespread magic values that would be better as constants, for example:

private static final char SYMBOL_EMPTY = '□';
private static final char SYMBOL_PLAYER1 = '■';
private static final char SYMBOL_PLAYER2 = '⊠';

Similarly, instead of initializing possiblePositions with new int[] { 5, 5, 5, 5, 5, 5, 5 }, it would be better to derive the correct value from the BOARD_WIDTH and BOARD_HEIGHT constants.

Code duplication

This snippet is duplicated in checkRowAndCol:

if (chainLength == 4) {
    switch (gameBoard[row][col]) {
        case '■':
            gameState = State.PLAYER_1_WIN;
            break;
        case '⊠':
            gameState = State.PLAYER_2_WIN;
            break;
    }
}

It would be better to move this to a helper method.

Unnecessary execution

When a player wins,
you could return immediately from checkRowAndCol,
no need to continue checking all rows and columns.

The helper method I mentioned in the previous section could return a boolean,
with a true value if there is a winner.
When the returned value is true,
the caller in checkRowAndCol could return immediately.

Code organization

Instead of checkRowAndCol, it would be better to separate to checkRow and checkCol methods.
You could still have a checkRowAndCol method that calls the other two,
but there's no reason for these two independent aspects to be implemented in the same method.


Fibonacci generator python implementation

tldr; I'd say that this function is too complicated.
Recursion should be avoided when possible as an iterative method is usually more readable and could be faster. Here's some other things to consider when making a recursive function: https://gist.github.com/abinoda/5593052#when-to-use-recursion-vs-iteration.
I think that some of the naming is not as clear as it could be, although that could just be an effect of the function being recursive. Consider changing parameter max_seq_length to seq_length. I couldn't quite see any scenario where you would give less results than the value passed in to max_seq_length.
Another item that could use some thought is your use of raising an exception when validating your input:
if(current_pos != 0 and len(sequence_list) == 0):
    raise Exception("Please initalize {} argument: {} with 0".format(fibonacci_calc.__name__, fibonacci_calc.__code__.co_varnames[1]))

Here, you would likely be better off just logging a message instead of introducing more overhead by using an exception.
Here's an example of a function that addresses my concerns:
def get_fibonacci_sequence(start_num, seq_length):
    if (seq_length < 1):
        return []
    elif (seq_length == 1):
        return [start_num]
    elif (seq_length == 2):
        return [start_num, start_num]

    fibonacci_seq = [start_num, start_num]

    for i in range(2, seq_length):
        fibonacci_seq.append(fibonacci_seq[i - 1] + fibonacci_seq[i - 2])

    return fibonacci_seq

print(get_fibonacci_sequence(19, 7))

PS. I'm assuming all the print statements are just debugging aids and wouldn't be included in the final version. Those messages are likely superfluous for other purposes.


The two validations are independent.  There's no point to if (codeValue == "" || nameValue == "") { … }.

Instead of calling $.show() and $.hide(), use $.toggle(display):

  display
  Type: Boolean
  Use true to show the element or false to hide it.

You can also write $(function() { … }) instead of $(document).ready(function() { … }).

$(function () {
    $("#<%= btnInsertCountry.ClientID %>").click(function () {
        $("#divCodeValidation").toggle(
            "" == $("#<%= txtCountryCode.ClientID %>").val()
        );
        $("#divNameValidation").toggle(
            "" == $("#<%= txtCountryName.ClientID %>").val()
        );
    });
});


You could use a list and generator comprehension instead of memberlist[:].
You should use snake_case instead of CamelCase for variables.
You should use isinstance rather than type() is.
This is as it works on objects that extend list. E.g. class MyCustomList(list): pass.
You should remove the print.
They are quite slow, and is probably left over from debugging.

If I were to do the above I would use:

def members(member_list):
    def handle_nonideal(item):
        if not item:
            return 0
        if isinstance(item, list):
            return ', '.join(item)
        return item

    return [
        {
            key: handle_nonideal(item)
            for key, item in member.items()
        }
        for member in member_list
        if member['visibility'] != 'redacted'
    ]


Selecting and inserting MySQL records using PDO

Manually escaping values is generally a bad thing to do, you should use prepared statements instead.

When you generate the query, instead of concatenating directly the values you should concatenate placeholders and the same time generate an array with the values and the placeholders as keys.

public function queryInsert($tableName, array $arrayColums) {

    if (!is_array($arrayColums) or ! is_string($tableName)) {
        die('Неверный формат данных в запросе SELECT в запросе SQL');
    }

    $colums = $placeholders = '';
    $values = array();

    foreach ($arrayColums as $key => $value) {

        if (!is_string($value) or ! is_string($key)) {
            die('Неверный формат данных в запросе SQL');
        }
        $colums .= SequrityData::SequrityReturnData($key) . ', ';
        $placeholders .= ':' . SequrityData::SequrityReturnData($key) . ', ';
        $values[':' . SequrityData::SequrityReturnData($key)] = $value
    }
    $colums = substr($colums, 0, -2);
    $placeholders = substr($placeholders, 0, -2);

    $tableName = SequrityData::SequrityReturnData($tableName);
    $insert = "INSERT INTO $tableName ($colums) VALUES ($placeholders)";
    $query = $this->_PDO->prepare($insert);
    $query->execute($values);

}

Also, most of the times is generally not a good idea to call die() or echoing directly from inside a class. What you should do when something unexpected happens is to throw an exception and then on the client code you can catch it, log it and display a friendly error message to the user.

Inside class:

if (!is_string($value) or ! is_string($key)) {
    throw new MysqlAccessException('Неверный формат данных в запросе SQL');
}

Client code:

try {
    $conn->queryInsert(...);
}
catch (MysqlAccessException $e) {
    $logger = new ExceptionLogger();
    $logger->error($e);
    $notifier = new Notifier();
    $notifier->error('Oops! We are sorry but there was an error, please try again later.');
}

It's also a good idea to catch any PDOExceptions inside the class, log them, and then inside the catch block throw a more generic type of exception like MysqlAccessException to catch on the client code. You don't want to catch PDOExceptions on the client code because they are very specific, and if you decide in the future to change the database class and use something else instead of PDO you will have the to update the client code as well.

try {
    $query->execute($values);
}
catch (PDOException $e) {
    $logger = new ExceptionLogger();
    $logger->error($e);
    throw new MysqlAccessException('Unable to execute insert.');
}

An other thing is that you should never hardcode database credentials in your database class. You should pass them through the constructor. A nice idea would be to have a dedicated config class that is responsible for providing the app configuration data by parsing a config file. This will also enable you to decouple the logic from the data and have different config files for production and development environments. An other reason why you don't want to hardcode this kind of data, is that if you use a versioning system like git and you are not the only person that maintains the code you don't want to commit sensitive data to the repository.


Release the acquired lock after specific timeout

First you shouldn't make your lock object public if it's for internal working of the class.  Typically they are marked as private.

The lock statement is just wrapper around the Monitor class.  The Monitor class has a built in timeout.   To use it we need to write a bit more code but less than what you currently have

private static readonly object _lockObject = new object();

public bool UpdateData()
{
    bool lockWasTaken = false;
    try
    {
        Monitor.TryEnter(_lockObject, TimeSpan.FromSeconds(1), ref lockWasTaken);
        if (lockWasTaken)
        {
            // do work here
        }

    }
    finally
    {
        if (lockWasTaken)
        {
            Monitor.Exit(_lockObject);
        }
    }

    return lockWasTaken;
}

Also if you are going to throw an exception you should make it useful and shouldn't normally use the standard Exception class.  If it's timing out then throw the TimeoutException.  This make it easier for callers to know it timed out and they can decide if they can capture it and retry.


Not a proper code review as per se but I was wondering if things couldn't be done in a more straight-forward way like this :

#!/usr/bin/python

class Machine(object):
    def __init__(self, state, transitions):
        self.transitions = transitions
        self.state = state

    def __call__(self, input):
        old_state = self.state
        self.state = self.transitions.get((self.state, input), self.state)
        print("DEBUG %s -- %s --> %s" % (old_state, input, self.state))

machine = Machine(
    "a",
    {
        ("a","msgA"):"b",
        ("b","msgB"):"c",
        ("c","msgB"):"b",
        ("c","msgC"):"a",
    }
    )

machine("msgA")
machine("msgB")
machine("msgC")
machine("msgB")

Using functions to have actual side effects, this could look like this :

#!/usr/bin/python

# examples of helper functions
def goto(s):
    return lambda state,input: s

def no_move():
    return lambda state,input: state

def verbose_no_move():
    def func(state,input):
        print('Cannot find a transition for %s from %s' % (input, state))
        return state
    return func

def print_input_and_goto(s):
    def func(state,input):
        print(input)
        return s
    return func

def print_old_state_and_goto(s):
    def func(state,input):
        print(state)
        return s
    return func

def raise_exception():
    def func(state,input):
        raise ValueError('Cannot find a transition for %s from %s' % (input, state))

class Machine(object):
    def __init__(self, initial_state, transitions):
        self.transitions = transitions
        self.state = initial_state
        self.default = verbose_no_move() # pick a default behavior

    def __call__(self, input):
        old_state = self.state
        func = self.transitions.get((self.state, input), self.default)
        self.state = func(self.state,input)
        print("DEBUG %s -- %s --> %s" % (old_state, input, self.state))

machine = Machine(
    "a",
    {
        ("a","msgA"):goto("b"),
        ("b","msgB"):print_input_and_goto("c"),
        ("c","msgB"):goto("b"),
        ("c","msgC"):print_old_state_and_goto("a"),
    }
    )

machine("msgA")
machine("msgB")
machine("msgC")
machine("msgB")


See https://github.com/coolaj86/knuth-shuffle for a shuffle function.

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

And write something like:

var correct = 0, answer = new Array();
var myQuestions = [ // my delimiter is ::, use any delimiter you like
  "Name a Programming language thats also a gem::ruby",
  "Name a Programming language thats also a snake::python",
  "What language do we use to style webpages?::css",
  "What language do you use to build the structure of a web page?::html",
  "What core language do you use to add interactivity to a web page?::javascript"
]
shuffle(myQuestions);

for(i = 0; i < myQuestions.length; i++) {
  answer[i] = prompt(myQuestions[i].substring(0,myQuestions[i].indexOf("::")));
  if(answer[i].toUpperCase() == myQuestions[i].substring(myQuestions[i].indexOf("::")+2).toUpperCase()) { // +2 because string is 2 characters and array starts at 0
    correct++;
  }
}

And so on …

I always say to minimize absolute code (never use it if it's possible). In this way, your code is more flexible leaving room for additions and improvements (you can improve on this code to include multiple answers as seen in your original code).


Use and understanding of async/await in .NET 4.5 +

Yes, your understanding is correct. Note that you're not using CancellationToken provided to ProcessScript. If your operations are cancellable and/or you're using other asynchronous API that accepts CancellationTokens it's highly recommended to pass it through the code, otherwise just don't create the CancellationTokenSource.

Following your comments:

Thread.Sleep(5000); // This is UI Blocking...

This is correct since async methods return control to the caller only when something is  awaited.

// awaits the long runniing task - non-UI blocking.
await task;

Here we release the UI thread and running a (computing) task in parallel. The reason I've added "computing" is that you're manually spanning a new task using Task.Factory. In case of I/O-related task returned by .NET framework it won't actually represent a new thread as it can wait for external data on the same thread.

// The await above sets this up as a continuation on the UI thread.

Correct. See good article Await, SynchronizationContext, and Console Apps that describes in details the behavior of await.

// Allow access to the UI from this background thread from
// the ThreadPool.
Task.Factory.StartNew(() =>
    {
        this.resultsTextBox.AppendText("\n\nNow in 'LongRunning'!! Waiting 5s simulating HARD WORK!!");
    }, CancellationToken.None,
       TaskCreationOptions.None,
       uiScheduler);

You're passing TaskScheduler corresponding to UI thread so naturally the code will be safe to work with UI. I would recommend using IProgress<T> to update/inform UI about changes in long-running task though, since you may want to separate computation logic from UI-related code.


Call html() on two jQuery selector objects

I believe you would be better off combining the two jQuery objects using .add() rather than a comma in the selector.  It's also more elegant than having to call .each().

$today.add($selected).html(date);


I don't see any issues with your code.

One suggestion would be to make your code a little DRYer by assigning to your prototype in 1 go and drop the jsdoc ( it adds a lot of lines, for little value ).

//Definition of an engine
var Engine = function() {};

Engine.prototype = {
  constructor : Engine,
  start : function() {
    console.log('start engine');
  }
};

Instead of

/**
 * Engine
 * @constructor
 * @returns {Engine}
 */
var Engine = function() {
    // definition of an engine
};

Engine.prototype.constructor = Engine;
Engine.prototype.start = function() {
    console.log('start engine');
};

Creating ferrari out of car is even more verbose, I would suggest 2 helper functions to keep the code more readable.

BobsGarage.Ferrari.prototype = {
  constructor : BobsGarage.Ferrari,
  speedUp : function() {
    console.log('speed up');
  },
}

extendPrototype( BobsGarage.Car , BobsGarage.Ferrari );

function extendPrototype( base , extension )
{
  extension.prototype = extend( base.prototype , extension.prototype );
}

function extend( o , extension )
{
  for( var key in extension )
    o[key] = extension[key];
  return o;
}

Obviously you would keep re-using extend and extendPrototype.


Unless you know for sure that the degrees, minutes, and seconds are always going to be 2 digits each, this approach will cause issues. I would recommend using 3 separate inputs for each value and automatically tabbing over to the next one when the first one is filled.

If you do know they will always be 2 digits, why not just concat the value with + instead of putting them in an array and joining them?


The use of database "sets" rather than "functions"

First goal in thinking in SQL (or thinking in sets) is to get rid of IF statements and Loops (or cursors).  So for your 2nd function this is much better:

CREATE FUNCTION dbo.funcSellIdByPropId
(
@PropertyId AS INT
)
RETURNS INT
AS
BEGIN
  DECLARE @ID AS INT

  SELECT @ID = COALESCE(MATRIXAGENCYPROPERTY.AgencyId, PRIVATESELLERS.id, 0)
  FROM  MATRIXAGENCYPROPERTY, PRIVATESELLERS
  WHERE MATRIXAGENCYPROPERTY.PropertyId = @PropertyId AND
        PRIVATESELLERS.PropertyId = @PropertyId

  RETURN @ID
END

This select can now be implemented as a view and then joined to any other select statement instead of calling a function.

For the 3rd function you could implement a view like this:

SELECT
  PropertyId
  ROW_NUMBER() OVER (PARTITION BY PropertyId ORDER BY weight DESC) AS [imgnum],
  image
FROM PROPERTYGALLERY

Now you can join on this view by PropertyId and imgnum instead of calling a function

For your first function take a look at this answer I posted on SO.  Using the XML generator like this is considered the fastest way to create a comma separated list in MS SQL.  Like the others examples I've given here, this technique could be used in a view to create a list of comma separated values partitioned by PropertyId

The key to both of these solutions is thinking in sets.  Instead of solving one problem (as the function does) they solve all the problems.  Then when you join to these queries you limit to just the data you need.

SQL Engines love this -- their optimizers are designed to make this kind of process work really fast.

Detailed Example (see comments)

First create the view:

-- MATRIXAGENCYPROPERTY.AgencyId and PRIVATESELLERS.id are mutually exclusive.
-- Grab all of them with their PropertyID
CREATE VIEW SellIDByPropertyID(ID, PropertyID) AS
(
  SELECT AgencyId, PropertyID
  FROM MATRIXAGENCYPROPERTY
  UNION ALL
  SELECT ID, PropertyId
  FROM PRIVATESELLERS
)

Now we can integrate it into your original query:

SELECT
   ...
   dbo.funcSellIdByPropId(T0.id) as SellerId,
   ...
FROM T0
   ...

To

SELECT
   ...
   S2P.ID,
   ...
FROM T0
JOIN SellIDByPropertyID S2P ON T0.id = S2P.PropertyId
   ...

Why this works

Once again the key to understanding is to think in sets.  If you just think about a single record a reaction might be the original SP would be faster because if it is a agency property it will only do one select and the IF statement will stop the 2nd select from being run giving a speed advantage.

  Side note: often on SQL Engines a select statement will be slower than
  an if statement so even the above assumption is wrong, but I'll ignore
  that for now.

However, this goes out the window as soon as we look at the set.  If the original query is returning more than one record -- say N records then with the original function call we have the overhead of N function calls + N Selects + N/2 Selects (if half are not agencies).  With the view we have just 2 Selects.  Clearly O(3.5N) > O(2)


The function could be replaced with this line:

return list(chain.from_iterable(zip(values, [element] * len(values))))[:-1]

Essentially,
zipping values with another list of the same size containing element in all values, flattening the zip, and chopping off the end.

About your original implementation, instead of this:

if len(copy_list) <= 1:
    return copy_list

This is more Pythonic:

if not copy_list:
    return copy_list

I'm also wondering if this needs to be a @staticmethod.
Since it's a pure function, I'd just call it weave.
Here's the complete implementation with doctests:

from itertools import chain

def weave(element, values: list) -> list:
    """
    >>> weave('module', [])
    []
    >>> weave('module', ['a'])
    ['a']
    >>> weave('module', ['a', 'b'])
    ['a', 'module', 'b']
    >>> weave('module', ['a', 'b', 'c'])
    ['a', 'module', 'b', 'module', 'c']

    :param element: The element to weave into the list
    :param values: The original list
    :return: The list with element weaved into it.
    """
    return list(chain.from_iterable(zip(values, [element] * len(values))))[:-1]

I see @jonrsharpe beat me to the doctests.
To add something new,
another way to run doctests:

python -m doctest yourfile.py

Update

Originally I proposed this one-liner:

return sum(zip(values, [element] * len(values)), ())[:-1]

But that turns out to be a bad idea.
This other discussion is also illuminating.


I would make my review mostly on the security, with some other improvements.

The main issue with this code, obviously, is SQL injection. It can easily allow anyone to browse the whole contents of your database. You should be really using prepared statements for the every SQL query you run, if at least one variable is going to be used in it.
Worse yet, by echoing the error out, you ease the task for the attacker significantly. By getting the feedback for their actions through the error message, an attacker could save themselves a lot of time. In case of error, only a generalized error message should be ever sent outside.
a somewhat similar issue: never give a potential hacker any certain feedback regarding the correctness of login and password - it's none of their business. Whereas a honest user could be just informed that their credentials didn't match. So it should be the only response in case of the wrong credentials.
Another issue is HTTP method used. It is considered a good practice to use POST method for the credentials, as it has a much lower footprint. For example, when using GET method, you will have all user passwords stored in the server's access log in the raw form. Why bother with hashing them in the database, if raw passwords can be easily accessed anyway?

I also removed redundant isset() calls. Given you already tested your input variables with isset, a condition $username = isset($_GET['auth_username']) will never be evaluated to false. So I just removed it altogether.

A note on the error reporting. Like it is said above, a system error message should be never echoed outside. At the same time, it should be logged carefully for the site admin's reference. Seemingly contradicting at first, there rules are  perfectly go together. I wrote an article on the PHP error reporting in which I summarized all my experience and which I highly recommend to read.

So the code would be

<?php

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $connection = mysqli_connect("localhost","root","","mydb");

    if (!isset($_POST['auth_username'],$_POST['auth_password'])) {
        exit('you failed to provide the correct parameters.');
    }

    $sql = "SELECT password, has_subscription FROM a__client_accounts WHERE username=?";
    $stmt = $connection->prepare($sql);
    $stmt->bind_param("s", $_POST['auth_username'])
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($db_password, $has_subscription);

    if ($stmt->fetch() && password_verify($_POST['auth_password'], $db_password)
    {
        if (!$has_subscription)
        {
            exit('you authenticated, but you don\'t have a subscription');
        } else {
            exit('congratulations');
        }
    } else {
        echo 'wrong login or password';
    }
} catch (\Exception $e) {
    error_log($e);
    exit("server error");
}


Using a concrete class where an abstract one or an interface can be used is usually a bad practice. That is, the getChildren method of the TrieNode class should return a Map<Character, Integer>, not a HashMap. There is no need to get bound to a concrete implementation.
The TrieNode class has redundant fields and methods. The value field is not used anywhere, so there is no need to keep it. Getters and setters for it are not necessary, too. Moreover, this classes exposes its internal representation. The clients of this class(in this it is the Trie class) do not really need to know how the children of this node are represented. Instead of returning a Map and letting the client work with it, I would create two methods: getChildForCharacter and getChildForCharacterOrCreateIfAbsent. Here is my version of this class:

class TrieNode {

    private Map<Character, Integer> children = new HashMap<>();

    /**
     * Returns the child of this node for the given character or null
     * if it does not exist.
     */
    public TrieNode getChildForCharacter(char c) {
        return children.get(c);
    }

    /**
     * Returns the child of this node for the given character. If it does
     * not exist, a new child is created.
     */
    public TrieNode getChildForCharacterOrCreateIfAbsent(char c) {
        if (getChildForCharacter(c) == null) {
            children.put(c, new TrieNode());
        }
        return children.get(c);
    }
};

Now this class does not expose its implementation and we can easily change it in the future if it is necessary. You could also add a isTerminal and setTerminal methods to this class if you want to search for the entire words, not just their prefixes.
The Trie class, again, in my opinion, contains a couple of methods that should not be there.

I think that the getRoot and setRoot method should be simply deleted. Why? Setting a new root breaks the trie(in a sense that previously added strings might turn out not to be there any) and the purpose of a getter is not clear(why would I need a trie's root?). Moreover, they expose the internal representation, which is not good. I'd just remove them. The clients of the Trie do not need to know that it has a root in the first place because it is an implementation detail.
traverseTree should be private(or at least protected). It is a helper method. There is no need to expose it to the clients. They don't even know what a TrieNode is(because this class is not public).
buildTrie is not a very good name. It implies that this method should be called only once(then the question is: why isn't it a constructor?). But it makes perfect sense to add new words to a trie. That's why I'd rename it to addAll or something like this. I would also add a method add which takes one String argument(to avoid making the clients of this class create a Set even if they want to add only one String.

Spacing and indentation. It is inconsistent in your code. Sometimes whitespaces around binary operators are absent, sometimes there are arbitrary whitespaces before a semicolon. You should keep you style consistent and adhere to established guidelines. It is easy to fix it using almost any modern Java IDE.
Testing. If do not use unit-tests, start using them. Testing your code in a consistent, systematic manner is a very good practice.

 Summary

Avoid exposing the internal representation of objects. Do not create getters and setters for the sake of having them. It is a bad practice.
Keep your code style consistent and follow established guidelines unless you have very good reasons not to.
Keep a consistent level of abstraction in your API. Try not to mix concepts from different levels(like a node in a trie and a HashMap).


Determining common divisors of two numbers

There are few improvements you can do in your code:

First choose better variable names. I would name the Scanner type variable as scanner rather than x. Really, x, y, z are the worst variable name, which doesn't give any idea as to what they denote.
Secondly, I won't force user to pass larger number first, and then smaller number. I would take the burden of finding that out myself.
There is no need of storing all the divisors of both the numbers in two different arrays. Suppose you have to find common divisor of 2 and 2132340. Will you store all the divisors of 2132340, or simply check that the common divisor cannot be greater than the divisor of 2, and use that fact?
Another fact is, all the divisors of num1 will be less than or equal to num1 / 2. Now, if num1 < num2, then the common divisors all must be < num1 / 2. So, iterate the loop till min / 2.
Of course, you can move the code that finds the common divisor in a different method, and store them in a List<Integer>.
Lastly, it might be possible that the smaller number itself is a divisor of larger number. So, you need to store that too.

Here's the modified code which looks a bit cleaner:

public static void main (String args[]){
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter the 1st number :  ");
    int num1 = scanner.nextInt();
    System.out.print("Enter the 2nd number : ");
    int num2 = scanner.nextInt();

    List<Integer> commonDivisor = getCommonDivisor(num1, num2);
    System.out.println(commonDivisor);
}

public static List<Integer> getCommonDivisor(int num1, int num2) {

    List<Integer> list = new ArrayList<Integer>();

    int min = minimum(num1, num2);

    for(int i = 1; i <= min / 2; i++) {
        if (num1 % i == 0 && num2 % i == 0) {
            list.add(i);
        }
    }

    if (num1 % min == 0 && num2 % min == 0) {
        list.add(min);
    }

    return list;
}

public static int minimum(int num1, int num2) {
    return num1 <= num2 ? num1 : num2;
}


Is this a good way to create an article in HTML5?

A good reference for element semantics would be HTML5 Doctor. You can read all about the tags and their intended purposes. From their overview for <section>, <article> and <div>:

Section
Represents a generic document or application section. In this context, a section is a thematic grouping of content, typically with a header, possibly with a footer. Examples include chapters in a book, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A web site's home page could be split into sections for an introduction, news items, contact information.
Article
Represents a section of a page that consists of a composition that forms an independent part of a document, page, or site. This could be a forum post, a magazine or newspaper article, a Web log entry, a user-submitted comment, or any other independent item of content.
Div
The div element has no special meaning at all. It represents its children. It can be used with the class, lang, and title attributes to mark up semantics common to a group of consecutive elements.

Their analogy of <section> is a chapter, an <article> is a section of the page. Chapters contain articles, not the other way around. A <div> might be more appropriate, since it has no meaning.


Letter frequency analysis (Breaking Vigenere)

use File::Slurp;

File::Slurp is considered broken by a lot of people. A good alternative is Path::Tiny.

It's also good practice to import only what you need when you use a module. That helps others to see where a function is coming from (like your read_file, which I tried to find in your code), and it helps to keep your namespace clean.

use Path::Tiny 'path';

my $text = path('krypton4')->slurp;

my @FILENAMES = ("found1", "found2", "found3");

All caps names are typically used for constants only. You can create a constant with the use constants pragma. That works by installing a sub into your namespace that returns a scalar. As a function, there's no sigil, and you need to use references for arrays.

The qw() quoted words operator is a nice shrotand for creating lists of quoted words, as you don't have to bother with commas and quotes.

use constant FILENAMES => [ qw(found1 found2 found3) ];

my $ENCRYPTED_STRING = read_file("krypton4");
$ENCRYPTED_STRING =~ s/\s+//g;

You only use this variable once. It's not really configuration either, so making it a constant feels wrong. In Perl, we try to declare variables as close to where they are used as possible, and in the smallest scope possible. I would recommend simply using Path::Tiny's path down in your foreach loop.

You could however add a constant for the krypton4 file name if you wanted.

use constant ENCRYPTED_FILE => 'krypton4';

If your Perl is at least 5.14, you can use the /r modifier on regex substitution to return an altered version, instead of doing in-place edit.

foreach my $item (split //, path(ENCRYPTED_FILE)->slurp =~ s/\s+//gr) { ... }

If your Perl is older, you can also use map to do that in one line. Note that s///g returns the number of substitutions, you have to explicitly return $_ from the block to get the text.

foreach my $item (split //, map { s/\s+//g; $_ } path(ENCRYPTED_FILE)->slurp) { ... }

foreach (split //, $string) {
    $frequency{$_}++;
}

If you use $_ explicitly in a loop body, it's clearer to use a named variable instead. I would call this $letter.

foreach my $letter (split //, $string) {
    $frequency{$letter}++;
}

sub get_single_key {
    my (%text_freq) = @_;
    my @text = ();
    foreach my $name ( sort { $text_freq{$b} <=> $text_freq{$a} } keys %text_freq ) {
        push @text, $name;
    }

    return map { $text[uc($_)] => $ENGLISH_FREQ[$_] } (0 .. $#text);
}

The frequency you've calculated with count_frequency is the frequency of each letter in the text. Your variable %text_frequency should thus be named %letter_frequency. But that's long. Why not stick with %frequency? It worked above.

You don't need to initialize arrays and hashes with an empty list. Perl does that for you.

I didn't read the algorithm description, so I don't know exactly what this does, but @text feels like the name is wrong. That variable is not an array of texts, or ordered pieces of one text. I think it contains the letters ordered by frequency. So @letters might be better.

It's good that you used a named loop variable, but again, this is a letter, right? So $letter is way more fitting than $name.

You can just assign the list of keys that sort returns to @letters.

There's a bug in your map statement. The $_ is not the letter, but the index. Your iteration 0 .. $#text gives you all the indexes. You are ucing the index, not the value.

You don't need the parentheses around the range. map takes a list, and the range operator .. gives you a list.

sub get_single_key {
    my (%frequency) = @_;

    my @letters = sort { $frequency{$b} <=> $frequency{$a} } keys %frequency;

    return map { uc $letters[$_] => ENGLISH_FREQUENCIES->[0] } 0 .. $#letters;
}

Since you have that comment Perform Letter Frequency Analysis where you use this function, and you return a hash, which implies a bunch of things, the name get_single_key might not be optimal.

foreach (split //, $ENCRYPTED_STRING) {
    print "$cypher_key{$_}";
}

A postfix foreach (or for for brevity) will be easier to read here.

You don't have to quote a single variable. There is no need for interpolation.

print $cypher_key{$_}
    for split //, path(ENCRYPTED_FILE)->slurp =~ s/\s+//gr;

say "";

It's shorter than print "\n" (or print "$/" if you insist on being portable), but it just feels off. It's good though that you realized that you need an empty string so it does not output $_ instead.


Matlab tic and toc commands implemented in C++

So as you are using c++ you should use the stl for that

#include <chrono>
#include <iostream>
int main() {
    std::chrono::high_resolution_clock::time_point start, end;

    start = std::chrono::high_resolution_clock::now();
    /* do someting */
    end = std::chrono::high_resolution_clock::now();
    double time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( end - start ).count();
    std::cout << "Code took " << time_elapsed << " miliseconds to execute\n";
};

EDIT

So here an more extended version

#include <chrono>
#include <iostream>

std::chrono::high_resolution_clock::time_point start_timer() {
    return std::chrono::high_resolution_clock::now();
}

void stop_timer (clock::time_point &start, std::string &message) {
    using cast = std::chrono::duration_cast;
    auto duration = cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start);
    auto hours    = cast<std::chrono::hours>(duration).count();
    duration     -= cast<std::chrono::milliseconds>(hours);
    auto minutes  = cast<std::chrono::minutes>(duration).count();
    duration     -= cast<std::chrono::milliseconds>(minutes);
    auto seconds  = cast<std::chrono::minutes>(duration).count();
    duration     -= cast<std::chrono::milliseconds>(seconds);

    std::cout << "The code took ";
    if (hours >= 1) {
        std::cout << std::lrint(hours) << "h";
    }
    if (minutes >= 1) {
        std::cout << std::lrint(minutes) << "m";
    }
    if (seconds >= 1) {
        std::cout << std::lrint(seconds) << "s";
    }
    if (milliseconds >= 1) {
        std::cout << std::lrint(duration) << "ms";
    }
    std::cout << " to execute\n";
}

int main() {
    std::chrono::high_resolution_clock::time_point start = start_timer();
    /* do someting */
    stop_timer(start);
}


You need functions.
Functions help to split up your code and make understanding how everything fits together easier.
You should have a function for:

Getting the page.

Parsing the JSON with your helpful error message.

Getting the payload.

A main function for calling all the other functions.
We should only call the main function if the script is the entry point.
We can do so with the following code:
if __name__ == "__main__":
    main()

You should add a function to walk paths.

product_price = doc.get('markets', {}).get('6', {}).get('pricesByPricelist', {}).get('3', {}).get('price', {})

# Added exception incase the [0] is not able to get any value from 'media'
try:
    product_image = doc.get('media', {})[0].get('sources', {}).get('full', {}).get('url', {})
except KeyError:
    product_image = None

Things would be so much simpler if we could just do:
price = get(data, "markets", "6", "pricesByPricelist", "3", "price")
image = get(data, "media", 0, "sources", "full", "url")

To build get is simple.

We take an object, a path and a default value.
For each segment of the path we index the object.
If the object doesn't have the value (__getitem__ raises LookupError) we return the default value.
The default value should be to raise an error.
We can ensure anything the user passes to the function is returned.
By making a new instance of an object we can then check if the default is the instance.
For convenience we can build the get function which defaults to None.

_SENTINEL = object()

def walk(obj, path, default=_SENTINEL):
    try:
        for segment in path:
            obj = obj[segment]
        return obj
    except LookupError:
        if default is _SENTINEL:
            raise LookupError(f"couldn't walk path; {path}") from None
        else:
            return default

def get(obj, *path):
    return walk(obj, path, default=None)

I'd highly recommend using exceptions for control flow in Python.
We can subclass BaseException to make an exception that prints to the user and then exits the system.
By wrapping the main() call in a try we can check if our custom error is raised print and then exit with a status of 1.
try:
    main()
except PrettyExitException as e:
    print(e)
    raise SystemExit(1) from None

import json
from json import JSONDecodeError

import requests

_SENTINEL = object()

class PrettyExitException(BaseException):
    pass

def get_page():
    headers = {'origin': 'https://www.aplace.com', 'Content-Type': 'application/json'}
    with requests.get("http://api.aplace.com/sv/dam/aaltoili-iso-mehu-gren-red-sand", headers=headers) as response:
        if not response.ok:
            raise PrettyExitException(f"Requests NOT ok -> {payload}")
        return response.text

def parse_json(raw_json):
    try:
        return json.loads(raw_json)
    except (JSONDecodeError, KeyError, ValueError) as err:
        raise PrettyExitException(f"Not able to parse JSON -> {err} -> Payload: {payload}") from None

def walk(obj, path, default=_SENTINEL):
    try:
        for segment in path:
            obj = obj[segment]
        return obj
    except LookupError:
        if default is _SENTINEL:
            raise LookupError(f"couldn't walk path; {path}") from None
        else:
            return default

def get(obj, *path):
    return walk(obj, path, default=None)

def build_payload(data):
    name = get(data, "name")
    brand = get(data, "brandName")
    price = get(data, "markets", "6", "pricesByPricelist", "3", "price")
    image = get(data, "media", 0, "sources", "full", "url")
    size = get(data, "items")
    count = 0
    sizes = []
    sizes_with_stock = []

    if name is not None and brand is not None:
        name = f"{brand} {name}"
    else:
        name = None

    if price is not None:
        price = price.replace("\xa0", "")

    if size is not None:
        for value in size.values():
            stock = get(value, "stockByMarket", "6")
            if stock is not None:
                _name = get(value, "name")
                count += stock
                sizes.append(_name)
                sizes_with_stock.append(f"{_name} - ({stock})")

    return {
        "name": name,
        "price": price,
        "image": image,
        "sizes": sizes,
        "sizesWithStock": sizes_with_stock,
        "stock": count,
    }

def main():
    raw_data = get_page()
    data = parse_json(raw_data.replace(",,", ","))
    payload = build_payload(data.get("productData", {}))
    print(f"Finished payload -> {payload}")

if __name__ == "__main__":
    try:
        main()
    except PrettyExitException as e:
        print(e)
        raise SystemExit(1) from None


How to get two JavaScript classes to talk to each other?

There are multiple ways of handling this. If you can pass the Books you want to the Shelf object, that would be probably one of the easiest methods.

//The Shelves
function Shelf (shelfNumber, shelfName) {
    this.shelfNumber = shelfNumber;
    this.shelfName = shelfName;
    this.books = new Array();
    this.addBook = function(book) {
        this.books[this.books.length] = book;
    }
    this.displayBooks = function() {
        for(i=0; i < this.books.length; i++) {
            displayBooks(this.books[i]);
        }
    }
}

// then you can use it like this...

shelf100.addBook(bookA);
shelf100.addBook(bookB);
shelf100.addBook(bookC);

shelf100.displayBooks();


Fetching data via jquery and adding items to a list

Your code looks good, and I'm not going to suggest comestic changes. However:

the_url is not informative enough, try to find a variable that conveys that this url will let you fetch the repositories of an user.
Did you consider that repo.name could contain a ' which would cause you to output wrong html? Fortunately, GitHub prevents such things to happen.
Declare var i; at the top of your success function. Here's why.
The way you're building your html string is dangerous.  It's also hard to read and easy to get wrong.

As Philip suggested, using some sort of template would be a good idea, but there's no way to do this in standard jQuery (jQuery templates have been deprecated, and the way forward seems to be JsRender which is not yet Beta). Fortunately, your code is not big enough for you to need that. Instead, use attr(), text() and addClass() wisely:

var dt = $('<dt>').attr('href', repo.url).attr('title', repo.name).text(repo.name);
var dd = $('<dd>').addClass('project-description').text(repo.description);
$('#gh-projects').append(dt).append(dd);


This is an interesting problem, and you've written an interesting solution.

With respect to your inefficient urn "store" -- the mapping of immutable urn references (Urn Natural) to mutable urn contents -- it might be worth considering that because of the nature of your monad, most monadic computations involving urns will scale exponentially in the number of urns anyway, so big-O performance of urn list building and lookups is essentially irrelevant.  You can start thinking about it when people want to use your monad for 100000-urn problems; or you could probably port everything over to a Data.Map Int or Data.IntMap in a few minutes).

The bigger problem, as you've noted, is that because this all has to run in a specific monotyped monad, unless you want to pre-declare the set of urns and their element types as used in a particular computation, you need an ugly, unsafe generic type like [Any] to represent your set of urns.

One method of dealing with this would be to represent the mutable contents of an urn by a set of always-integer indices while packaging the actual elements as part of the immutable Urn reference.  That is, the Urn references you pass around can be represented as:

data Urn s a = Urn { tag :: Key
                   , labels :: Int -> a }
type role Urn nominal representational

with monotyped mutable state:

data UrnState = UrnState { nextTag :: Key
                         , urns :: IntMap [Int] }

So urns urnState ! tag1 is the set of integer indices still in play for that urn, and the actual elements are available by looking up those indices in the labels urnRef map.

SPOILERS

A complete code example, which seems to work on your test case is:

{-# LANGUAGE DeriveFunctor, RoleAnnotations, RankNTypes #-}
import Data.List
import Control.Monad
import qualified Data.IntMap as IntMap
import Data.IntMap (Key, IntMap, (!))

data Urn s a = Urn { tag :: Key
                   , labels :: Int -> a }
type role Urn nominal representational

data UrnState = UrnState { nextTag :: Key
                         , urns :: IntMap [Int] }

newtype Draw s a = Draw { unDraw :: UrnState -> [(a, UrnState)] } deriving (Functor)
type role Draw nominal representational
instance Applicative (Draw s) where
  pure x = Draw (\s -> [(x,s)])
  (<*>) = ap
instance Monad (Draw s) where
  Draw d >>= f = Draw $ \s -> do  -- list monad
    (a', s') <- d s
    unDraw (f a') s'

evalDraw :: (forall s. Draw s a) -> [a]
evalDraw (Draw d) = map fst $ d $ UrnState 0 IntMap.empty

newUrn :: [a] -> Draw s (Urn s a)
newUrn xs = Draw $ \(UrnState nxttag urs) ->
  let -- list of labels keyed by indexes [0..n-1]
      lbls = IntMap.fromAscList (zip [0..] xs)
      -- new urn has tag "nxttag" and the immutable labelling function
      u = Urn nxttag (lbls !)
      -- add urn to state
      urs' = IntMap.insert nxttag (IntMap.keys lbls) urs
  in  [(u, UrnState (nxttag+1) urs')]

draws :: [a] -> [(a,[a])]
draws xs = zipWith3 go (inits xs) xs (tail (tails xs))
  where go l a r = (a, l++r)

drawFrom :: Urn s a -> Draw s a
drawFrom (Urn tg lbls) = Draw $ \(UrnState nxttag urs) ->
  case urs ! tg of
    [] -> fail "empty urn"
    xs -> do  -- list monad
      (a, xs') <- draws xs
      return $ (lbls a, UrnState nxttag $ IntMap.insert tg xs' urs)

main :: IO ()
main = print $ evalDraw $ do
  l <- newUrn [1,2,3,3]
  x <- drawFrom l
  y <- drawFrom l
  return (x, y)


Group by range and include edge duplicates

Can there be empty groups?
If you pass in a rangeSize of 5, your current code will have an empty group. Is this desired?
Iterating over entire collection for each group
In addition to Peter Csala's recommendations, there is a possible performance issue here: you are iterating over the entire source for each group. The delegate passed to Where must be evaluated against all the items, to determine the contents of each group.
for (var i = 1; i <= steps; i++)
{
    ...
    var currentGroup = items.Where(p => p.Value >= min && p.Value <= max);
    groups.Add(currentGroup.Select(p => _mapper.Map<DTO.Item>(p)));
}

If you have few items, or only a small number of groups, this might not be an issue.
The following might be more efficient. Create a sequence of mapped-item / group-index pairs:
public IEnumerable<(DTO.Item mappedItem, int groupIndex)> GroupIndexes(int rangeSize) {
    foreach (var item in _itemRepository.GetAll()) {
        var groupIndex = Math.Floor(item.Value / rangeSize);
        var mapped = _mapper.Map<DTO.Item>(item);
        yield return (mapped, groupIndex);
        if (item.Value > 0 && item.Value % rangeSize == 0) {
            yield return (mapped, groupIndex - 1);
        }
    }
}

which you could then use to group:
var grouped = GroupIndexes(10).GroupBy(x => x.groupIndex, x => x.mappedItem);


You can get rid of the nested loop, replacing this

for ( int x = 0; x < bm.getWidth(); x++ )
 {
     for ( int y = 0; y < bm.getHeight(); y++ )
     {
         c = pixels[x+y*w];
         lLightness = ((c&0x00FF0000 )>>16) + ((c & 0x0000FF00 )>>8) + (c&0x000000FF);
         pixels[x+y*w] = lLightness;
         gLightness += lLightness;
     }
 }

With this:

int size = bm.getWidth()*bm.getHeight();
for (int i = 0; i < size; i++) {
  c = pixels[i];
 // etc.
}

It will at least save one x+y*w operation per pixel.

It may be advantageous to calculate size into a separate variable as above, instead of doing it inside the loop, as in for (int i = 0; i < bm.getWidth()*bm.getHeight(); i++). The condition is checked at each round so you would end up calling the getters at each round, and who knows what's in them? The JIT compiler may be able to optimize this kind of stuff away - and probably will, if the getters are simple "return class member" statements - but at least it's not guaranteed.

More substantial improvements can be got by sacrificing perfection. Maybe you needn't take each pixel into account for calculating the threshold? Perhaps count only every 10th on each direction? Then you would probably use the nested loop again. Like this:

int width = bm.getWidth();
int height = bm.getHeight();

for ( int x = 0; x < width; x+=10; )
{
  for ( int y = 0; y < height; y+=10; )
  {
   // etc.
  }
}

gLightness /= (width / 10) * (height / 10);


Don't use sum as a variable.  Especially because you want to use it with your approach!

sum = 0
for i in s:
    sum += values[i]

could become:

number = sum(values[i] for i in s)

s[i] is a string.  s[i] + s[i+1] is a string.  There is no need to use str() to convert what is already a string to a string.  But s[i:i+2] is easier still.

With 3999 as the maximum, the longest Roman numeral string would be 15 characters  ("MMMDCCCLXXXVIII").  Your last loop would iterate 14 times, taking two letter substrings.

There are only 6 two letter negative combinations.  You could instead search for those 6 patterns:

number += sum(value for key, value in checks.items() if key in s)

This is 6 \$O(N)\$ substring searches, instead of N \$O(1)\$ lookups.  Time complexity is unchanged, but this latter approach may be faster for many strings.  (It certainly will be slower for 1 character strings!)

checks and values are constants.  You should not recreate them every time you call the function.  Make them global, initialized once.

PEP-8:

Variables and functions should be snake_case, not camelCase, so romanToInt should be roman_to_int.

s  is too short to be descriptive.  roman might be better.

self?  This should be a function, not a method in a class.  If it is in a class, then use @staticmethod, since it doesn't use self (or cls) at all.

Result:

SUBTRACTIVE = {"IV": 2, "IX": 2, "XL": 20, "XC": 20, "CD": 200, "CM": 200}
VALUES = {"I": 1, "V": 5, "X":10, "L": 50, "C": 100, "D": 500, "M": 1000}

def roman_to_int(roman: str) -> int:

    number = sum(VALUES[ch] for ch in roman)
    number -= sum(val for key, val in SUBTRACTIVE.items() if key in roman)

    return number

Although I'm not a fan of CHECKS, but a better concise name is escaping me.  Now using SUBTRACTIVE as suggested by JollyJoker.

Speed Tests

Execution time for parsing all Roman numerals from I to MMMCMXCIX, repeated 100 times, in seconds:

somya_agrawal   1.288
ajneufeld       0.737
jg              1.521
jg2             1.324
maarten_bodewes 2.186
maarten_bodewes 1.653 (decode only)

It wasn't clear whether J.G. was using local variable or global variables for checks and values in their solution, so I coded it both ways.

Speed Test Code

import time

def create_roman(value):
    roman = ""
    for letters, val in (("M", 1000),
                         ("CM", 900), ("D", 500), ("CD", 400), ("C", 100),
                         ("XC", 90), ("L", 50), ("XL", 40), ("X", 10),
                         ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)):
        while value >= val:
            roman += letters
            value -= val
    return roman

ROMAN_NUMERALS = [create_roman(value) for value in range(1, 4000)]

def somya_agrawal(s: str) -> int:
    checks = {"IV":-2,"IX":-2, "XL":-20, "XC":-20, "CD":-200, "CM":-200}
    values = {"I":1, "V":5,"X":10, "L":50,"C":100, "D":500,"M":1000}
    sum = 0

    for i in s:
        sum += values[i]

    for i in range(len(s) - 1):
        combine = str(s[i] + s[i + 1])
        if combine in checks:
            sum += checks[combine]

    return sum

CHECKS = {"IV": 2, "IX": 2, "XL": 20, "XC": 20, "CD": 200, "CM": 200}
VALUES = {"I": 1, "V": 5, "X":10, "L": 50, "C": 100, "D": 500, "M": 1000}

def ajneufeld(roman: str) -> int:
    number = sum(VALUES[ch] for ch in roman)
    number -= sum(val for key, val in CHECKS.items() if key in roman)

    return number

def jg(s: str) -> int:
    checks = {"IV":-2,"IX":-2, "XL":-20, "XC":-20, "CD":-200, "CM":-200}
    values = {"I":1, "V":5,"X":10, "L":50,"C":100, "D":500,"M":1000}

    result = sum(values[i] for i in s)
    result += sum(checks.get(s[i : i + 2], 0) for i in range(len(s) - 1))

    return result

checks = {"IV":-2,"IX":-2, "XL":-20, "XC":-20, "CD":-200, "CM":-200}
values = {"I":1, "V":5,"X":10, "L":50,"C":100, "D":500,"M":1000}

def jg2(s: str) -> int:

    result = sum(values[i] for i in s)
    result += sum(checks.get(s[i : i + 2], 0) for i in range(len(s) - 1))

    return result

def time_test(f):
    start = time.perf_counter()
    for _ in range(100):
        for roman in ROMAN_NUMERALS:
            f(roman)
    end = time.perf_counter()
    print(f"{f.__name__:15} {end-start:5.3f}")

if __name__ == '__main__':
    for f in (somya_agrawal, ajneufeld, jg, jg2):
        time_test(f)


Longest collatz sequence using dynamic programming

Well, it appears you are having a bit of trouble getting things off-the-ground, so to speak. Let's start with the basics. Let's name your file collatz.c and after a quick glance, it looks like it should compile:

gcc -Wall -Wextra -o ctz collatz.c

Good, it compiled with no errors and no warnings. Now let's see if it will run:

output:

$ time ./ctz
525
837799

real    0m2.088s
user    0m2.082s
sys     0m0.004s

Also good, max is 525 and k is 837799 and it completed in less than 2.1 seconds. The logic is implemented in a single recursive function akin to that used by a non-math-lib power function, so no great speed improvements come to mind. As was pointed out, there are optimization that can help reduce the execution time. Let's try the suggested -Ofast -fwhole-program:

gcc -Wall -Wextra -o ctz collatz.c -Ofast -fwhole-program

output:

$ time ./ctz
525
837799

real    0m0.480s
user    0m0.474s
sys     0m0.003s

A 400+% improvement. That's better. So it looks like your work is done. Drop a comment or edit your question if you have more specifics in mind.


Overriding scrolling behavior for navigation elements

One potential problem I see is that you initialize the w variable once at $(document).ready() time and then you use that value in several event handlers.  But the window width is a dynamic value that can be changed over time so your event handlers can be using a stale value for w.  You should probably be fetching $(window).width() anytime you need it so it is always correct.

You can also replace:

$('#main_nav > ul').css('display', 'none');

with this:

menu.hide();

since you've already cached the value of $('#main_nav > ul') and .hide() is a shortcut for .css('display', 'none');.

You could also probably replace this entire code section:

if (w < 768) {
    $('#main_nav > ul').css('display', 'none');
}

with a CSS rule using media queries.

menu.removeAttr('style'); is pretty harsh (removing all possible styles).  If you're just trying to show the menu again when the width has exceeded a desired value, then you can just do this:

$(window).resize(function () {
    if ($(window).width() > 768) {
        menu.show();
    }
});

Note, there is no need to check .is(':hidden') because calling .show() on something that is already visible just does nothing and .is(':hidden') is a slightly expensive operation because it has to check the visibility of every single parent object.


The string manipulation is avoidable, by working with bits of the exponent directly:

def quad_pow(base, exponent, modul):
    a = 1
    b = base

    while exponent:
        if exponent & 1:
            a = (a * b) % modul
        b = (b * b) % modul
        exponent >>= 1
    return a


Proper capitalization for surname like McDonald

If you are going to create a list of the last names it will get very big, but you would have a list of the names so you could instead

surnames.Add("McDonald")

And then

else
    foreach name in surnames
        if lcase(item) = lcase(name) then
            xWord = name
        end if
    next
end if

But, this would get rather long as you add the names in, which is a big downfall when talking about maintenance especially on a VBScript.


Tkinter is not just OOP, it's about http://en.wikipedia.org/wiki/Event-driven_programming . The code you posted does not yet show enough to be judged, because it's too small and the application purpose is not yet clearly visible. When code will grow, you will need to decompose it into modules, but it is good to think about the strategy before hand.

Tkinter allows to process events in event-driven style, so it's hard to see why do you need "a tick" to check if a user presses something. (I am not sure, may be it is intended this way).

One more note I can make is about style. Take alook at http://www.python.org/dev/peps/pep-0008/ It's not very important, but makes the code look much nicer.

UPDATE: MVC (model-view-controller) is very natural approach for Tkinter (as is the case with other GUI frameworks). Please, take a look at toy MVC (link from an answer to https://stackoverflow.com/questions/7638139/python-tk-with-mvc-pattern)


Beginnings of Go web server with mongoDb

You might wanted to start writing some comments on your code.

For example I've read all your code but there are some method that I don't understand like :

func(a* App) GetMongoSession() *mgo.Session {
  return a.Mongo.Session.Copy()
}

Okay we know It is getting the mongo session. but for what purpose?

// We get the mongo session for .... you can start explain why
func(a* App) GetMongoSession() *mgo.Session {
  return a.Mongo.Session.Copy()
}

I think it is a good think to keep comment the code, so others can understand it quickly. especially when someone who new to mongoDB. :D


Finding the longest palindromic substring

In terms of efficiency, I like the code.

I'd just fix a few stylistic issues:

Naming: l, a, s don't say anything about what the variable means. Also, you named your function palindrome, but that's returning a boolean, so I'd name it is_palindrome. The i in the substring function is a bit puzzling to me: you have a variable named end, why not call the other one start?
As @kyrill mentioned, you should probably change comments above the functions to docstrings.
The comment Declare local variable for the length of s. is useless.
I'd instead add another comment explaining why it works. If you have a function simply called substrings I expect it to return the substrings. This code only works because it returns the substrings starting from the longest to the shortest. I'd at least change the comment descending order (which may mean for example lexicographical order or alphabetical order) to from longest to shortest. Better be explicit.
I know, it's a bit long, but since you're using a generator, I'd rename the function substrings to get_next_substring.
As @zondo mentioned Question2 is not a PEP8 compliant name, but I'm not sure if the automatic grader will need it to be called like that.


Avoiding code duplication for attribute-removal code

I think that @david-harkness code could be simplified further:

(function () {
    var $max = $("#Max"),
        $min = $("#Min"),
        $result = $("#Result"),
        changeHandler = function () {
            $result.prop("disabled", $max.val() != $min.val());
        };

    $max.change(changeHandler);
    $min.change(changeHandler);
}());

but I'm not really sure about the side effects of using prop instead of attr.


Short review;

Use a beautifier, the code is not properly indented or spaced out
You use var, try to use const and let
The code already assigned billAmount / noOfGuests to split, so you can compare rounding and split
£ should probably be a single string constant
elseIf is a terrible variable name
elseIf is already multiplied by noOfGuests, why would you multiply it again in the if statement?
billAmount and noOfGuests should be parameters of splitBill and splitTip
tipremainder should be tipRemainder


Temporary modifying env variables with context manager

Instead of MaxOMP as a name, I like MaxOmp - in general still CamelCase your names even if they include an acronym.

Additionally, there isn't any reason why this needs to be restricted to any particular environment variable. As such, I would probably make this:

class EnvironmentVariableContextManager:

    _base_value = None
    _variable = None

    def __init__(self, variable_name, value):
        self.variable = variable_name
        self.target_value = value

    @property
    def variable(self):
        return self._variable

    @variable.setter
    def variable(self, name):
        self._base_value = os.environ.get(name, None)

        if self._base_value is None:
            raise Exception(f"{name} is not a valid environment variable")

        self._variable = name

    @property
    def original_value(self):
        return self._base_value

    def __enter__(self):
        os.environ[self.variable] = self.target_value

    def __exit__(self, *):
        os.environ[self.variable] = self.original_value

This has a few benefits:

We use properties to properly encapsulate access and add some extra validation (if you don't care about invalid environment variables feel free to remove that)
We restore it to the original value, not some hardcoded value. You could also provide a way to specify an "after" value if that was desirable.

As suggested in the comments, we may have a valid use-case for an environment variable that doesn't currently have a value. In that case, we would remove the exception, and instead do this:

@variable.setter
def variable(self, name):
    self._base_value = os.environ.get(name, None)
    self._variable = name

def __exit__(self, *):
    if self.original_value is None:
        os.environ.pop(self.variable)
    else:
        os.environ[self.variable] = self.original_value

Once we have that, then we just inherit.

class MaxOmpThreads(EnvironmentVariableContextManager):

    def __init__(self, max_threads=None):
        max_threads = max_threads or mp.cpu_count()
        super().__init__("OMP_NUM_THREADS", max_threads)

Another thing to note, is that os.environ only reflects the environment variables at the time of Python startup. If this is not what you want then you'll likely need a different solution.

This also may not be thread-safe; if you might have multiple processes working on something at once, and some need one setting and some need another, then you're likely to run into issues. If your program is overall serial, and the pieces that use OMP are well defined and contained, you're probably fine.


Fetching busy students and their latest product

Without additional info about indexes and row counts it's hard to tell, but the most elegant solution is probably using Analytical Functions (using employees instead of students):

with cte as
 (
    select s.age, s.name as EmployeeName, p.Name as ProductName,
       -- row with the newest date
       row_number() over (partition by s.ID order by sp.Date desc) as rn,
       -- number of Products per employee
       count(*) over (partition by s.ID) as cnt
    from Student as s
    join StudentProduct as sp
      on sp.EmployeeID = e.ID
    join Product as p
      on p.ID = sp.ProductID
    where s.age > 19
 )
select age, EmployeeName, ProductName
from cte
where cnt > 3  -- more than three products
  and rn = 1   -- the latest product


Your naming tells me nothing and doesn't follow Standard VBA naming conventions.

Dim i - this is a counter? why not rowNumber
Dim n - this is also a counter? why not labelNumber
Dim x - is this a counter? why not nextRowNumber
Dim Library should be library
Dim LastRow should be lastRow

With library in fact Worksheets have a CodeName property - View Properties window (F4) and the (Name) field can be used as the worksheet name. This way you can avoid Sheets("mySheet") and instead just use mySheet.

A good way to speed up your macro is to use Application.Screenupdating = False and Application.Calculation = xlManual and Application.EnableEvents = False. Just be sure to return them to True and xlAutomatic and True before exiting the sub.

Additionally, you're doing everything on the sheet, which is slow by nature. Even just reading into an array should be quicker -

Option Explicit

Private Sub PrepareLibrary()
    Application.Screenupdating = False
    Dim lastRow As Long
    Dim results As Variant
    Dim resultsIndex As Long
    Dim currentRow As Long
    Dim currentColumn As Long
    currentColumn = 0
    lastRow = Library.Cells(Rows.Count, "A").End(xlUp).Row
    ReDim results(1 To lastRow)
    results = Library.Range("A1:A" & lastRow).Value

    For resultsIndex = 1 To lastRow
        If IsNumeric(results(resultsIndex, 1)) Then
            currentColumn = currentColumn + 1
            Sheets("Sheet2").Cells(1, currentColumn) = results(resultsIndex, 1)
            currentRow = 2
        Else:
        Sheet2.Cells(currentRow, currentColumn) = results(resultsIndex, 1)
        currentRow = currentRow + 1
        End If
     Next
     Application.Screenupdating = True
End Sub

That's not a very good example of using the array to the maximum benefit, but it's something.


Keep your concerns separated

One design principle that is vital to engineering good software is that of "separation of concerns".  In other words, each function should be concerned with doing one, and only one, thing.

If you step back and take a look at the pascal function, you will see it's trying to do two things at once:

Compute Pascal's triangle
Pretty-print the triangle

You can separate these concerns.

Let's start with the pascal function.  It should only compute the values in the triangle.  It should return a list of "rows", where a row is represented a list of numbers.

So we can use pascal to compute a list of lists of numbers.  Now we want to pretty-print this list.  We could do this all in one function (and there's nothing really wrong with that).  But if we're careful, we can make things more generic (and thus reusable).  We can compose pretty-printing the triangle into the following:

Formatting each row.  This involves taking a list of numbers and returning a string representation for that row.
Centering the rows.  Basically, padding each string with spaces.
Printing the rows.  Taking the strings and print them each on separate lines.

We can define functions format-row, center-lines, and print-lines to handle these tasks.  Now we can define a function pretty-print-pascal that combines these functions:

(define pretty-print-pascal (x)
  (print-lines (center-lines (map format-row (pascal x)))))


Input
One thing I would suggest is provide a hint to the user about the format of their coordinates input. It's not immediately obvious that the format should be x y. I had to look at the code to figure that out. Intuitively, one might expect to type in x and y on separate lines or maybe separate them with a comma.
One way to deal with this is to add a string in the input function, so rather than:
ordinates = input()
you could do something like:
ordinates = input("Please enter your coordinates (example: 1 2): ")
Better yet, it would be easier to deal with only individual x and y coordinates throughout the program, rather than  mixing them with strings combining the two. For this, you would simply ask for the two coordinates with separate input() statements (e.g. input("Enter your x: ", input("Enter your y: ")). Then you don't have to worry about splitting strings or unpacking tuples or anything or the sort.
Coordinates
Another point is that the vertical coordinates seem to be backwards, in that the 1st row is at the bottom and the 3rd row at the top. Again it would make the game more user friendly to either specify this to the user or rearrange the grid array so that [1, 1] is top left and [3, 3] is bottom right.