In my opinion, use Explaining Variables or Summary Variables express the dict. I like this coding style as follows.

keyword = {
    'this': iss,
    'an': example,
    'dictionary': 'wich is very long',
}
return some_long_name('maybe long string', keyword)


Not sure exactly what this code is supposed to accomplish, but there are at least a few comments I think are valid regardless.

Avoid using namespace std;

This brings an extremely large number of names into scope. While perfectly reasonable with other namespaces, you usually want to avoid it with the std namespace.

Your use of isalpha

This code:

 cout<<"Enter total number of processes(maximum 20):";
 cin>>n;
 while(char (n))
 {
      if(isalpha(n))
      {
            cout<<"Invalid Input";
      }

... makes very little (if any) sense to me. You've read a number from the user, then you're trying to use isalpha on that. Since (in C and C++) char is a small integer type, it's valid (from the compiler's viewpoint) to pass that int to isalpha, but it's really not meaningful at all.

Given that you want a number less than or equal to 20, it would probably be best to check for that before using it though--as it stands now, if the user enters something like 30, the code will blithely continue trying to run, and write past the ends of the arrays it has allocated.

Use of arrays

That brings us to the next obvious problem: you're probably a lot better of using something like std::vector (or possibly std::array) rather than the arrays that are built into the language. These behave much better in general: they know their own size, don't decay to points the minute you look at them wrong, and are generally just a whole lot better.

Treat users humanely

Demanding that a user enter 20 (or even 10) process burst times interactively is inhumane. It would be much better to (for example) accept a file containing the burst times instead.

Use applicable standard algorithms

First of all, it looks to me like your computation of arrival times:

   wt[0]=0;
   for(i=1;i<n;i++)
   {
         wt[i]=0+bt[i];
         for(j=0;j<i;j++)
         wt[i]+=bt[j];
   }

...is actually broken. Since you're storing the first arrival time as 0, you have a total of one more arrival time than burst times.

I'd switch to using std::vectors as mentioned previously, and then use the standard partial_sum algorithm to do most of the work:

wt[0] = 0;

std::partial_sum(bt.begin(), bt.end(), std::back_inserter(wt));

I believe this produces the results you wanted: for N inputs, it produces 0 for the first result, and each succeeding result is the sum of the burst times up to that point.

Names

Many of the names you've used (e.g., bt, wt, avwt) are (I suppose) quick to type, but certainly hard to read. I'd prefer to see burst_time, wait_time, average_wait, so I could read them a little more easily.

Output

Since you have one more arrival time than burst time, you may want to report your results a little differently. Right now, at least as I read things you're not reporting (or actually even computing) the last arrival time. Since the sequence is really that process 0 starts at time 0, and each successive time is based on the previous process times, I think I'd arrange the columns with the arrival time on the left and the process time on the right, so the numbers read more meaningful from let to right, top to bottom (i.e., in the direction people normally read).

For formatting output into columns, I'd also advise using std::setw instead of tabs.

Putting those together, we might end up with code something like this:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <numeric>
#include <fstream>
#include <iomanip>

int main(int argc, char **argv) {

    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <filename>\n";
        return EXIT_FAILURE;
    }

    std::ifstream in(argv[1]);

    // Read the burst times from the file into our vector:
    std::vector<int> burst_times{ std::istream_iterator<int>(in), {} };

    std::vector<int> arrival_times{ 0 };
    std::partial_sum(burst_times.begin(), burst_times.end(),
                     std::back_inserter(arrival_times));

    int width = 10;
    std::cout << "\n" << std::setw(width) << "Process"
                      << std::setw(width) << "Arrival"
                      << std::setw(width) << "Duration" << "\n";

    int i;
    for (i = 0; i < burst_times.size(); i++)
        std::cout << std::setw(width) << i + 1
                  << std::setw(width) << arrival_times[i]
                  << std::setw(width) << burst_times[i] << "\n";

    std::cout << std::setw(width) << i + 1
              << std::setw(width) << arrival_times[i] << "\n";

    auto total_times = std::accumulate(arrival_times.begin(), arrival_times.end(), 0);
    auto average_time =  total_times / arrival_times.size();

    std::cout << "\n\nAverage Waiting Time: " << average_time << "\n";
}


Namespacing

  1) Is it good enough that I am splitting my functions and then adding them to a single global object? Any better way?

Yes, it's a good and popular approach. It's simple and it works.

You might consider using closures to create app.p, app.q and app.r. I think this is referred to as using IIFEs (immediately invoked function expressions) [details]. Right now, app.p, app.q and app.r have no persistent private scope. The only private scope they will have is whatever happens within the function, itself. If they needed to keep track of something, they will need to use a variable in the global scope because it is the only scope outside of the function. Using an 'IIFE' would allow there to be some persistent and private state for each function:

app.p = (function() {
    var someCounter = 0;
    return function(){
        someCounter++;
        // do stuff
    }
})();

Now, app.p can access the someCounter variable but nothing else can. Some people don't care for this, but I'm a fan.

For larger projects, the var app = app || {}; might become unwieldy. Something I've been working with a bit that allows a little more flexibility is at the bottom of this page:

http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/

function namespace(namespaceString) {
    var parts = namespaceString.split('.'),
        parent = window,
        currentPart = '';

    for(var i = 0, length = parts.length; i < length; i++) {
        currentPart = parts[i];
        parent[currentPart] = parent[currentPart] || {};
        parent = parent[currentPart];
    }

    return parent;
}

Using this approach, to define something in a namespace (modified from the same page):

// using an immediately invoked function expression (IIFE)
// keeps things private to the function and prevents spillage
// of variables into this outer scope
(function() {
    // retrieve what exists or make a new definition
    var examples = namespace('io.examples');

    // add something to it (another IIFE)
    examples.log = (function() {
        // can have private variables
        var numMsgs = 0,
            // for this, the api is an invokable function: api(), but
            // we will also add more functions to it: api.subFunction()
            // these will all have access to the numMsgs private variable
            api = function() {
                numMsgs++;
                console.log.apply(console, arguments);
            };
        api.getMsgCount = function() {
            return numMsgs;
        }
        // returning api sets io.examples.log to the api function
        return api;
    })();
})();

And, to use something from a namespace:

// retrieve what exists (we already made something,
// so it will not create an empty place-holder)
var log = namespace('io.examples.log');

// the api was a function, so we can call it
// or access the sub-function we attached to it
log('hello');
var numSoFar = log.getMsgCount();

A related topic is AMDs (asynchronous module definitions) and dependency-injection (which is rather a sub-set of what AMDs set out to do, I think). Some options are requireJS, yepnope, and angularjs (which entails committing the project to the angularjs framework). I'm sure there are a lot of others, I just don't know them.

native addEventListener

  2) I am using some native window.addEventListener() calls...

Historically, when I avoid using a library it's because I don't want to either load it. That being said, the performance difference is impressive. Most things I write are driven from UI events, which are generally rare (how often are you clicking?), and the performance difference between the two doesn't matter. I would say it doesn't even matter if the code base is large. Seems like the main thing would be whether you are handling events that occur super-frequently or not.

It's also worth noting that creating a dependency on a library can hinder the reusability of whatever you're writing.

init process

  3) How the whole execution begins, like Zepto kickstarts init() function

If you're using native event listeners, then you don't have a choice, it can't go in the Zepto init. If you're using the Zepto init process, I would just put it in the Zepto(...) if a) nothing else needs a reference to it and b) you don't need it before then, anyway.


double Clib_atof(char s[])
{
    double val, power, rtn;
    int i, sign;
    for (i = 0; isspace(s[i]); i++);

Looks too much like the ; was an accident. I suggest using {/\*empty\*/} instead to make it clear you did it on purpose. Or I might write it as a while loop.

    sign = (s[i] == '-') ? -1 : 1;
    if (s[i] == '+' || s[i] == '-') ++i;
    for (val = 0.0; isdigit(s[i]); ++i) {
        val = 10.0 * val + (s[i] - '0');
    }

I dislike the use of a for loop here. The initializer condition doesn't really have any to do with the loop control. Repeating the loop until some condition becomes true feels like a while loop. With a for loop I think of iterating or counting not testing.

    if (s[i] == '.') {
        ++i;
    }
    for (power = 1.0; isdigit(s[i]); ++i) {
        val = 10.0 * val + (s[i] - '0');
        power *= 10.0;
    }

    rtn = (sign * val / (power));

I wouldn't use abbreviations like rtn and val. They make the code harder to read. I don't think any of those parens are necessary.

    // Next work on exponent
    if (s[i] == 'e') {
        int j, esign;
        int eval = 0;

I look at this and think evaluate, but I don't think that is what you meant.

        fprintf(stdout, "e found\n");
        for (j = i + 1; isspace(s[j]); ++j);

Why would you allow space here? Why j?  Why didn't you stick with i?

        esign = (s[j] == '-') ? -1 : 1;
        if (s[j] == '+' || s[j] == '-') ++j;
        for (; isdigit(s[j]); ++j) {
            eval = 10 * eval + (s[j] - '0');
        }

I note that this is pretty much the same as a previous block of code. Consider extracting the common bits into a function:

        fprintf(stdout, "eval = %d\n", eval);
        int l;
        for (l = 0; l < eval; l++) {
            (esign >= 0) ? (rtn *= 10) : (rtn /= 10);
        }

I suspect using a pow() function would be more fruitful.

    }

    // Finally return the solution
    return rtn;
}


Creating Simple New Elements, Object Instances and Assigning IDs

Not sure why you need an id, I think you can do the same without any id.

Even the Entity object array is not clear why you need it.

But the first point is to wrap up your code in a function, so you can contain it safely.

So add a function that contains all the code and just design what you need to pass to that function and what you need to have as a public API from your module.

Another point is about your html:

  <button id='btn' onClick='createEnty()'>Create</button>

You should do the bind on the javascript code instead. As you already provided an id for the button, you can easely access to the object and bind on the click event.

So your module can be like so:

function MakeEntryModule(buttonSelector, containerSelector) {
    // code here

    // here the return object with the public methods
    return {
       myMethod: myFunction
    }
}

// then you can do so:
var entryModule = MakeEntryModule('#btn', '#container');

You can also use an anonymous function that is called directly:

var entryModule = (function(a,b){
    // code goes here
})('#btn', '#container');

This is fine, but the previous is more clear when you have parameters.

So here is a rewrite of your code:

function MakeEntryModule(buttonSelector, containerSelector) {
    // cache the container element to avoid
    // performing the search each time.
    var container = document.querySelector(containerSelector);

    // just pass title and description to the createEntry
    // function to be able to make it more generic.
    function createEntry(titleText, descriptionText) {
        var entry = document.createElement("div");
        entry.classList.add("entry");
        entry.appendChild(createSpan("title", titleText));
        entry.appendChild(createSpan("description", descriptionText));
        entry.appendChild(deleteButton(entry));

        container.appendChild(entry);
    }

    function createSpan(className, text) {
        var spn = document.createElement("span");
        spn.classList.add(className);
        spn.appendChild(document.createTextNode(text));
        return spn;
    }

    // the delete element can be make so:
    function deleteButton(toDelete) {
        var btn = createSpan("remove", "remove");
        var _listener = btn.addEventListener("click", function () {
            btn.removeEventListener("click", _listener);
            toDelete.remove();
        });

        return btn;
    }

    // here you bind your createEntry to the button
    var _listener = document.querySelector(buttonSelector)
        .addEventListener("click", function () {
            createEntry("title text here", "description text here");
        });

    // the only public API needed is the remove listener
    // to avoid memory leak
    return {
        removeListener: function () {
            document.removeEventListener("click", _listener);
        }
    }
}

You can even make it shorter using modern Javascript syntax:

function MakeEntryModule(buttonSelector, containerSelector) {
    const container = document.querySelector(containerSelector);

    function createEntry(titleText, descriptionText) {
        const entry = document.createElement("div");
        entry.classList.add("entry");
        entry.appendChild(createSpan("title", titleText));
        entry.appendChild(createSpan("description", descriptionText));
        entry.appendChild(deleteButton(entry));

        container.appendChild(entry);
    }

    function createSpan(className, text) {
        const spn = document.createElement("span");
        spn.classList.add(className);
        spn.appendChild(document.createTextNode(text));
        return spn;
    }

    function deleteButton(toDelete) {
        const btn = createSpan("remove", "remove");
        const _listener = btn.addEventListener("click", () => {
            btn.removeEventListener("click", _listener);
            toDelete.remove();
        });

        return btn;
    }

    const _listener = document.querySelector(buttonSelector)
        .addEventListener("click", () =>
            createEntry("title text here", "description text here"));

    return {
        removeListener: () =>
            document.removeEventListener("click", _listener)
    }
}

You should use const and let instead of var if possible, use var only if you have browser compatibility requirements.

About arrow functions, they are very compact and elegant, but use with carefull as they have a different behaviour compared with normal functions.

They are good for event handlers as they bind the declaration context, with the "correct" this object scope.

But they can drive to performance issues in some situations.

I get rid of the objects array, if you really need you can add it without problem.


Can this coffeescripts method be simplified?

First, return true if num is 5 is the same as just num is 5.
Then, you can convert the explicit loop into a reduce (you can read about it in Wikipedia or MDN):

MyObject =
  checkCondition: (num) -> num is 5

  getSum: (num) ->
    [0..num].reduce (x,y) =>
        if @checkCondition y then x + y else x

Note => instead of plain -> after (x,y). This is fat arrow, it prevents the capture of @ the inside function.


Selecting control class in a document assembler

If all the Test methods look like in the provided sample implementation then I see several approaches to make your factory method cleaner:

Use a switch:

public static class Instructions
{
    public static const string DeleteIf = "DeleteIf";
    public static const string Optional = "Optional";
    ...
}

public static PrecedentControl AsPrecedentControl(this Wd.ContentControl control)
{
    switch (instruction.Command)
    {
        case Instructions.DeleteIf: return new DeleteIf(control);
        case Instructions.Optional: return new Optional(control);
        ...
        default:
            throw new InvalidInstructionException(instruction);
    }
}

Use a data driven approach with a Dictionary:

Dictionary<string, Type> InstructionMap = new Dictionary<string, Type>
{
    { Instructions.DeleteIf, typeof(DeleteIf) },
    { Instructions.Optional, typeof(Optional) },
    ...
}

And your factory method being:

public static PrecedentControl AsPrecedentControl(this Wd.ContentControl control)
{
    Type instructionType = null;
    if (InstructionMap.TryGet(instruction.Command, out instructionType))
    {
        return Activator.CreateInstanceOf(instructionType, control);
    }
    throw new InvalidInstructionException(instruction);
}

If by convention the instruction commands are all named the exact same as the corresponding classes dealing with them you can build the dictionary dynamically once via reflection by finding all the types deriving from PrecedentControl. Something along these lines might work:

typeof(PrecedentControl).Assembly
                        .GetTypes()
                        .Where(t => !t.IsAbstract && typeof(PrecedentControl).IsAssignableFrom(t))
                        .ToDictionary(t => t.Name, t => t);


OOP implementation of Rock Paper Scissors game logic in Java

I don't see anything object-oriented in it. A program without a single non-static method can hardly be called OO.
The main task of this piece of code is to compare PlayedMove instances, so to follow OO style, you should make that comparison a method of PlayedMove. This will make the enum a bit more complex (beyond beginner level), so you might want to switch away from PlayedMove being an enum (or, use it as an exercise on complex enums).


Prompting for a positive integer and validating user input in Java

while (true) { // This is often frowned upon?

Frowned upon? Not that I know of.

Using a scanner for extracting numbers or tokens from a stream of input is great when the data is guaranteed to be in the expected format, and when it's ok to crash on any error.

The .nextInt and similar methods are less practical when you have to validate the input and give a chance to retry. In such cases I find it a lot more practical to read line by line, and perform the integer parsing manually, like this:

public static int getPositiveIntInput(String message) {
    System.out.print(message);

    while (true) {
        String line = sc.nextLine();
        try {
            int n = Integer.parseInt(line);
            if (n > 0) {
                return n;
            }
        } catch (NumberFormatException e) {
            // ok to ignore: let it fall through to print error message and try next line
        }
        System.out.print("Error: input must be a positive integer.\n" + message);
    }
}


Starting with the end: test.rb barely tests anything. Yes, it'll exercise your code, and make it crash if there's a mistake, but it doesn't actually verify that your code does what it's supposed to do.

So, I'd highly suggest you write proper unit test using one of the many test libraries out there (Ruby's own Test::Unit, minitest, rspec, etc...)

You seem to be confused about accessor methods. The purpose of attr_accessor is to have Ruby automatically generate the methods to get and set an instance variable. In your Member class, you're using attr_accessor, but you're also (redundantly) providing your own getters and setters. Since they literally just get and set, they're exactly the same as what attr_accessor has already made for you.

So Member can be reduce to this:

module Entity
  class Member
    attr_accessor :id, :username, :email, :password

    class << self
      def table_name
        @table_name ||= 'members'
      end
    end

    def table_name
      @table_name ||= 'members'
    end
  end
end

(Of course, id shouldn't be easily settable, but I can't cover everything in this review)

The whole table_name construction is odd too. If anything, this would make more sense:

module Entity
  class Member
    attr_accessor :id, :username, :email, :password

    def self.table_name
      'members'
    end
  end
end

Since table_name should probably be constant, just return a string. And don't duplicate the method for both class and instance. If anyone needs the table name from an instance, they can do some_member_object.class.table_name.

Your Main class also has some funny ideas about data access. Here, you're not using attr_reader :keys and attr_accessor :table_name although you might as well. Then you can skip the methods. The other reason to do this is that naming methods get_* or set_* is not very Ruby-like.

get_values (which should just be named values), is also problematic for a few reasons:

Main is supposed to be pretty abstract. Why does it assume that values should be returned as quoted strings? What is the derived class isn't meant for SQLite or any kind of SQL? Perhaps you just want the raw values?
Yes, in fact you do want the raw values! Poor string-quoting is the oldest attack vector in the book. For instance, what if, say, the password value is a string like this: "sup'); DROP TABLE members;"?

With your code, you'll end up running the following the current query when trying to save:

INSERT INTO members (email, username, password)
VALUES ('foo@example.com', 'foo', 'sup'); DROP TABLE members; ');

A basic SQL injection attack. As you can see from the syntax highlighting, the SQL suddenly contains TWO commands: INSERT and DROP TABLE. You insert a row... and it happens to delete your entire table. Oops.

Long story short: Use proper parameter substitution (which the sqlite3 gem has built in):

db.execute("INSERT INTO members (email, username, password) VALUES (?, ?, ?)", [email, username, password])

That let's sqlite take care of doing proper string quoting/escaping and all that. It's safe.

And you can replace the get_values method with attr_reader :values.

Of course, the only reason attr_readers make sense is that you have the prebuild method. Which doesn't really make much sense. If must be called before anything else works, so if anything it should be a constructor.

But really, it's simpler to just drop Main entirely, and instead add a superclass for Member:

class Record
  def to_hash
    instance_variables.each_with_object({}) do |hash, name|
      key = name.to_s.sub('@', '') }
      value = send(key)
      hash[key] = value;
    end
  end
end

class Member < Record
  ...
end

And then the sqlite adapter becomes:

require 'sqlite3' # require statement should be at the top of the file

class Sqlite
  def initialize
    @db = SQLite3::Database.new 'file.db' # the filename should really be an argument
  end

  # formerly named "persist", but "persist" can mean either insert *or* update
  def insert(record)
    hash = record.to_hash.delete("id")
    markers = ["?"] * hash.keys.count
    sql = "INSERT INTO #{record.class.table_name} (#{hash.keys.join(',')} VALUES (#{markers.join(','))"
    @db.execute(sql, hash.values);

    record.id = @db.execute("SELECT last_insert_rowid()")
    record
  end

  # presumably you'll only want 1 record returned when searching by id
  def retrieve(klass, id)
    columns = columns_in_table(klass.table_name)
    rows = @db.execute("SELECT * FROM #{klass.table_name} WHERE id=? LIMIT 1", id)
    return nil if rows.empty? # nothing found
    instance = klass.new
    rows.first.zip(columns).each do |key, value|
      instance.send("#{key}=", value)
    end
    instance
  end

  def delete(record)
    @db.execute("DELETE FROM #{record.class.table_name} WHERE id=#{record.id}"
  end

  private

  def columns_in_table(table)
    @db.execute("PRAGMA TABLE_INFO (#{table})").map { |info| info[1] }
  end
end

Of course, there's still a long way from here to a well-known and battle-tested implementation like Rails' ActiveRecord. For instance, you currently have to duplicate the names of columns in your objects. If an object doesn't have the same instance variables as the table's columns - or if they're named differently, or of the wrong type... - things will break.

So, in all, a good exercise, but not something I'd rely on.


Is this algorithm efficient for the 01Knapsack?

It's no way optimal. Looking at the wiki, there are algorithms using dynamic programming, which are surely faster.

The other thing is fooling around with a HashSet. It's a nice and fast data structure, but all you need is a boolean[], which is an order of magnitude faster. And it also makes it all simpler.

Item#taken is not a good idea. It should a property of the knapsack, the item doesn't really care. Imagine, you'd parallelize your program, then you'd need an immutable Item.

calculateTotalWorth should be replaced by an incremented computation the way weight gets computed.

The knapsack.worth should only be checked when no item fits. Otherwise, you know that it's not optimal yet.


if (list.Count <= maxCount)
{
    throw new InvalidOperationException("Items in list <= maxCount, unable to trim list.");
}

This doesn't seem like an exceptional case to me. If the idea is to trim the list to a certain size and the list is already smaller than that size -- the job is already done! In that case I would replace this with return true;.

while (list.Count > maxCount)
{
    T last = list.Last<T>();
    list.Remove(last);
}

This is the main guts of your method. Since the preceding if statement has already established that list.Count > maxCount, you know that the loop is always going to run at least one. Therefore you could replace this with a do-while loop. This is a negligible performance improvement.

do
{
    T last = list.Last<T>();
    list.Remove(last);
}
while (list.Count > maxCount)

catch
{
    return false;
}

Two problems here.

YAGNI
Using boolean values to indicate whether or not the method was successful is a design flaw. This harks back to the old HRESULT days which were universally loathed. Instead, let the exception do the job of alerting the calling code to errors (this is what exceptions are for). In the case that there is no exception, there is no use for the returned true value.

You could also consider returning a reference to the list itself from the method, allowing people to use method chaining syntax, which is all the rage these days - especially with LINQ..

public static List<T> TrimFirst<T>(this List<T> list, int maxCount)
{
    if (list.Count <= maxCount)
        return list;

    do
    {
        T first = list.First<T>();
        list.Remove(first);
    }
    while (list.Count > maxCount);

    return list;
}

One final thing. It's usually a good idea to defend against NullReferenceExceptions by asserting that your argument is not null.

if (list == null)
    throw new ArgumentNullException("list");

ArgumentNullExceptions are always preferable to NullReferenceExceptions.


In a clean rule, consider removing $(OBJECT_FILES) instead of src/*.o
I don't see where LDFLAGS is ever used.
I understand that you are not likely to edit include files; however, to be on a safe side you may want to add auto dependency generation:

DEP_FILES = $(SOURCE_FILES:.cc=.d)

%.d: %.cc
    $(CC) $(INCLUDES) $(CXXFLAGS) -MM -MT -o $@ $<

-include $(DEP_FILES)

(and remove $(DEP_FILES) on clean).


Overall I think you have about the simplest you could hope for. The only thing I'd do is set your bounds better. You know that you can do min(array)/ceil(k/len(array)) and you know you at most you can do max(array)/floor(k/len(array)).

I was going to suggest going for extra credit with a more sophisticated algorithm, but I don't think you can beat what the binary search approach. At worst you're going to be 32 or 64 * O(n). Given the simplicity of the algorithm I think that will likely beat sorting and all the alternatives I can think of either explicitly or implicitly do a sort which would be O(n log n).


Updating the presentation of a credit card field as the card type becomes known

Create a map from card.type to what class it should be:

var cardTypeToClass = {  'visa': 'e-visa',
                         'master-card': 'e-master-card',
                         //...
                       };

This creates an associative array so if you give it a key value then you can get out the associated value.

in your case that is done like:

if (event.isValid) {
    $("#card-number").addClass(CREDIT_CARD_LIST.replace(CREDIT_CARD_LIST, cardTypeToClass[event.card.type]));
} else {
    $("#card-number").removeClass(CREDIT_CARD_LIST);
}

This concentrates the mapping into a single section and separates out what the code actually does.


Solution to King Kohima problem in Python

There is a much faster solution to this problem. If the ending character is Y, two strings can be created. But if the ending character is X, only one valid string can be created: XY. This results in the following equation, complexity O(n):
def king_kohima(number: int) -> int:
    x = [0, 1, 1]
    y = [0, 1, 2]
    for i in range(3, number + 1): # Start at 3 so we skip results already stored.
        x += [y[i - 1]]
        y += [x[i - 1] + y[i - 1]]
    result = x[number] + y[number]
    return result * result

After benchmarking, this code is substantially faster than your original code.
Benchmarks:
Iterations king_kohima_op:      100     1.52433s
Iterations king_kohima:         100     0.00154s
Iterations king_kohima_op:      200     2.80376s
Iterations king_kohima:         200     0.00617s
Iterations king_kohima_op:      300     4.28752s
Iterations king_kohima:         300     0.01403s
Iterations king_kohima_op:      400     5.65897s
Iterations king_kohima:         400     0.02699s
Iterations king_kohima_op:      500     7.35554s
Iterations king_kohima:         500     0.04244s
Iterations king_kohima_op:      600     8.48669s
Iterations king_kohima:         600     0.06066s
Iterations king_kohima_op:      700     9.78000s
Iterations king_kohima:         700     0.08022s
Iterations king_kohima_op:      800     10.87804s
Iterations king_kohima:         800     0.10385s
Iterations king_kohima_op:      900     12.21734s
Iterations king_kohima:         900     0.13148s
Iterations king_kohima_op:      1000    13.80984s
Iterations king_kohima:         1000    0.16195s


I would recommend your outputs be flops. It would be a cleaner output signal and easier to do timing analyses. It takes time (few nano seconds) to calculate the tx value after the clock with combinational logic. During that time the intermediate values are being transmitted and causing noise. This noise will can get worse from resistance an capacitance in your USB cable; lowers the signal quality. It seems your running at low speeds, so you wouldn't see a problem, but at higher speeds you may run into trouble.

Be aware that many synthesizers treat conditional operators (the ? : syntax) as explicit 2:1 muxes. So your current tx logic will always be a chain of 2:1 muxes even when a 4:1 is more suitable. A case statement within an always block tend to synthesize more optimally. I have a more detail answer for ? : vs case() on here on Electronics StackExchange.

Usually a FSM is written as a case statement; not if-else statements. The synthesizer doesn't really care. It is more of a common practice with RTL designers. It makes the FSM easier to identify and control how it synthesizes (full_case, parallel_case, onehot, encoding, etc.).

For a more optimzed design, your code should look something like the below. Or you can use two always blocks (my preference); one for calculating the next states for the flops, the other for simple flop assignment.

module uart_send #(parameter BAUD_RATE = 9600,
                   parameter CLOCK_SPEED_MHZ = 100)
                  (input [7:0] data_byte,
                  input start_send,
                  input clk,
                  output reg tx, // <-- reg outputs
                  output reg ready); // <-- reg outputs

  /* ... local parameter and reg declarations here ... */

  always @(posedge clk) begin
    case(state)
      IDLE : begin
          /*your IDLE code here*/
        end
      START_BIT : begin
          /*your START_BIT code here*/
        end
      END_BIT : begin
          /*your END_BIT code here*/
        end
      DATA_BIT : begin
          /*your DATA_BIT code here*/
        end
    endcase
  end

endmodule

I will also suggest changing the uart_send instantiation form connect by port order to connect by name.

uart_send sender("X", count == 100000000, clk, tx, ready);

to (port order does not matter)

uart_send sender( .data_byte("X"), .start_send(count == 100000000),
                  .clk(clk), .tx(tx), .ready(ready) );

or even cleaner (width matching)

wire [7:0] data_byte = "X";
wire start_send = (count == 100000000);
uart_send sender( .data_byte(data_byte), .start_send(start_send),
                  .clk(clk), .tx(tx), .ready(ready) );

I believe you can abbreviate matching name and size to just .name (ex .clk is the same as .clk(clk)) but I do not remember if that if Verilog or an added feature in SystemVerilog. I not have my copy if the LRMs with me.

wire [7:0] data_byte = "X";
wire start_send = (count == 100000000);
uart_send sender( .data_byte, .start_send, .clk, .tx, .ready );


Step 1: extract to a method

In the current code you have a hardcoded array, and the main logic follows right after. It's hard to test this way. What if you want to see if the implementation works with a different set of numbers? You have to rewrite the array. Better to extract the main logic into its own, independent method:

int[] sort(int[] arr) {
    // ...
}

Now you can test with multiple different inputs easier:

arr = new int[]{2, 5, 1, 8, 12, 3, 7};
InsertionSort.sort(arr);
System.out.println(Arrays.toString(arr));

arr = new int[]{4, 3, 2, 1, 2};
InsertionSort.sort(arr);
System.out.println(Arrays.toString(arr));

Step 2: convert print statements to proper unit tests

The problem with print statements is that every time you change something and rerun, you have to re-verify the output of each statement. Unit tests can automate the verification step, and converting is easy enough to do:

private void sort(int[] arr) {
    InsertionSort.sort(arr);
}

@Test
public void testMixedValues() {
    int[] arr = {2, 5, 1, 8, 12, 3, 7};
    sort(arr);
    assertEquals("[1, 2, 3, 5, 7, 8, 12]", Arrays.toString(arr));
}

@Test
public void testDecreasingValues() {
    int[] arr = {4, 3, 2, 1};
    sort(arr);
    assertEquals("[1, 2, 3, 4]", Arrays.toString(arr));
}

Btw, I didn't type the expected strings in the assertEquals. I wrote the test cases first, with "" as the expected values, and ran the tests. All the tests failed, of course, but the error messages told me the actual values that were different from the expected "". I verified that they are correct and copy-pasted the correct texts into the test cases.

Now you can make changes and the test cases will flag an error if something breaks. Unless you do something really horrible, typically only a few of the test cases will break, and you don't need to reverify the others that are still working, which makes debugging a lot easier.

Return void instead of int[]

It might be better to return void instead of int[]. The problem with returning int[] is that the caller might wonder if the returned array is a new array or not. It is not a new array. For example in this code:

int[] arr1 = { 9, 4, 6, 2, 1, 7 };
int[] arr2 = InsertionSort.sort(arr1);
arr2[3] = -1;

Both arr1 and arr2 will be modified, which might be counter-intuitive.

The fact that java.util.Collections.sort() also returns void suggests that it's better that way.

Minor things

The method name insertionSort is redundant, because the word "insertion" is already in the class name. How about simply sort?


Project Euler Problem 1 - Multiples of 3 and 5

I think that any is your friend here.

aMultipleOf factors x = any (\f -> x `rem` f == 0) factors
prob001 :: (Integral a) => [a] -> [a] -> a
prob001 nums factors = sum $ filter (aMultipleOf factors) nums


How to re-factor dynamic menu code to OOP in a MVC framework?

Ok, firstly, you never want HTML in your controller. Always keep your output in your view, your application flow in the controller and your business logic in the model. Otherwise, this breaks separation of concerns (SoC). See https://stackoverflow.com/questions/1376643/mvc-separation-of-concerns for a relevant answer.

Below, I am defining two classes - URI and User. These two should exist in your MVC platform to handle URI and User based actions (checking if a user is logged in, checking for the current URI or Permalink, etc). These would likely be helpers. We will use these later on by injecting them into our Menu::get() function.

# Placeholder classes URI and User, which handle all URI and User activity
class URI{
    # ...
}

class User{
    # ...
}

Below is the Menu class. Note that I namespaced it, considering its a helper, this would allow it to be called with full namespace path if you placed the helper directory into your autoloader.

Note how we are injecting an instance of URI via parameter $uri, and an instance of User via parameter $user. This is Dependency Injection (see https://stackoverflow.com/questions/130794/what-is-dependency-injection).

# Helper class "Menu"
namespace KidDiamond\MVC\Helpers;

class Menu {
    # Rather than defining a new User object, just inject the user object as a parameter
    public static function get(URI $uri, User $User){
        if (!$user->isLoggedIn()) {
            $navArr = Config::get('navigation');

            $menu = '
' . PHP_EOL;
            foreach ($navArr as $name => $path) {
                $xor_active = ((in_array($URI, $path)) ? ' class="active"' : false);
                $menu .= '\t
' . $name . '
' . PHP_EOL;
            }
            $menu .= '
' . PHP_EOL . PHP_EOL;
        } else {
            # logged off navigation menu
        }

        return $menu;
    }
}

Now, we move on to the Controller. Notice how all its doing is maintaining an initialized $menu_helper variable. You could technically inject the Menu helper...but I personally prefer to initialize it to a property.

The $data variable inside the index() method is automatically returned, and injected into our view, below.

# Controller class HomeController
namespace KidDiamond\MVC\Controllers;

class HomeController extends \BaseController{
    private $menu_helper;

    public function __construct(){
        $this->menu_helper = new KidDiamond\MVC\Helpers\Menu;
    }

    public function index(){
        $data['dynamic-menu'] = $this->menu_helper();

        return $data;
    }
}

This is our (simple) view. Notice that we're using a templating system (Blade, Mustache, etc) to output our variable dynamic-menu which was in the $data array in our controller method.

# View for /index

            {{dynamic-menu}}

I hope this helps. Do note that the code above is completely untested and is only there to help point you in the right direction. There may be syntax errors and other general errors.


~ThreadPool() = default;

We need to call stop() in the destructor!

template<typename Func, typename... Args>
decltype(auto) add_task(Func&& func, Args... args) {
    using ReturnType = decltype(func(args...));

For perfect forwarding we need to use && for args:
template<typename Func, typename... Args>
decltype(auto) add_task(Func&& func, Args&&... args) {
    using ReturnType = decltype(func(std::forward<Args>(args)...));

ThreadPool(int number_of_workers) {

We need to check that this number is greater than zero. Also it might be better to use an unsigned int to match the result of std::thread::hardware_concurrency().

void thread_func() {
    while(true) {
        std::unique_lock lk{pool_mutex};
        if (task_queue.empty() && stopped) {
            break;
        }
        ...

I'm not sure that we should wait for the task_queue to be empty before stopping. I'd suggest that stop() should prevent threads taking any more tasks from the queue (i.e. provide a way to "cancel" tasks that haven't started executing yet).
If we wait for the queue to be empty when calling stop(), we're waiting for all the tasks to complete, so calling stop() doesn't really do much. (The calling code is already in control of whether or not it adds more tasks and waits for futures).
        if (task_queue.empty()) {
            cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });
        }

We don't really need to put cond.wait() in an if statement. It will check the condition before waiting.
I'd probably go for something more like:
void thread_func() {
    while(true) {

        std::unique_lock lk{pool_mutex};
        cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });

        if (stopped)
            break;

        assert(!task_queue.empty());

        auto callable = std::move(task_queue.front());
        task_queue.pop();

        lk.unlock();

        callable();
    }
}


There is never a need to do this:

return Task.Run(() => GetDataAsync()).Result;

Why start a new task and then synchronously wait with .Result? This is the sort of code that will bite you later when you find out that a synchronisation context can cause a deadlock. See Stephen Cleary's blog post on the subject of an async deadlock. Stephen's blog is an absolute gold mine of information on aysnc and await.

Either use the synchronous api all the way from your controller down into the Azure Storage SDK or use the asynchronous one (with async and await). Don't mix and match - that's a source of errors and also pointless. Aysnc is useful when there's something else the thread could be doing. E.g. in a web app that's serving requests. If the web app is blocked by .Result or Wait then there is no benefit and you should use the synchronous API.


First of all, the fact that you are mixing the use of Jackpot and MultiJackpot in this way suggests that they are really 2 different instances of a common, underlying concept. That calls into question whether they really need to be implemented as two different models. But that's up to you; you know the specifics of your own application.

As for removing the duplication, how about something along the lines of:

games     = ['Caribbean Stud', 'Progressive Blackjack']
@jackpots = games.map do |game|
  [Jackpot.where(...),
   MultiJackpot.where(...)]
end

You end up with an extra level of array nesting in the results, which could be eliminated with flatten(1). Or if don't mind adding your own methods to Array, I like to add one called mappend... I find it useful in almost every project. It it like map, but it appends all the returned arrays together to form a single array.

If you need the names of the games together with the results, you can games.zip(@jackpots) (you need the extra level of nesting for that one).

As for the DB calls, you'll find it hard to work around that while still using your nice Active Record query helpers. When DB performance is critical, I usually end up rolling my own SQL, perhaps using custom helpers added to model classes.


You don't seem to have a policy for a maximum pool side. Is that by mistake or by design? What should happen if someone requests an object too many?
Your choice of method names is slightly off. When I talk to an object pool, I don't want to Loan it an object, nor do I want to Receive an object. I want to "borrow," "obtain," "take" or "get" an object from the pool, and I want to "return" or "release" or "put" an object back into the pool.

I'd suggest:

obj = pool.Borrow()
// ...
pool.Return(obj)

Finally, why does your object have an id? It seems unused. I'd suggest just using interface{} as your object type.


Classes to serialize departments and their employees

Using inheritance, first you can clean up your structure as following:

class DepartmentNameSerializer < Serializer
  self.root = false
  attributes :id, :name
end

class DepartmentSerializer < DepartmentNameSerializer
  has_many :employees, serializer: EmployeeSerializer
  has_one :location, serializer: LocationNameSerializer
end

class DepartmentWithManagersSerializer < DepartmentNameSerializer
  has_many :primary_managers, serializer: ManagerSerializer
  has_many :secondary_managers, serializer: ManagerSerializer
end

class DepartmentWithEmployeesSerializer < DepartmentNameSerializer
  has_many :employees, serializer: EmployeeNameSerializer
end

There is little you can do to really enhance your code any further in terms of readability and reusability if you want to separate all serializer contexts into separate classes like this.

If you are using ActiveModel::Serializers which I think you do, since 0.8.0 you can use ActiveRecord-Serialization-like :except and :only to add some serialization context, so you could refactor your structure to work like the following:

class DepartmentSerializer < Serializer
  self.root = false
  attributes :id, :name, :employee_names, :location_names
  # it is afaik not possible to pass serialization context to the other serializers
  # via association
  # has_many :employee_names, serializer: EmployeeSerializer, only: :name
  # has_one :location_names, serializer: LocationSerializer, only: :name
  has_many :employees, serializer: EmployeeSerializer
  has_many :primary_managers, serializer: ManagerSerializer
  has_many :secondary_managers, serializer: ManagerSerializer

  def employee_names
    EmployeeSerializer.new(object.employees, only: :name) # + root: false if EmployeeSerializer uses a root
  end

  def location_names
    LocationSerializer.new(object.locations, only: :name) # + root: false if LocationSerializer uses a root
  end
end

And your controllers can call the DepartmentSerializer like this:

class DepartmentController < ApplicationController # or other

  def some_context_with_managers
    render json: @department, except: %i(employees employee_names location_names)
  end

  # ... and so on
end


I'm not a big fan of your type-hinting comments.  Let JavaScript be JavaScript.  If you want typing, practice TypeScript instead.

I find it counterintuitive that the ListNode constructor takes its next parameter before its val parameter.  Putting val first is more natural (see my piDigits example below), and also allows next to be omitted for the last node in a list.

You can use the {val, next} syntactic shorthand.

As for the reverseLinkedList algorithm, there is too much code, with too many special cases.  The fact that you mention .next.next, reaching two elements ahead, is a sign that you aren't thinking about the loop invariant the right way.  You want the code to consider just the local situation at the head.

It's not really appropriate to explicitly set a variable to undefined; undefined is supposed to represent the fact that no assignment has taken place.  In any case, you should be more lenient than checking for … === undefined.

I find that it's nearly always unhelpful to use temp as a variable name or in a variable name.

const ListNode = (val, next) => { return {val, next}; };

const reverseLinkedList = (head) => {
    let newTail = null;
    while (head) {
        let next = head.next;
        head.next = newTail;
        newTail = head;
        head = next;
    }
    return newTail;
};

let piDigits = ListNode(3, ListNode(1, ListNode(4, ListNode(1, ListNode(5)))));
console.log(reverseLinkedList(piDigits));

let emptyList = null;
console.log(reverseLinkedList(emptyList));


If you don't mind modifying the original array, you can shorten the (perfectly adequate code you have) with this:

$head = array_splice($course, 0, $team);  // remove and return first $team elements
$merged = array_merge($course, $head);    // append them to the end

You should be able to omit the temporary $head array by inserting the array_splice call into the array_merge call at the cost of a little code clarity. Try it out to make sure the order of operations is correct.

$merged = array_merge($course, array_splice($course, 0, $team));

Edit: If you're doing this once per team you can use a loop with array_shift to remove the first element and array_push to place it at the end:

for ($team = 0; $team < $numTeams; $team++) {
    array_push($course, array_shift($course));
    // use $course...
}


Your suggestion is not really type-safe as you can still pass a key of the wrong type. Therefore I would just use a normal (string) key. But I would add a generic TryGet method which takes account of the type. The setter needs not to be generic.

static class DictionaryExtensions
{
    public static T Get<T>(this IDictionary<string, object> dictionary, string key)
    {
        return (T)dictionary[key];
    }

    public static bool TryGet<T>(this IDictionary<string, object> dictionary,
                                 string key, out T value)
    {
        object result;
        if (dictionary.TryGetValue(key, out result) && result is T) {
            value = (T)result;
            return true;
        }
        value = default(T);
        return false;
    }

    public static void Set(this IDictionary<string, object> dictionary,
                           string key, object value)
    {
        dictionary[key] = value;
    }
}

You can then use the dictionary like this.

int age = 20;
dictionary.Set("age", age);

// ...

age = dictionary.Get<int>("age");

// or the safe way
if (dictionary.TryGet("age", out age)) {
    Console.WriteLine("The age is {0}", age);
} else {
    Console.WriteLine("Age not found or of wrong type");
}

Note that the compiler can infer the generic type when using TryGet.

UPDATE

In despite of my suggestion above, I must agree that your solution is elegant. Here is another suggestion which is based on your solution but which encapsulates the dictionary instead of providing a key. Well, it acts as wrapper and as key at the same time

public class Property<T>
{
    Dictionary<object, object> _dict;

    public Property (Dictionary<object, object> dict)
    {
        _dict = dict;
    }

    public T Value {
        get { return (T)_dict[this]; }
        set { _dict[this] = value; }
    }
}

Alternatively, a string key could be provided in the Property's constructor.

You can use it like this

private static readonly Dictionary<object, object> _properties =
    new Dictionary<object, object>();
private static readonly Property<int> _age = new Property<int>(_properties);

...

_age.Value > 18
_age.Value = age


Powershell to quickly ping a number of machines

Want to start of with I am new to workflows as well. For the most part your code is solid. You should see a couple of suggestions that would actually improve performance especially if you are running this against 100's of computers.

Grouping logic

This is more of a compliment. I thought, from what I read, that -ThrottleLimit would be a simple answer to replace your grouping logic. Likely from my inexperience but most of my testing shows that what you have there outperforms some simple tests that use just -ThrottleLimit. I know that it does have its place but here I think what you have is actually better.

Use a parameter for grouping/ throttling

You have a necessary property for $computers but I think it would make just as much sense to have a parameter in the workflow for GroupSize as well.

Use of ScriptMethod

While this is a neat way to get the computers group together I think it is overkill for a simple array of computers. You can avoid group-object all together really since you already know how to group the computers. Instead consider just using a simple foreach-object loop that extracts the chunks of computers each as there own array. In practice there is no performance gain here. It is easier to understand if it was simple array splitting.

Many different ways of splitting the array into smaller chunks as well. I was trying to avoid a simple counter that reset when it reached the $groupsize

As an aside I'm am disappointed that you still need Add-Member if you want to make something other than a note property easily. I read about another approach here but did not think it was useful enough to suggest in your case.

New-Object and [pscustomobject]

You use both approaches for creating object. Might as well just stick to one. When I changed your final object creation to just a [pscustomobject] cast on the hashtable it actually improved performance!

Testing the connection twice

I like the idea of hardening the test. It is possible that a computer might not respond to the first ping and could be recorded as down when it is indeed not. So I am fine with doing the test twice.

However when you are testing a computer that is up you would ping it twice. Would be better to do two separate tests and do it in such a way that the first, if successful, will prevent checking again as it would be redundant.

Consider the following very simple If statement.

if(1 -eq 1 -or 1/0 ){"Yo"}

At first glance you should see the divide by 0 for the second condition and expect failure. That will never be checked since 1 -eq 1 will always be true. Since the first condition is true then PowerShell will ignore the right hand condition as it would not change the outcome. This concept is covered under about_logical_operators in the last paragraph.

So I propose something like this:

$pingable = (Test-Connection $_ -Count 1 -Quiet -ErrorAction SilentlyContinue) -or
                        (Test-Connection $_ -Count 1 -Quiet -ErrorAction SilentlyContinue)

Same command is called twice but only if the first one fails. So it is still hardened but should be efficient as well. I suppose you could splat the commands since they are the same but I was trying to keep extra logic out of the loop for performance.

You by no means need to use this code but I implore you to try both yours against mine to see if there is at least a performance improvement.

workflow Test-ConnectionQuickly {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string[]]$computers,
        [Parameter(Mandatory = $false)]
        [int]$GroupSize = 10
    )
    $computerGroups = InlineScript {
        #group computers to throttle the number of threads
        $numberofGroups = [math]::Ceiling($using:Computers.Count / $using:groupSize)
        1..$numberofGroups | ForEach-Object{
            # Arrays are zero based which is why you will see -1
            ,($using:computers | Select -Index ((($_ - 1) * $using:GroupSize)..($_ * $using:GroupSize - 1)))
            # Use the unary operator to ensure an array of computers is returned and not unrolled.
    }

    }
    ForEach -parallel ($computerGroup in $computerGroups) {
        $computerGroup | ForEach-Object{
            $pingable = (Test-Connection $_ -Count 1 -Quiet -ErrorAction SilentlyContinue) -or
                        (Test-Connection $_ -Count 1 -Quiet -ErrorAction SilentlyContinue)
            [pscustomobject]@{Name=$_;Online=$pingable}
        }
    }
}

The only points I would recommend, if nothing else, is [pscustomobject]@{Name=$_;Online=$pingable} and how I broke up the ping test into 2 separate tests.

Most of my testing was done with a $GroupSize of 5 and 80 computers.

Measure-Command -Expression {Test-ConnectionQuickly $computers -GroupSize 5}

You definitely need to experiment with $GroupSize to find that sweet spot.


Keep main content scrollable but not the body

You can use flexbox. This works in all modern browsers, and will also make it responsive.

.wrapper {
  /* Makes the wrapper fill the entire screen */
  position: fixed;
  top: 0;
  height: 100%;
  left: 0;
  width: 100%;
  /* The important bit */
  display: flex;
  flex-direction: column;
}

.main {
  /* Makes the main content take up the remaining space */
  flex: 1;
  overflow-y: scroll;
}

.header, .footer {
  height: 50px;
}

JSFiddle


Multithreading synchronization between reading and writing in a channel

if multiple threads try to read they may each decrement the buffer if one thread was interrupted right before it could decrement and after it passed the while

Instead use a Semaphore which is designed for just this:

public class Channel {

    private Semaphore sem = new Semaphore(0);

    public void read() throws InterruptedException {
        // This function should keep blocking until there is something to read.

        sem.acquire();
    }

    public void write() {
        // This function should just write (nothing) to the buffer (by increasing the counter of the imaginary buffer).
        sem.release();
    }
}

otherwise you should decrement in a loop:

int read;
do{
    while((read = buffer.get())==0){
    //sleep
    }
}while(!buffer.compareAndSet(read, read-1));


Function to get current timestamp in node

Your code does not work - process.hrtime() does not return with a timestamp of any useful form unless you compare it to another process.hrtime() in the same running program (typically used for measuring performance).

From the documentation:

  These times are relative to an arbitrary time in the past, and not
  related to the time of day and therefore not subject to clock drift.
  The primary use is for measuring performance between intervals

Bottom line is that the arbitrary time in the past could be anything, and not the same "epoch" as new Date().

There is no way in native JavaScript or Node (without making OS system calls through libraries, etc.) that I know of to get a more granular resolution than the millisecond times from Date.


Splitting text into individual characters for animation

There are a number of ways you can improve the javascript/jquery on this page.

If possible you should move all of your


Mathematically, the least common multiple of a range of numbers can be expressed as

$$LCM(1..1) = 1$$
$$LCM(1..n+1) = \frac{LCM(1..n) * (n+1)}{GCD(\;LCM(1..n), \;n+1)} $$

So you can start with 1 and work your way up

static long leastCommonMultiple(long n) {
    long multiple = 1;

    for ( long i = 1; i <= n; i++ ) {
        multiple *= i / gcd(multiple, i);
    }

    return multiple;
}

The optimal Greatest Common Divisor algorithm is

static long gcd(long a, long b) {
    return ( 0 == b ) ? a : gcd(b, a%b);
}

The iterative version is

static long gcd(long a, long b) {
    while ( 0 != b ) {
        long temp = a;
        a = b;
        b = temp % b;
    }

    return a;
}

Running with the iterative version takes about a third of the time that your solution does on my machine.

You can get an additional speedup by using the fact that you already know \$LCM(1..10) = 2520\$.

static long leastCommonMultiple(long n) {
    long multiple = 2520;

    for ( long i = 11; i <= n; i++ ) {
        multiple *= i / gcd(multiple, i);
    }

    return multiple;
}

That allows you to start at 11 rather than 1.  It's not much of a gain though.  And of course, it's unique to this particular problem.


Five functions to get the digits of a number

I'm afraid your code has errors,  so your benchmarking is invalid.

The get-digits-3 function is wrong.
A corrected version runs about twelve times slower than
get-digits-4.

Repairing get-digits-3

Your get-digits-3 doesn't work:

=> (get-digits-3 123456789)
()

The function chain should be applied to the argument num:

(defn get-digits-3 [num]
  (->> num
       (str)
       (map str)
       (map int)
       (into '())))

But this fails:

=> (get-digits-3 123456789)
ClassCastException java.base/java.lang.String cannot be cast to java.base/java.lang.Character  clojure.lang.RT.intCast (RT.java:1213)

The culprit is the (map int) line. You can't apply int to strings. If you drop the offending line, you get the character values:

=> (get-digits-3 123456789)
(57 56 55 54 53 52 51 50 49)

Notice, too, that they are in reverse order. So we

subtract the value of character 0 and
conj onto the other end by using a vector.

This gives us ...

(defn get-digits-3 [num]
  (->> num
       (str)
       (map int)
       (map #(- % (int \0)))
       (into [])))

=> (get-digits-3 123456789)
[1 2 3 4 5 6 7 8 9]

Benchmarking

I went about this differently:

I used a single example instead of a range.
I used Criterium's bench rather than its quick-bench.

The results were as follow:

For your original (faulty) version of get-digits-3:

=> (bench (get-digits-3 123456789))
...
             Execution time mean : 228.998292 ns

For the corrected version:

=> (bench (get-digits-3 123456789))
...
             Execution time mean : 3.440024 µs

And for get-digits-4:

=>(bench (get-digits-4 123456789))
...
             Execution time mean : 247.502418 ns

This confirms that your faulty get-digits-3 is about as fast as get-digits-4. And get-digits-3 ignores its argument, so is bound to get relatively faster as the numbers get bigger. You can see that the corrected version is nowhere near competitive.


Testing the same code with different input data

I've got one possible solution from Max Lunin:

NSArray *successCodes = @[@200, @201, @202, @203, @204, @205, @206];
for (NSNumber *statusCode in successCodes) {
    it([NSString stringWithFormat:@"should call operationSucceeded for status code %@", statusCode], ^{
        MKNetworkOperation *op =[[MKNetworkOperation alloc] initWithURLString:@"http://example.com/api" params:nil httpMethod:@"GET"];
        [op stub:@selector(notifyCache)];
        NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:nil
                                                                  statusCode:[statusCode intValue]
                                                                 HTTPVersion:nil
                                                                headerFields:nil];
        [op stub:@selector(response) andReturn:response];
        [[op should] receive:@selector(operationSucceeded)];
        [op connectionDidFinishLoading:[NSURLConnection nullMock]];
    });
}

It solves the problem with error explanation. It will tell something like: 'Operation, should call operationSucceeded for status code 202' [FAILED], expected subject to receive -operationSucceeded exactly 1 time, but received it 0 times

Any other more clear solutions?


Interface programming with Data Access Layer

The IBoundControl is good. It isolates the specific data calls. It's refreshing to see another approach than falling back to the repository pattern.

IBoundControl implementation is on a class that also doubles as the DTO. This is breaking the SRP. One way to solve this is to create class that's only job is for lookup values. Call it Lookup. It has two fields: Id and Name.

The new interface looks like this:

public interface IBoundControl
    {
         string GetCommandName();
         List<Lookup> ReadyReader(IDataReader rdr);
    }

Now the IBoundControl implementation will only contain data layer specific code and will return a normalized resultset of lookup values. Also notice that IBoundControl.ReadyReader is taking a dependency on IDataReader instead of implementation specific SqlDataReader.


Allow changing the properties of a mutable controller in a thread safe way

Another option is to create ControllerInfo with mutable properties and a Clone method which would return a copy of the instance.

Then on the ControllerInfo Info set, simply call the Clone method and set _info to the clone of the object passed in.

private ControllerInfo _info;

public Info
{
   get { return _info; }
   set { _info = value.Clone(); }
}

To be clearer you can do away with Info as a property and instead code a method

public Controller SetInfo(ControllerInfo info)
{
     _info = info.Clone();
     return this;
}

Doing away with "get" semantics for Info, is a good idea, as you do not want the interface to suggest that a get followed by mutating the Info object would reflect the changes in the Controller.


Pig Latin translator with too many `push_str`s

Write tests

Unfortunately, your piglatify doesn't follow your rules. apple gets transformed into applyaay, but it should get transformed into apple-hay. Also, first should get transformed into irst-fay, but you will transform it into irstfay.

Rust makes it really easy to add tests to your code:

#[cfg(test)]
mod test {
    use transform_word;

    #[test]
    fn empty_string() {
        assert_eq!(transform_word(""), "");
    }

    #[test]
    fn apple() {
        assert_eq!(transform_word("apple"), "apple-hay");
    }

    #[test]
    fn first() {
        assert_eq!(transform_word("first"), "irst-fay");
    }
}

While this only uses the given strings from the exercise, it already tells us that there is something amiss if we run the tests with cargo test:

running 3 tests
test test::empty_string ... FAILED
test test::first ... FAILED
test test::apple ... FAILED

failures:

---- test::empty_string stdout ----
    thread 'test::empty_string' panicked at 'byte index 1 is out of bounds of ``', /checkout/src/libcore/str/mod.rs:2217:9
note: Run with `RUST_BACKTRACE=1` for a backtrace.

---- test::first stdout ----
    thread 'test::first' panicked at 'assertion failed: `(left == right)`
  left: `"irstfay"`,
 right: `"irst-fay"`', src/main.rs:57:9

---- test::apple stdout ----
    thread 'test::apple' panicked at 'assertion failed: `(left == right)`
  left: `"ppleahay"`,
 right: `"apple-hay"`', src/main.rs:52:9

Use with_capacity if possible

You can use String::with_capacity in transform_word. The new word has the same length as the old one plus four:

fn transform_word(word: &str) -> String {
    if word.is_empty() {
        return String::new();
    }
    let mut new_word = String::with_capacity(word.len() + 4);

    // still buggy, see above
    new_word.push_str(&word[1..]);
    new_word.push_str(&word[..1]);
    if starts_with_a_vowel(word) {
        new_word.push_str("h");
    }
    new_word.push_str("ay");
    new_word
}

However, we still need to fix the bug mentioned before:

fn transform_word(word: &str) -> String {
    if word.is_empty() {
        return String::new();
    }
    let mut new_word = String::with_capacity(word.len() + 4);

    if starts_with_a_vowel(word) {
        new_word.push_str(&word);
        new_word.push_str("-hay");
        new_word
    } else {
        new_word.push_str(&word[1..]);
        new_word.push('-');
        new_word.push_str(&word[..1]);
        new_word.push_str("ay");
        new_word
    }
}

Alternative variants

Truth be told, that looks somewhat silly. We can just use += instead of push_str, or even +:

fn transform_word(word: &str) -> String {
    if word.is_empty() {
        return word.to_owned();
    }
    if starts_with_a_vowel(word) {
        word.to_owned() + "-hay"
    } else {
        word[1..].to_owned() + "-" + &word[..1] + "ay"
    }
}

Speaking about alternatives, if you use any then starts_with_a_vowel can be written in a single line:

fn starts_with_a_vowel(word: &str) -> bool {
    "aeiou".chars().any(|vowel| word.starts_with(vowel))
}

Note that we use a Char as pattern, not a String. starts_with works with both, but this variant shows our intend to match only a single character.

Ownership

It's not necessary to take ownership of the given String in pig_latinify.


Recursive method to print a descending then ascending integer sequence

Assuming you can use a helper function, you could do this:

  public static void writeSequence(int n) {
    if (n < 1) throw new IllegalArgumentException();
    writeSequenceHelper(n);
  }

  public static void writeSequenceHelper(int n) {
    if (n <= 0) return;
    int m = (n+1) / 2;
    System.out.print(m + " ");
    writeSequenceHelper(n - 2);
    System.out.print(m + " ");
  }

If you can't use a helper function like this to workaround the strange IllegalArgumentException requirement, you could do this (which is similar to your solution, but a little more succinct):

  public static void writeSequence2(int n) {
    if (n < 1) throw new IllegalArgumentException();
    if (n == 1) {
      System.out.print("1");
    } else if (n == 2) {
      System.out.print("1 1");
    } else {
      int m = (n+1) / 2;
      System.out.print(m + " ");
      writeSequence2(n - 2);
      System.out.print(" " + m);
    }
  }


Bootstrap 3.0 Carousel gallery post WordPress

IMO, clean wp code is hard, if not impossible to acchieve. I can tell you, however, that the first thing I'd remove from your functions is the echo $html; statements.

A function is a block of code that does something, and returns that data, to be used anywhere. Your functions don't return anything (apart from the implicit null), but echo a heck of a lot. That could be considered a side-effect. Functions that have side-effects are bad news. Why not replace the echo $html; with a simple return $html; for a start, then call the functions like so:

<?=function_slides();?>

<?= is short for <?php echo, and doesn't require the short_tags to be enabled anyway.
This is only the tip of the ice-berg, though. Your functions contain an awful lot of duplicate statements ($special_gallery = get_post_gallery( $post, false ), for one). Why not pass that as an argument, so you can keep it in scope for all calls, and avoid the overhead of repeating the same function calls?
What's more: the entire function bodies of both function_slides and function_indicators are remarkably similar, and could easily be combined into a single function:

function functions_slide_indicator($post) //specify argument, you forgot this
{
    $special_gallery = get_post_gallery( $post, false );
    $ids = explode( ",", $special_gallery['ids'] );
    $formats = array(
        'indicator' => '

',
        'slide'     => '

%s

%s

'
    );
    $html = array(
        'indicator' => '

',
        'slide'     => '
'
    );
    $link= wp_get_attachment_url($ids[0]);//get data for first id, not in loop
    $attachment_meta = wp_get_attachment($ids[0]);
    $html['slide'] .= sprintf(str_replace('<div class="item"', '<div class="active item"', $formats['slide']), $link, $attachment_meta['title'], $attachment_meta['description']);
    for($i = 1, $j = count($ids);$i<$j;$i++)
    {//start at 1, not 0, so no active class in here
        $link   = wp_get_attachment_url( $ids[$i] );
        $attachment_meta = wp_get_attachment($ids[$i]);
        $html['indicator'] .= sprintf($formats['indicator'], $i);// no need to increment/decrement it here, it'll be the value you need
        $html['slide'] .= sprintf($formats['slide'],$link, $attachment_meta['title'], $attachment_meta['description']);
    }
    $html['indicator'] .= '
';
    $html['slide'] .= '
';//close markup
    return $html;//return array
}

Call this like so:

<?php
    $content = functions_slide_indicator($post);
    echo $content['indicator'];//indicators
    echo $content['slide'];//carousel

Of course, this is only the start, instead of calling that function in the loop, I'd personally go for:

$links = array_map($ids, 'wp_get_attachment_url');

For example. Though this isn't the most performant way to go, at least it looks cleaner, though it could look cleaner still, if you used Objects.


Correct way to extend Bootstrap Modal - lock, unlock

Looks fine to me, except that you failed declare the e variable in the lock/unlock functions. So it's an automatic global, which isn't good.

With a little bit of cleanup:

(function ($) {
  var _original = $.fn.modal.Constructor.prototype.hide;

  function trigger(target, name, relatedTarget) {
    target.trigger($.Event(name, { relatedTarget: relatedTarget }));
  }

  $.extend($.fn.modal.Constructor.prototype, {
    hide: function (_relatedTarget) {
      if (this.isLocked) return;
      return _original.call(this, _relatedTarget);
    },

    lock: function (_relatedTarget) {
      this.isLocked = true;
      trigger(this.$element, 'lock.bs.modal', _relatedTarget);
    },

    unlock: function (_relatedTarget) {
      this.isLocked = false;
      trigger(this.$element, 'unlock.bs.modal', _relatedTarget);
    }
  });
})(jQuery);


Reporting new USB storage devices on Linux and macOS with Python

This script might get the job done, but it is a rather crude and inefficient hack.  Ideally, you should avoid polling every quarter second (or polling at all).  Also, I see no reason to write any files to /tmp.

The ideal way to do it in Linux is to use udev.  If you don't want to write a persistent udev rule, or you don't have root access, you can run /sbin/udevadm monitor --udev --property as a child process, and trigger your test whenever udevadm offers output.  For a smarter script, you can can look for the ACTION=add line and take advantage of the information in the SUBSYSTEM=… and DEVPATH=… lines.  DEVPATH tells you path to the device within /sys.  But, even if you simply trigger your script only when any output appears, that would be a huge improvement over polling four times a second.

import itertools
from subprocess import Popen, PIPE
import re
import sys

KEYVALUE_RE = re.compile(r'([^=]+)=(.*)')

def events(stream):
    """
    Read udev events from the stream, yielding them as dictionaries.
    """
    while True:
        event = dict(
            KEYVALUE_RE.match(line).groups()
            for line in itertools.takewhile(KEYVALUE_RE.match, stream)
        )
        if event:
            yield event

try:
    UDEVADM = ['/sbin/udevadm', 'monitor', '--udev', '--property']
    with Popen(UDEVADM, stdout=PIPE, encoding='UTF-8') as udevadm:
        for event in events(udevadm.stdout):
            if event['ACTION'] == 'add' and event.get('DRIVER') == 'usb-storage':
                print(event)
                break
except KeyboardInterrupt:
    sys.exit(1)

On macOS, you can get similar information by running and monitoring the output of /usr/sbin/diskutil activity, if you are interested in storage devices.  Look for lines starting with ***DiskAppeared.

from subprocess import Popen, PIPE
import sys

try:
    DISKUTIL = ['/usr/sbin/diskutil', 'activity']
    with Popen(DISKUTIL, stdout=PIPE, encoding='UTF-8') as diskutil:
        # Ignore events that describe the present state
        for line in diskutil.stdout:
            if line.startswith('***DAIdle'):
                break
        # Detect the first subsequent "Disk Appeared" event
        for line in diskutil.stdout:
            if line.startswith('***DiskAppeared'):
                print(line)
                break
except KeyboardInterrupt:
    sys.exit(1)

If you are interested in non-storage devices as well, then you could take advantage of the File System Events API, possibly through the MacFSEvents Python package or the cross-platform fswatch program.


You said :

  I never use the variable but only the constructor to see if it doesn't throw an exception

I would ask you, then why did you declare a variable at all ? You could have done :

public boolean isNaN(final String string) {
    try {
       new BigDecimal(string);
    } catch (final Exception e) {
        return true;
    }
    return false;
}

When you don't need a variable, don't declare it.

You should not catch Exception because it's too generic. What do you really want ? The constructor throw NumberFormatException if the argument is not valid, the better option would be to catch that one instead.


Split string into 160-character chunks while adding text to each part

Some notes:

Is your code inside a module or a class, I guess? You can include it in the question.
As a general rule, favour the user of affirmative statements (if instead of unless).
If you spend enough time with a pencil and a paper, maybe you'd get to a nice formula get_total_parts(message_size, sms_size, parts_message_min_size), but it's not trivial, that's for sure. A pre-computing of the max_size (along with some extra info you'll need) is a bit tedious to write but fast. For example, what's the maximum size if you have a total count with exactly 3 digits (100-999)? (SMS_SIZE - PARTS_MSG_MIN_SIZE - 2) * 9 + (SMS_SIZE - PARTS_MSG_MIN_SIZE - 3) * 90 + (SMS_SIZE - PARTS_MSG_MIN_SIZE - 4) * 900. You get the idea.

I'd write:

module SMS
  SMS_LENGTH = 160

  PARTS_MESSAGE = " - Part %{n} of %{total}"

  SPLIT_INFO = (1..70).map do |ndigits|
    base_size = (PARTS_MESSAGE % {n: "1", total: "1"}).size
    parts_per_digit = (0...ndigits).map do |n|
      (SMS_LENGTH - base_size - (ndigits + n - 1)) * (9 * (10 ** n))
    end
    {
      max_size: parts_per_digit.reduce(0, :+),
      size_of_first_parts: parts_per_digit[0...-1].reduce(0, :+),
      min_parts: 10**(ndigits - 1) - 1,
      msgsize_for_last_parts: (SMS_LENGTH - base_size - 2 * (ndigits - 1))
    }
  end

  def self.get_total_parts_for_long_message(text)
    info = SPLIT_INFO.detect { |h| text.size <= h[:max_size] } or
      raise ValueError("Message text too large")
    info[:size_of_first_parts] +
      Rational(text.size - info[:min_size], info[:msgsize_for_last_parts]).ceil
  end

  def self.send_sms_message(text, to, from)
    if text.length <= SMS_LENGTH
      deliver_message_via_carrier(text, to, from)
    else
      total_parts = get_total_parts_for_long_message(text)
      idx = 0

      (1..total_parts).each do |part_index|
        split_message = PARTS_MESSAGE % {n: part_index, total: total_parts}
        user_message_size = SMS_LENGTH - split_message.size
        message_text = text[idx, SMS_LENGTH - user_message_size]
        deliver_message_via_carrier(message_text + split_message, to, from)
        idx += user_message_size
      end
    end
  end

  def self.deliver_message_via_carrier(text, to, from)
    puts("Sending #{from} -> #{to}: #{text} - #{text.size} bytes")
  end
end


Compare and match results in two two-dimensional arrays in Excel VBA

Couple notes -

Your comments aren't needed. Comments - "code tell you how, comments tell you why". The code should speak for itself, if it needs a comment, it might need to be made more clear. If not, the comment should describe why you're doing something rather than how you're doing it. Here are a few reasons to avoid comments all together.
It's good practice to indent all of your code that way Labels will stick out as obvious.
Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.

Variable names - give your variables meaningful names:

arr1 - this is the first array for comparison, why not describe what it is? Same for arr2.
What are the rowX, colX, ax, arr1x, arr2y? The capitalization isn't consistent - Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names.

Creating and populating your arrays. I don't think you need the lastRow function. If you do, I'd use Private Function LastRow(ByVal targetRange as Range) as Long and just ensure you explicitly pass the range with the sheet qualifier.

If so, you can eliminate some variables as well

Dim arr1() As Variant
Dim arr2() As Variant
Dim lastRow As Long
lastRow = x 'target for firstarray
ReDim arr1(1 To lastRow, 1 To 4) As Variant 'dynamically sizes arr1 array
lastRow = x 'target for firstarray
ReDim arr2(1 To lastRow, 1 To 2) As Variant 'dynamically sizes arr2 array

As far as reusing the lastRow variables, just use Ubound(targetArray) instead.

Dim i As Long

For i = 1 To UBound(firstArray)
    firstArray(i, 1) = Cells(i, 1)
    firstArray(i, 2) = Cells(i, 2)
    firstArray(i, 3) = Cells(i, 3)
    secondarray(i, 1) = Sheet2.Cells(i, 1)
    secondarray(i, 2) = Sheet2.Cells(1, 2)
Next i

I'm not sure what you're doing here - populating the array? The other answer covers this - just populate it ater you dim it undimensioned.

For aX = 1 To arr1x
    For rowX = 1 To arr2y
        If arr1(aX, 3) = arr2(rowX, 1) Then
            arr1(aX, 4) = arr2(rowX, 2)
            rowX = arr2y 'helps to exit array earlier when a match is found
        End If
    Next rowX
Next aX

resetting rowX = arr2y is not the proper way to exit the loop:

If arr1(aX, 3) = arr2(rowX, 1) Then
   arr1(aX, 4) = arr2(rowX, 2)
   Exit For
End If

Also, why are you using aX as a byte for this? I don't understand that.

You can simplify the loops populating the arrays, combine everything into 1 loop and avoid looping 4 times. That should speed it up a bit. And I would really urge you to get rid of the arr1x and arr2y in favor or Ubound.


Converting from strings to byte arrays with LINQ in C#

Edit: corrected an issue with leading zero bytes in the result.

I'll focus on the GetOctalBytes method in this review.

Also, for the explanation I assume that the string is processed right-to-left (reverse order) and similarily, the resulting byte array starts with the lowest byte at index 0. Those assumptions will be represented / corrected in the final code.

For octal strings, a group of 8 characters forms a group of up to 3 result bytes. So for each complete group, take 3 bytes. The following table shows important properties for different character counts of a group.

(in-group character count) (bits count) (bytes needed) (affected byte indices in group)
1                           3           1              0
2                           6           1              0
3                           9           2              0, 1
4                          12           2                 1
5                          15           2                 1
6                          18           3                 1, 2
7                          21           3                    2
8                          24           3                    2

The total bytes needed can be calculated as (octal.Length * 3 + 7) / 8. However, for length 3 or 6, the actually needed byte count can be lower, if the character value needs only 2 or 1 of its bits. So for these cases, the number of bytes can be lowered. Since a new group starts every 8 characters and each group needs 3 bytes, the starting index of the current byte group in the result array can be calculated as (character_index / 8) * 3. The affected in-group indices are calculated from the remainder:

remainder = (character_index % 8);
if (remainder < 3) group-index 0 affected
if (remainder >= 2 && remainder < 6) group-index 1 affected
if (remainder >= 5) group-index 2 affected

In order to avoid leading zero bytes, the character value has to be considered additionally for the second and third byte.

I hope these explanations are enough introduction for the following code suggestion:

Note: I ditched the linq solution in favor of a more readable solution with less array-recreation.

public static byte[] GetOctalBytes(this string octal, bool preTrimmed = false)
{
    if (!preTrimmed)
    {
        octal = octal.Trim();
        if (octal.StartsWith("0o", StringComparison.OrdinalIgnoreCase) || octal.StartsWith("8#"))
            octal = octal.Substring(2);
    }

    octal = octal.TrimStart('0');
    if (octal.Length == 0)
        return new byte[] { 0 };

    var arrayLength = (octal.Length * 3 + 7) / 8;
    var inGroup = (octal.Length % 8);
    if ((inGroup == 3 && octal[0] < '4') ||
        (inGroup == 6 && octal[0] < '2'))
    {
        --arrayLength;
    }

    var result = new byte[arrayLength];

    for (int i = 0; i < octal.Length; i++)
    {
        var baseIndex = (i / 8) * 3;
        var shift = (i % 8) * 3;
        var valueInGroup = (octal[octal.Length - i - 1] - '0') << shift;

        result[result.Length - baseIndex - 1] |= (byte)(valueInGroup & 0xff);
        if (valueInGroup > 0xff)
            result[result.Length - baseIndex - 2] |= (byte)((valueInGroup >> 8) & 0xff);
        if (valueInGroup > 0xffff)
            result[result.Length - baseIndex - 3] |= (byte)((valueInGroup >> 16) & 0xff);
    }

    return result;
}


Long SQL query with much duplication between two halves of a UNION

Your SQL Fiddle and the question have inconsistent column names: the fiddle has id_activity_package, while the code in this question has activity_package_id.  I'll consider the fiddle as supplementary information, and treat the code in the question as authoritative.

The two halves of the UNION are nearly identical, with the exception of the second INNER JOIN.  Let's analyze it one step at a time.

In the first half of the UNION, you join with APA_T, which is…

SELECT DISTINCT apa.district AS district,
    (SELECT s1.activity_package_id
        FROM tbl_activity_package_address s1
        WHERE apa.district = s1.district
        ORDER BY s1.id DESC
        LIMIT 1
    ) AS idActivityPackage
    FROM tbl_activity_package_address apa
    ORDER BY apa.district

The DISTINCT there is superfluous, since the innermost SELECT is guaranteed to return at most one row per district.

As I read it, APA_T is a subquery that lists the most recently added activity_package_id for each district.  I think it's worth creating a view for clarity.

CREATE VIEW latest_activity_package_address AS
SELECT *
    FROM tbl_activity_package_address
    WHERE id IN (
        SELECT MAX(id)
            FROM tbl_activity_package_address AS latest_apa
            GROUP BY district
    );

Then, the first half of the UNION becomes:

SELECT GROUP_CONCAT(district ORDER BY district), t.name
    FROM tbl_activity AS t
        INNER JOIN tbl_activity_package AS ap
            ON t.id = ap.activity_id
        INNER JOIN latest_activity_package_address AS apa
            ON ap.id = apa.activity_package_id
    WHERE (ap.publication_date <= CURDATE())
        AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) >= CURDATE())
    GROUP BY t.name
    ORDER BY apa.district

I've copied the ORDER BY clause into the GROUP_CONCAT(), where I think it belongs.
Next, I'd like to point out that LIMIT 6,6 will produce non-deterministic results, since there is no ORDER BY clause on the UNION query.  You've put an ORDER BY on each half of the UNION, but that doesn't guarantee that the result will be ordered the same way.
Surprisingly, I haven't found a way to reduce duplication between the two halves of the UNION.  However, there is now a nice parallelism which may be more aesthetically pleasing.  You don't need to select new table aliases for the second half; they aren't in the same scope as the first half.

SELECT GROUP_CONCAT(district ORDER BY district), t.name
    FROM tbl_activity AS t
        INNER JOIN tbl_activity_package AS ap
            ON t.id = ap.activity_id
        INNER JOIN latest_activity_package_address AS apa
            ON ap.id = apa.activity_package_id
    WHERE (ap.publication_date <= CURDATE())
        AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) >= CURDATE())
    GROUP BY t.name
    ORDER BY apa.district
UNION DISTINCT
SELECT GROUP_CONCAT(district ORDER BY district), t.name
    FROM tbl_activity AS t
        INNER JOIN tbl_activity_package AS ap
            ON t.id = ap.activity_id
        INNER JOIN tbl_activity_package_address AS apa
            ON ap.id = apa.activity_package_id
    WHERE (ap.publication_date <= CURDATE())
        AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) >= CURDATE())
    GROUP BY t.name
    ORDER BY apa.district


Here you have some general thoughts:

First of all, cache jQuery elements (var $this = $(this); instead of multiple executions of $(this)). http://jsfiddle.net/tomalec/pXPdS/1/
You can also chain jQuery methods, it simplifies codes, and helps with above.
To reduce amount of code you can use toggleClass instead of addClass removeClass.http://jsfiddle.net/tomalec/pXPdS/2/
Instead of selecting $('#rankDrag') in start callback you can use reference given in arguments ui.helper
http://jsfiddle.net/tomalec/pXPdS/3/
To get id of empty/not empty holder ids, in my opinion, .map is more readable than .each. Moreover, you can move that function outside rearrange to avoid re-declaring it every time.

function getTruncatedId(index, element){
    return element.id.substring(14);
}

function rearrange(dropid) {
    //..
    emptyHolders = holders.filter('.holder-empty').map(getTruncatedId);
    isRanked = holders.filter(':not(.holder-empty)').map(getTruncatedId);
    //..
}

http://jsfiddle.net/tomalec/pXPdS/4/
Pass dropped element to rearrange, so you will not have to traverse through DOM again:

rearrange( $(this).attr('id') );//dropId = $(this).attr('id');
//..
isEmpty = $('#'+dropId).hasClass('holder-empty');

http://jsfiddle.net/tomalec/pXPdS/5/


Generic Pickle-Aware Super-Class for Mixing Classes with and without __slots__ in Python

A few of trivial points:

getattr(cls, '__slots__', []) would be better as getattr(..., ()) - tuples are immutable so are normally cached by the implementation.
set(slot for slots in all_slots for slot in slots) would be better as {slot for slots in all_slots for slot in slots}
It might be better to do

try:
    statedict = vars(self).copy()
except TypeError:
    statedict = {}


Using session wrapper for accessing session data

Do not use Hungarian notation for constants, keep it in PascalCase. If you like to differentiate the names from the properties you can name in form of {PropertyName}Key, like UserIdKey.
Do prefer .net aliases over the full type name, like Int32 -> int, String -> string.
Avoid repetition of word, like User.UserId and SessionHelper.GetSession.... Unless you are worried about mixed up with the foreign key in your DTO, but it is not the case here.
UserModel (if it is User, that is fine)(you weren't really consistent with the code) should be renamed to CurrentUser :

// which one makes more sense ?
UserModel.Name = userName;
CurrentUser.Name = userName;

HttpContext.Current.Session shows up quite frequently in SessionHelper, you could use a property to shorten it :

private static HttpSessionState CurrentSession
{
    get { return HttpContext.Current.Session; }
}

The SessionHelper class :

public class SessionHelper
{
    private static HttpSessionState Session
    {
        get { return HttpContext.Current.Session; }
    }

    public void SaveValue(string key, string value)
    {
        Session.Add(key, value);
    }
    public static string GetStringValue(string key)
    {
        if (Session == null || Session[key] == null)
            return null;

        return HttpContext.Current.Session[key].ToString();
    }
    public static int GetIntValue(string key)
    {
        if (Session == null || Session[key] == null)
            return 0;

        int result;
        return int.TryParse(Session[key].ToString(), out result) ? result : 0;
    }
}

If you can get your hand on C# 6, consider this version :

public class SessionHelper_c6
{
    private static HttpSessionState Session => HttpContext.Current.Session;

    public void SaveValue(string key, string value)
    {
        Session.Add(key, value);
    }
    public static string GetStringValue(string key)
    {
        return Session?[key]?.ToString() ?? null;
    }
    public static int GetIntValue(string key)
    {
        var value = Session?[key]?.ToString() ?? null;
        int result;
        return value != null && int.TryParse(value, out result) ? result : 0;
    }
}


IMHO string parsing is not a good idea for embedded applications. If you really care for speed, it would be better to use some binary format w/o dynamic length numbers etc.

I suggest you cannot change protocol due to legacy code/hardware. Then you could try turning your parser into finite automate. You just make a table (first index for current state, second index for a class of read char, value is new state and function to call) and then (state, f) = transition[state][class_of[*s++]]; f(); Files, generated with YACC for some simple grammars, could be helpful.

If you need just some minor modifications to your code, here you are.
First you read data into your buffer. All you have to do then is just some calculations with Horner scheme:

x_result = ((buffer[5]-'0')*10+buffer[6]-'0')*10+... ;
if (buffer[4] == '-') x_result =- x_result;

String constructor, substring method and other string operations are quite costly.


FactoryPattern without If-else construct

This is a good example for demonstrating that you can implement factory pattern without conditional statements. Of course, no piece of code is good for every imaginable requirement.

In real world cases factory pattern usually needed because some aspect of the object building is not trivial. One such case is when you do not have the concrete classes at compile time. e.g. when you are a library/framework developer and the user will have the concrete classes. In that case you would want to externalize the class names to the program configuration. This program requires that you have the SubmitButton.class et al at compile time, and is  dependent of those concrete classes.


Caret color and movement animation in Swing

Hey Not 100% sure what's up with the babySteps function

  "the stepsColor(int from, int to, int max) provide the maximum addition to add it to > from to be to but the return will be less than max"

Is a little confusing anyway I refactored

public static int babySteps(int from, int to, int max) {
    int j = 0;
    int currentPoint = to;
    for (;j <= max; j++) {
        if (!from >= currentPoint || !from <= currentPoint) {
            return j;
        }
    }
}

Can you send me the GitHub link so I can look into the code base thanks