Changing the id field to an _id field for the lowest tweet id

Three parts to your questions: 1) find lowest tweet ID and 2) assign id: to _id 3) can (1) and (2) be done without iterating over the list.

To answer (3) first, (1) definitely can be done without iteration, but I am unaware of how to do (2) without iteration.

(1) Lowest Tweet ID
The sort function is great for this. This question has more on sorting. To create a new list with the lowest id in the first position:

results = sorted(search_results, key=lambda x: x.id)

To do the same thing replacing the list:

search_results.sort(search_results, key=lambda x: x.id)

Simply access the "0"th result in the list and you have your lowest tweet id.

2) Assign id: to _id

Perhaps someone can answer this better, but the best way I know of is how you've done it:

for tweet in search_results:
    tweet['_id'] = tweet.pop('id')

Your final code would look something like:

search_result = #search result from Twitter API
results = sorted(search_results, key=lambda x: x.id)
min_id = results[0]['id']
for tweet in search_results:
    tweet['_id'] = tweet.pop('id')


Terminating a C loop when maximum hardware limit reached

Use unsigned rather than signed because once there is overflow the effect is undefined.
Whereas with unsigned there is no overflow but modulo arithmetic plus it produces an additional value.

cat >fib2.c <<EOF
// Fibinocci numbers
#include <stdio.h>
int main(){
   for (unsigned long long ii=1, fib=1, prev=0, temp;
         fib>=prev;  // Wrap indicates max value per implementation
         ii++, temp=fib, fib+=prev, prev=temp)
      printf("%llu: %llu\n", ii, fib);
   }
EOF
gcc -std=c99 -ofib2 fib2.c
./fib2


Removing duplicates from unsorted LinkedList

Yes, this looks \$O(n^2)\$: when all elements are unique,
the program will compare all elements with all other elements.

A better solution will be to use a Set to keep track of the already seen items.
You will still have to iterate over all items,
but you won't have to compare to all other elements,
but simply do a lookup in the Set,
which in case of a HashSet will be \$O(1)\$ complexity.
Of course, when all elements are unique,
then this method will use twice as much memory as your original.
That's a trade-off you'll have to consider.

Unfortunately you didn't provide the implementation of LinkedListNode so it's not easy to play with this code.
But looking at it I'm wondering if it correctly removes all duplicates,
for example will it turn 1->2->2->2->2->3 into 1->2->3.
(Maybe it does, a bit hard to decipher, but I suggest to do a quick test.
And maybe next time include enough code so that reviewers can test run easily.)

UPDATE

As you remarked in your last comment,
another way, without using a buffer / Set is to sort the list first,
and remove the duplicates after.
That would have \$O(n\log n)\$ complexity.
However, keep in mind that the elements will be reordered with that approach (if they were not ordered to begin with).
Depending on your use case, that may be perfectly acceptable, of course.


That seems good. I really like the callback mechanism to do whatever we want with the marked positions and not one specific action. That makes for a generic tool; good design. I don't have much to say to improve the algorithm itself, but here are my two cents anyway:

Do you have a using std::swap; anywhere? Otherwise, I don't think that the unqualified calls to swap will work as intended.
While auto is a great tool, there are some times when I don't think that it adds to readability. For example, it took me more time that I would have wanted to see that swap_xy was a bool. That's prone to debate anyway, but I don't think that you will ever replace it by another type and an explicit bool would have highlighted the logic. That's still subjective though.
Still pretty subjective, but instead of this:

auto pen = p0;
while (pen.x != p1.x) {
    // ...
    pen.x += step_x;
}

I would have used a for loop since you explicitly have an initialization, a condition and a step. And everyone uses the same variable pen, which isn't used after the loop.

for (auto pen = p0; pen.x != p1.x; pen.x += step_x) {
    // ...
}

Nitpicking again, but I would have factored the multiplication by 2 out of the std::abs in the computation of error:

auto error = 2 * std::abs(d.y*(pen.x - p0.x) - d.x*(pen.y - p0.y));

By the way, this factorization highlights something else: you actually do not need to keep the multiplication by 2 in error; you only need it for the comparison:

auto error = std::abs(d.y*(pen.x - p0.x) - d.x*(pen.y - p0.y));
while (2 * error > dx_abs) {
    pen.y += step_y;
    error -= dx_abs;
    mark(pen);
    skip = true;
}

Not that it makes a big difference, but it still makes the code a little bit terser.


Game of Life Neighbour count optimization

There are several style issues with this code. Most notably:

Use camelCase for method names
Use camelCase for variable names
Put spaces around operators, for example:

i = i1 instead of i=i1
yCoordinate + 1 == xLen instead of yCoordinate+1==xLen
... and so on

j1, j2, ... are poor variable names

To simplify this code, a couple of ideas:

Use an enum to represent neighbors: North, NorthEast, East, SouthEast, ...

Create custom fields dx and dy to represent the direction offset

Iterate over Neighbor.values(), for each item perform this check:

Calculate the neighbor position using current position + the neighbor's dx and dy
Check if the position is on the grid, for example with a isValid(Position pos, Neighbor neighbor) method
Check if the position is alive, for example with a isAlive(Position pos, Neighbor neighbor) method
If both the above are true, increment the count

To get you started, here's an example enum:

enum Neighbor {
    North(0, 1),
    NorthEast(1, 1),
    East(1, 0);

    private final int dx;
    private final int dy;

    Neighbor(int dx, int dy) {
        this.dx = dx;
        this.dy = dy;
    }
}


From my experiences in MUDs and text games, I think you would do well to create a class/module that handles each command then inject them into your processor (even manually). It will help a lot with the maintainability but also isolating commands.

import {registerLook} from "./commands/look";
import {registerGo} from "./commands/go";

// Build up a hash of commands. With a MUD style, you would register the shorten
// versions also (so look registers as "l", "lo", "loo", and "look") but removes
// entries that would have a conflict (so "left" would remove the "l" for look but
// register "le", "lef", and "left".
let commands = {};

registerLook(commands);
registerGo(commands);

// Then when you are running the command.
if (command.action in commands
{
  commands[command.action].run(command, receiver);
}
else
{
  // Show error of missing command
}

You could go further with the SOLID implementation by having the commands injected from the top-level, but the main reason for doing this is to let you have the complex logic for the commands moved into a separate file that does one thing only (Single Responsibility Principle) while treating the switch of the commands against an interface (functions inserted into the hash by a register).

Ideally, having a DI figure out the commands would be nice, but I haven't found a good DI system for Typescript I like. (You could also scan the commands directory and inject the commands that way.)

It also lets you nest the commands if you need to. So if you have look at and look into, you could have commands/look.ts break apart the first word and then pass it into look commands (commands/look/at.ts) to further isolate it. Or whatever makes sense.


Finding words of different lengths given six letters

Before I get started I have to say: Thank you for coming here. Mess of Java For Loops is almost an understatement. Now, let's get working, shall we?

In the below answer I assume that sortedDictionary and anagram_words is both of type List<String>. I also assume that anagramCharacters is of type char[].

Code duplication

Start by identifying which parts of the code looks similar, and create some methods to reduce code duplication

Code like this is repeated several times:

if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]))
     anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]);

This can be extracted to a method: addWord() (Note that the below method is not optimized for what it is doing, it is mainly so that you are able to understand what it does better).

private void addWord(char... chars) {
    String string = "";
    for (char ch : chars) string += ch; // Create a strings of the chars
    if (sortedDictionary.contains(string))
        anagram_words.add(string);
}

So instead of repeatedly writing

if (sortedDictionary.contains(....)) anagram_words.add(...)

we simply call a method:

addWord(anagramCharacters[l1], anagramCharacters[l2], anagramCharacters[l3]);

Variables with index

Whenever you find yourself using variable names that contains numbered values, such as l1, l2, l3, l4, STOP and think "Would an array be useful here?". Creating an int[] letters is far more flexible than using the multiple variables l1, l2, l3

If all the l-variables are instead inside the letters array, some things can be simplified further at the moment:

This:

if(l4 != l1 && l4 != l2 && l4 != l3)

would become

if(letters[3] != letters[0] && letters[3] != letters[1] && letters[3] != letters[2])

This:

if(letters[3] != letters[0] && letters[3] != letters[1] && letters[3] != letters[2])

can become a method

private boolean lastLetterDifferent(int index) {
    for (int i = 0; i < index; i++) {
        if (letters[i] == letters[index]) return false;
    }
    return true;
}

The previous call we made to addWord only needs to contain the number of indexes to check instead of each and every char.

private void addWord(int numberOfChars) {
    String string = "";
    for (int i = 0; i < numberOfChars; i++) string += anagramCharacters[letters[i]]; // Create a strings of the chars
    if (sortedDictionary.contains(string))
        anagram_words.add(string);
}

So now that's done, what remains now?

After doing the above refactoring, here is what's left:

for(letters[0] = 0; letters[0] < 6; letters[0]++){
    for(letters[1] = 0; letters[1] < 6; letters[1]++) {
        if(lastLetterDifferent(1)) {
            for(letters[2] = 0; letters[2] < 6; letters[2]++) {
                if(letters[2] != letters[0] && letters[2] != letters[1]) {
                    addWord(3);
                    for(letters[3] = 0; letters[3] < 6; letters[3]++) {
                        if (lastLetterDifferent(3)) {
                            addWord(4);
                            for(letters[4] = 0; letters[4] < 6; letters[4]++){
                                if (lastLetterDifferent(4)) {
                                    addWord(5);
                                    for(letters[5] = 0; letters[5] < 6; letters[5]++){
                                        if (lastLetterDifferent(5)) {
                                            addWord(6);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

That looks a lot cleaner, but how flexible is this? What if we want to use an 8-letter word, or a 12-letter word? NO, you should NOT continue this pattern and add more for-loops! So what other alternative is there? Recursive methods, my friend!

To do this, we need a couple of helper methods. You mentioned the number 720. It just so happens that 720 equals 6 factorial. So let's create a factorial method.

public static int fact(int x) {
    if (x < 0) throw new IllegalArgumentException("x cannot be negative: " + x);
    if (x <= 1) return 1;
    return x * fact(x - 1);
}

This is a recursive because it calls itself on some occasions. More precisely, when x >= 2. Recursive methods are fun, so let's create another one!

public static <E> List<E> permutationI(List<E> values, int iteration) {
    if (values.size() == 0)
        return new ArrayList<E>();
    List<E> list = new ArrayList<E>(values.size());
    int divisor = fact(values.size() - 1);
    int pos = iteration / divisor; // Pick an index depending on the iteration value
    list.add(values.remove((int)pos)); // Remove from one list and add to another
    list.addAll(permutationI(values, iteration % divisor)); // Call method recursively to get all the elements
    return list;
}

Every time this method is called, it picks an index in the values list depending on the value of iteration. Then it gets the element for that index from the values list, removes that element from the values list and adds it to the list called list (which will be the methods result. Then this method calls itself to add all the remaining elements for the current iteration.

Putting it together:

We will need one more utility method to convert from a List of characters to a String (again, this method is not fully optimized. There are plenty of faster ways to do this).

public String charListToString(List<Character> list) {
    String result = "";
    for (Character ch : list) {
        result += ch;
    }
    return result;
}

And now, the final touch to use all this recursive-ness:

List<Character> indexes = new ArrayList<Character>();
for (char ch : anagramCharacters)
    indexes.add(ch); // Build a list of the characters in our original word
int totalPermutations = fact(indexes.size());
for (int i = 0; i < totalPermutations; i++) {
    // Since permutationI modifies the list we send, we copy the list
    List<Character> newList = permutationI(new ArrayList<Character>(indexes), i);
    addWord(charListToString(newList)); // Call our method to add the word to the result list
}


This is going to sound a bit harsh, but I don't see a purpose to this function.  It offers a tiny bit of a shortcut, but it cripples a lot of functionality to do so.

I'm not very familiar with MySQLi (PDO seems to have a lot more advantages than MySQLi and only a few, insignificant disadvantages -- though PDO does not have a procedural API like MySQLi does), but it seems like the only thing this function ever returns is the number of rows?  So this is a glorified num_rows() function?

debugging output should be removed, and errors should either be returned or thrown as exception.  Directly printing errors is bad since the calling code then doesn't know that an error occurred.
$variables is a blatant anti pattern.  If you want an array, use an array.  What if one of your bindings needs to have a comma in it?
What if numVars is >= 6? Doesn't seem very flexible.

If you decide to keep this function, use call_user_func_array to handle a dynamic amount of parameters.

Supporting numRows and numRows would probably come back to be a pain.  I'd stick with one or the other.

Or, better yet, use constants like MANIPULATE_OP_NUMROWS (like built in functions do).

manipulate is a vague name.  Manipulate what?  And manipulate how?
(int)strlen($type); strlen already returns an int.  (And even if it didn't, you're using loose comparisons anyway.)


Smooth sidebar toggle animation with vuejs and tailwind

You should use transition instead of animation and target the width property :
 .slide-enter-active, .slide-leave-active {
  transition: width 1s;
}
.slide-enter, .slide-leave-to{
  width:0;
}

LIVE DEMO
we could consider a transition as particular case of animation, the transition is applied when an element property changes (transition), but animation could be applied on any element infinitely or for some duration, you could watch the two first free videos on vue mastery that explain that clearly


I would use the Alternate Fire Method but I would convert the canShoot field to a CanShoot property.  Also startPosition is only used within the then block, so I would move its definition there as well.  Example:

public bool CanShoot => reloadCountDown <= 0F;

private void Fire ()
{
    if (!Input.GetKey(KeyCode.Space))
    {
        return;
    }

    if (CanShoot)
    {
        Vector3 startPosition = transform.position + new Vector3(0 ,(renderer.bounds.size.y * 0.5f), 0);
        GameObject playerProjectile = Instantiate(playerProjectilePrefab, startPosition, Quaternion.identity) as GameObject;
        playerProjectile.rigidbody2D.velocity = new Vector3 (0, playerProjectileSpeed, 0);
        reloadCountDown = reloadTime;
    }
    else
    {
        reloadCountDown -= Time.deltaTime;
    }
}

Your code looks more Java-ish than C#.  Since you've tagged it with C#, I will focus my comments on that.  However, I am not familiar with Unity3d and don't know how it will like some syntax changes.

Braces on a new line

With C#, we prefer braces on their own line.  The one exception would be a one-liner such as:

if (!Input.GetKey(KeyCode.Space)) { return; }

Fields should never be public

Your first 3 class-level variables are called fields.  They should either be properties or constants.  For example, will reloadTime always be 0.2f?  If so, it can be a constant.  If not, and if you want it to be exposed publicly, then you should make it a property.  If reloadTime does not need to be public, then it can remain a field.

Method, Property, & Constant Names are CamelCase

Fields & Parameter Names are PascalCase

This doesn't YET apply to your original code, but let's combine it with the previous section.  Your declarations could now look like:

public const float ReloadTime = 0.2F;
public GameObject PlayerProjectilePrefab { get; private set; }
public const float PlayerProjectileSpeed = 10F;

private bool CanShoot => reloadCountDown <= 0.F;
private float reloadCountDown;

But I am just guessing as to the private setters.  Use what your app requires.

Numeric Type Designators should be Uppercase

Change the f to F.  Really doesn't affect your code here but the reason for this guideline is you ever use long where a lowercase l could be confused as a numeric 1, but a capital L would not.

Always declare accessibility modifier

Instead of simply void Fire() use private void Fire().  When I see a private missing, I assume a newbie coder has forgotten it, which leads me to wonder what else he or she has forgotten.

Variable declaration and scoping

As mentioned at the very top with startPosition, you should limit the scope of a variable to where you need it.  In my example, startPosition was placed inside the then block and declared immediately before the one place where it was referenced.  Someone reading your code doesn't have to remember where it was defined, or worry about it afterwards.


Extracting large tar.bz2 folders in parallel

Re-purposing the argument list this way is not idiomatic Bash, and it took me some time to realise that (firstly) the supplied arguments are ignored and replaced with a list from filesystem and that (secondly) those arguments are replaced with the process IDs of the child tar processes.  It might be better to use distinctly-named array variables instead.

There's very little point in passing the -v argument to tar and then redirecting it to /dev/null.  If you don't pass -v, then tar will quietly get on with its job:

    tar -xjf "$FILE" -C /path/to/folders &

Why is maxproc set to 3?  Is that an empirical value based on your observed disk (and filesystem) throughput?  If so, provide a means to overwrite it (e.g. allow it to be passed as an environment variable).

If you want to spawn one child for each processor (core) on your system, you might choose maxproc=$(getconf _NPROCESSORS_ONLN); I'll leave it as an exercise to think of other possible defaults.

The wait command here waits for a specific process to exit.  If job 2 finishes before job 1, then the script won't start a new process to replace it until after job 1 completes, resulting in lower overall utilisation, especially if the jobs are of unequal size or proceeding at unequal rates.

Instead, replacing wait "$1" with wait -n will wait for any one child process to exit.  This is more likely to be what we want.

The script always returns a success value, even if one or more extractions fail (e.g. due to a full filesystem).  It's possible to remember that an error occurred:

status=0
for FILE in ...
do
    ...
    wait -n || status=1
done

wait || status=1
exit $status

Consider using an existing implementation of parallel or xjobs rather than reinventing the wheel.  That turns this script into a simple one-liner.


Avoid calling init method on each return method

The first thing I don't like much is that you walk the callstack to find the caller. It's faster and more robust to find the assembly via a type that's part of that assembly. Since your methods are called on a controller, you could use controller.GetType().Assembly to find it.

The next issue is that you only store a single value and you do so in a non threadsafe fashion. I'd use a threadsafe dictionary that maps an assembly to the data instead.

Omitting details like argument validation, my code would look similar to the following:

public class ModuleInformation
{
    private static readonly ConditionalWeakTable<Assembly, ModuleInformation> _dict = new ConditionalWeakTable<Assembly, ModuleInformation>();

    private static ModuleInformation LoadInfo(Assembly assembly)
    {
        // replace with code to load the module information
        return new ModuleInformation();
    }

    public static ModuleInformation Get(Assembly assembly)
    {
        return _dict.GetValue(assembly, LoadInfo);
    }

    public string Id { get; private set; }
}

public static class ModuleInformationExtensions
{
    public static ModuleInformation GetModuleInformation(this Controller controller)
    {
        return ModuleInformation.Get(controller.GetType().Assembly);
    }

    public static string GetAreaName(this Controller controller)
    {
        return controller.GetModuleInformation().Id;
    }
}

Another dubious part of your code is:

var moduleService = new ModulesService();
_module = moduleService.GetByNameSpace(moduleNamespace);

Depending on the implementation of the ModulesService it might be a good idea to pass it in via dependency injection. Database access from static methods is usually a bad idea since the database should be injected. This is incompatible with your static design, so you might want to switch to instances which are then injected into the controllers.


Bash script, "flash cards" for Spanish vocabulary

I haven't used or reviewed bash script for ever, so I'm just going to give a few comments:

Your script reads nicely, and even though I don't know spanish, there are some comments explaining the vital parts.
I think the script could benefit from a little more spacing, so that the various sections stood out a little more. The top half is better than the bottom half.
The variable names are good and helpful
However there are two code smells that I see:

Each time you set vocab_item you're re-reading the file. So at end of script you've read the file \$N\$ times, where \$N\$ is the number of lines
Each time you set english and spanish to trigger a new call to cut.

Reading the main file once

After a little searching I found this thread on SO:Looping through the content of a file in bash. The accepted answers uses the following construct:

while read p; do
  echo $p
done <peptides.txt

This would allow for reading the file just once, but you'll need to change a little of your logic related to counting the correct number of answers.

Splitting a line into an array

Another search, and another SO thread: Split string into an array in bash. This one to avoid the calls to cut.

IFS=', ' read -r -a parts <<< "$vocab_item"
english="${parts[0]}"
spanish="${parts[1]}"

Hope this helps to some extent.


Billing for work using an hourly, dual, or flat rate

OO or not

The first thing to do is decide whether or not you want an object-oriented design for this problem. From the requirements you've described, there's a very simple solution that doesn't need any real design work at all:

public static int CalculateFee(int flatRate, int hourlyRate, int hours)
{
    return flatRate + hourlyRate*hours;
}

(The two parts of a "dual rate" would just be summed before being passed in, and either flatRate or hourlyRate could be 0)

You can then carry around those variables however is most convenient for you. For example maybe you'd put the rates together into some property-bag class:

public class Rate
{
    public int Hourly { get; set; }
    public int Flat { get; set; }
}

Or maybe you'd just pass them around as integers. Likewise whether CalculateFee was a public method somewhere or a private method, or even in-lined in another method, is really just a choice about how to organize things to read most clearly, rather than about design.

I think the above should be your default starting point. Building a design means making decisions, and every decision is a potential wrong decision, which becomes technical debt. So you should never build more or earlier than you're driven to by your requirements.

But there are some reasons you may immediately want a heavier design than this. For example:

You know- or think it's very likely- that you'll have to add new types of rates in addition to flat, dual and hourly.
There may be more functionality that you need associated with each rate, like wanting to be able to write a descriptive string ("A rate of 30$ per hour").
You want to be able to replace a rate with a test double for unit testing (I'm not sure that's really appropriate with these classes, it's hard to know without seeing how they're used)

Polymorphism

I won't write out a full OO version because Dmitry Nogin's answer already demonstrates this really well.

But to distill out the key point from that, if you're going to use an OO solution, you want to use polymorphism. If you're doing code like:

IThing thing;

if(thing is ThingTypeA)
{
    CalculationA(thing);
}
else if(thing is ThingTypeB)
{
    CalculationB(thing);
}
else if...

Then that's a pretty good sign that you should instead have a Calculation method on IThing, with a different implementation for ThingTypeA and ThingTypeB. That's a core part of OO design, and one that's easy to apply here (as Dmitry's answer shows)

Note that this also lets you encapsulate your data- those integer fields can be private to the Rate implementations. Your classes aren't just bags to hold data for anyone to read, they provide useful behaviour.


Signal simulation through Python scripts using shared memory for testing a C application

It is short and to the point. Looks fine.

  used via both Python scripts and application to interact with each other

You didn't describe the interaction, in English nor in code. Maybe the two sides routinely manipulate lots of data structures (1500 signals didn't quite sound like "a lot") that the other side uses less than 1% of the time, so your code or the multiprocessing support that ppperry highlighted would be appropriate. But the interaction is going to require condition variables or mutexes or higher level coordination such as queues. Since you've not specified the performance characteristics, I would just start with a TCP connection, or pub-sub, and go from there, see how things shake out. Localhost TCP offers very high bandwidth, and low latency. Profiling might reveal a need for shmem, but I'm skeptical, and it's better to cross that bridge after it's clear that you need to.


Advent of code 2017 Day 2 (2) in Functional Programming (FP)

While your code works, it took me a few tries to really understand how it works. I believe this is primarily caused by the deep nesting of evenlyDiv. FP is great for reusable code, which makes helper functions a really good idea. In this case, by using a few helpers you can make the code more readable.

A few pointers on your current solution:

Don't use strings as numbers. Sure, it might work right now because division can't concatenate strings like addition can, but it is a dangerous habit to get into.
There is no need to use a regular expression in this case to split the input into rows and columns. .split(/\n/) is the same as .split('\n').
(d, v, i, line) is a lot of parameters, in this case you don't need two of them. Instead of line, you can just use row, and you never used i anyways.
Don't default to reduce, the original function can be easily simplified by using map instead and just dropping the diff parameter.
Try to avoid meaningless variable names. For very simple functions, it is fine to just use a, and b, but for anything longer than a line (and even some functions of only one line) it makes the code much more difficult to scan when another programmer in 6 months (you) looks at it.

Here is how I would implement the solution (assuming a relatively small table, if the table is very large, some optimization would be a good idea).

const INPUT = `5\t9\t2\t8
    9\t4\t7\t3
    3\t8\t6\t5`;

// Contained in most FP libraries, but simple to write
const unary = fn => arg => fn(arg)

const sum = (a, b) => a + b
const isNot = a => b => a !== b
const isDivisible = dividend => divisor => dividend % divisor === 0;

/**
 * Takes an array of numbers, returns the result of the division
 * of the first two numbers which divide evenly or 0 if no two
 * numbers are divisible.
 */
const divideEvenly = numbers => {
  return numbers.reduce((carry, n) => {
    if (carry) return carry;

    const divisor = numbers
      .filter(isNot(n))
      .find(isDivisible(n));
    return divisor == null ? carry : n / divisor;
  }, 0);
}

// Without unary, parseInt would fail due to trying to parse with different bases
const solution = INPUT.split('\n')
  .map(line => line.split('\t').map(unary(parseInt)))
  .map(divideEvenly)
  .reduce(sum, 0);

console.log("solution ", solution);


Setting Sass environment variables in Grunt

Here is a trick I used a few weeks back when I ran into the same issue as you are (were?) having. Although I've used grunt-contrib-sass I think the trick should translate quite well to grunt-sass. What I basically did was to define two environment files with the same name and placed them in different folders. Next I configured Compass through Grunt to use different include paths (pointing to the two different folders) based on the build target. My scss file setup was pretty much as follows :

sass/
  dev/
    _env.scss
  dist/
    _env.scss

  component/
    _stuff.scss

  main.scss

and my main.scss file opened with the line

@import "env";

// use env variables from here on

Next, in my case, I defined two compass tasks in my Gruntfile which, based on environment, would either add sass/dev or sass/dist to the include path, e.g. :

compass : {
  options : {
    sassDir : '<%= project.app %>/sass',
    // ... and other options
  },
  dev : {
    options : {
      importPath : ['<%=project.app%>/sass/dev']
    }
  },
  dist : {
    options : {
      importPath : ['<%=project.app%>/sass/dist']
    }
  }
}

Now by executing either compass:dist or compass:dev tasks the include paths differ which in turn result in the inclusion of the desired set of environment variables. For grunt-sass the same thing should be possible by setting the includePaths property (rather than importPath in grunt-contrib-sass). Hope that helps!


Token Bucket context manager for rate limiting async calls

Parent-less class

class TokenBucket():

can drop the parens.

lower_snake_case

These variables:

tokensPerS
refillSleepS
sleepDuration

etc., and all of your methods, should be in lower_snake_case instead of camelCase, by convention.

Type hints

PEP484 allows you to turn this

def hasTokens(self):

into this

def hasTokens(self) -> bool:

and likewise for your other method parameters and returns. Among other things, it will allow you to drop your types from comments like this:

"""
    tokens (collections.deque): The tokens (which manifest as timestamps)
                                in reverse chronological order.
    last (float):               The most recent token consumed.
    rate (float):               See __init__ arg `tokensPerS`.
    capacity (int):             See __init__ arg `capacity`.
    sleepDuration (float):      See __init__ arg `refillSleepS`.
"""

because they'll already be in the signature.


You could use Callable instead of RunnableAbleToThrowCheckedException. Its call method could throw Exeptions and has a return value too. You can use  Void as a type parameter and return null if you don't need these features:

public class MyCallable implements Callable<Void> {

    @Override
    public Void call() throws Exception {
        ...
        return null;
    }
}

TryHelper seems like an Executor to me. I'd name it ErrorHandlerExecutor and rename its tryDoIt methods to submit (similar to ExecutorService). I guess most developers would find it familiar.
errorLoggerExecutor seems a fair name for an instance which logs the errors of the submitted tasks.
I would also rename Handler to ErrorHandler to be more descriptive.


Currently, your code is next to unreadable.

The variable names are too cryptic. Names like den and S don't tell anything about the context of the variable.

Please, use descriptive names.

You don't give space for your variables to breath. You crammed everything up and that makes it harder to read.

An example:

for(i=0;i<n;i++)
temp[i] = S / den[i] ;

Could be written as

for(i = 0; i < n; i++)
temp[i] = S / den[i];

Still on the same for, you forgot to indent it.

Indentation is important to check what belongs where. Code is read far more times than written. Improve it's readability.

Still beating on that same for, you should always have brackets around your statements. Remember the Apple SSL bug? Well, it may happen with you.

Try this instead:

for(i = 0; i < n; i++)
{
    temp[i] = S / den[i];
}

You should declare your variables as close as possible of when you will use them.

One example is this:

for(i = 0; i < n; i++)
{
    temp[i] = S / den[i];
}

I would do like this:

for(int i = 0; i < n; i++)
{
    temp[i] = S / den[i];
}

A few lines below, you have this:

min = temp[0] ;
for(i=0;i<n;i++)

You start by giving min the value of temp[0]. Why don't you start the loop at 1? You reduce 1 iteration!

Like this:

int min = temp[0];
for(int i = 1; i < n; i++)

This would speed-up your code by a very small bit, but it is important to notice.

And to squeeze a tiny bit of performance, you can change:

if(min > temp[i] && temp[i]!=0)

Into this:

if(temp[i]!=0 && min > temp[i])

Now you ask: Why? And the answer is because of shortcut evaluation. If temp[0] is false, it won't evaluate min > temp[i], because we know that it will be false as well.

This won't save much, but you shave some comparisons. Which is really good!

If you want, I can even eliminate that tiny loop I've refered before:

int min = S / den[0];
int min_idx = 0;
for(int i = 1; i < n; i++)
{
    int temp = S / den[i];
    if(temp!=0 && min > temp)
    {
        min = temp;
        min_idx = i;
    }
}

And so, you can eliminate the tiny for and the temp[20]. This was untested and may not work!

You trust too much in the user. You have no validation what-so-ever! I could say I have 5 coins and then only give 2 denomination in the wrong order. What would happen?

Also, how can I say that I have a 0.5€ coin? Or a 2€ coin? Would it be 50 and 200?

I'm really sorry if I said something that might not fit at 100%. I'm not 100% confortable with C. But I hope I've helped you.


Printing loses precision

Using this input file:

6
0 0 0 0 10000 10000

Your program gives this answer:

$13333.3

The actual answer should be $13333.32.  The program seemed correct, but the printing only printed out 6 digits of precision.  I made this change to your program which made it print out the correct answer:

cout.precision(15);

Better to use integers

It would be safer to use integers throughout your program.  There could be any number of floating point roundoff problems that might show up unexpectedly, especially since 0.01 is not perfectly representable by a double.


Grouping positive & negative reviews and counting the words

Your code is actually really good.
But:

getWordListAndCounts should be get_word_list_and_counts.
This is as Python has a style guide called PEP8.
You use a ; but for no reason. It's best to never use it.
In get_texts you do [].append([...]). This can be: [[...]].
In get_texts you have r, it would be better to use review,
this makes it easier to read. Also all the ts in getWordListAndCounts.
You can make getWordListAndCounts a list/generator comprehension.
You seem to mix spaces and tabs. This leads to highly breakable code.
(Look at your question)
Don't have white space after code. It's really annoying, and violates PEP8.

Overall I would say your code is pretty decent.

I would re-write getWordListAndCounts to this for example:

def get_word_list_and_counts(text):
    # Rename the `t`'s I have no context on what they are.
    return Counter(
        str(ttt)
        for t in text
        for tt in t
        for ttt in (re.split("\s+", str(tt)))
    )

To remove the [].append, you can use the following if it has to be a list.

def get_texts(reviews, score):
    return [r[0].lower() for r in reviews if r[1] == str(score)]

As no-one has said it:

[[...]] in get_texts seems redundent, adds complexity, and makes the algorithm worse in memory, from \$O(1)\$ with generator comprehensions, to \$O(n)\$.

The way you call the code shows us also that there is potential to reduce the complexity.

getWordListAndCounts(get_texts(reviews, 1))

To show the change to get \$O(1)\$:

def get_texts(reviews, score):
    return (
        review[0].lower()
        for review in reviews
        if review[1] == str(score) # use ferada's change
    )

def get_word_list_and_counts(text):
    return Counter(
        word
        for line in text
        for word in (re.split("\s+", line))
    )

The above shows you can clearly see it's capable to be in a single function,
if you wish for it.
And remove one of the fors in the get_word_list_and_counts.

It as one function would look like this:

def get_word_list_and_counts(reviews, score):
    return Counter(
        word
        for review in reviews
        if review[1] == str(score)
        for word in re.split("\s+", review[0].lower())
    )

That with ferada's change is probably the smallest and most concise you'll get it.
Also the second for statement will only run if the if is true.


Some notes:

It would be debatable whether it's good practice to have arguments which may contain either single elements or collections.
If you convert whatever you get to an array (using Array), there is no need to repeat code.
Don't use each + << (imperative), use map + compact (functional).

I'd write:

def get_parent(relationship_item_or_collection)
  Array(relationship_item_or_collection).map do |relationship|
    if relationship[:relationship_roles][:relationship_role][:to_role][:name] == type
      relationship[:party][:party_id][:id]
    end
  end.compact
end


Using phantom types to represent amounts and exchange rates of currencies

You could rely on the fact the types describing your currencies are Enumerable and you can therefore always generate the appropriate token based on the type of an expression. You would write something like this:

{-# LANGUAGE ScopedTypeVariables #-}

module Currency where

data USD = USD deriving (Show, Enum)
data EUR = EUR deriving (Show, Enum)

currencyRep :: Enum a => a
currencyRep = toEnum 0

newtype Amount a = Amount { value :: Float }

instance (Enum a, Show a) => Show (Amount a) where
  show v = show (value v) ++ " " ++ show (currencyRep :: a)

newtype Rate a b = Rate { rate :: Float }

convert :: Rate a b -> Amount a -> Amount b
convert k v = Amount (rate k * value v)

-- example:
main :: IO ()
main = putStrLn $ show (Amount 3 :: Amount EUR)

Now you can really talk about phantom types: Amount does not carry around a representation of the currency being used and both Amount and Rate are newtypes meaning that they will be optimized away.

Question: Is there a typeclass of singletons out there? It'd be cleaner than using Enum (though relying on deriving is pretty useful) if we had something like this:

class Singleton a where
  unique :: a


Your implementation of Double Checked Locking is semantically correct; the acquire and release fences provide minimal necessary ordering.

I am wondering why you are using standalone fences, which is almost never necessary..
It is more common to use memory ordering directly on atomic operations:

auto sp = std::atomic_load_explicit(&(it->second), std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);

...

std::atomic_thread_fence(std::memory_order_release);
std::atomic_store_explicit(&(it->second), sp, std::memory_order_relaxed);

Can be replaced with:

auto sp = std::atomic_load_explicit(&(it->second), std::memory_order_acquire);

...

std::atomic_store_explicit(&(it->second), sp, std::memory_order_release);

Furthermore, I understand why you are using (void) lock;, but I would not use that line just to suppress a compiler warning.
Also I am surprised about that warning since a modern compiler should know that RAII objects have a function. Are you sure there is a warning or is that an assumption ?


Utility function to split a number into n parts in the given ratio

Because the problem is not quite formalised and is mostly defined by the way your code currently works, I must confess that I find it quite hard to make thinds more efficient/concise.

A few point however:

using ( len(num_loads) * min_num ) un-necessarly relies on the way you have populated num_loads. You could something more generic like : yet_to_split = total_num - sum(num for _,num in num_loads) so that things work no matter what.
at the moment, I don't think it is possible for the condition sum(reduced_loads) != total_num to be true. Indeed, at the beginning, the definition of yet_to_split leads to the following property : yet_to_split + sum_of_loads = total_num. Then as we iterate over yet_to_split, sum_of_loads gets increased one by one. Because the condition cannot be true, it's not really wise to expect anyone to expect and catch this exception. If you want to perform the verification, assert is what you should be using : assert(sum(reduced_loads) == total_num).
in order to avoid any troubles while processing the input, you might want to add more checks.

My suggestions are the following :

if not load_list:
    raise ValueError('Cannot distribute over an empty container')
if any(l <= 0 for l in load_list):
    raise ValueError('Load list must contain only stricly positive elements')

A bit of a naive question but couldn't the min_num logic be extracted out by processing the load_list normally and only at the end (in a potentially different function) check that min(return_array) >= min_num ? This makes performance slightly worse for cases leading to failures but makes this usual case a bit clearer.

For instance, the code would be like :

num_loads = [ [load, 0] for  load in load_list ]
for _ in range(total_num):
    min_elem = min(num_loads, key=lambda (load, count): (float(count)/load, load))
    min_elem[1] += 1
reduced_loads = [num for _,num in num_loads]
assert(sum(reduced_loads) == total_num)
return reduced_loads

Just a suggestion but instead of recomputing the minimal element by reprocessing the whole array every-time, maybe you could use an appropriate data structure like heapq to get the minimal element quickly and then re-add it to the structure once updated.


Removing duplicates from an array quickly

You can use the indexOf function to check if a value exists in an array. This would simplify your code greatly:

Array.prototype.unique = function() {
    var a = [];
    for ( i = 0; i < this.length; i++ ) {
        var current = this[i];
        if (a.indexOf(current) < 0) a.push(current);
    }

    this.length = 0;
    for ( i = 0; i < a.length; i++ ) {
        this.push( a[i] );
    }

    return this;
}

At the end you are replacing the array's content. It would be better to not mutate the original array, but to return the new array instead with unique elements:

Array.prototype.unique = function() {
    var a = [];
    for ( i = 0; i < this.length; i++ ) {
        var current = this[i];
        if (a.indexOf(current) < 0) a.push(current);
    }
    return a;
}

The name a is a very poor choice. unique would have been better.

You should declare the loop variable i using let, to limit its scope to the current block, so the code becomes:

Array.prototype.unique = function() {
    var unique = [];
    for (let i = 0; i < this.length; i++) {
        let current = this[i];
        if (unique.indexOf(current) < 0) unique.push(current);
    }
    return unique;
}

Finally, there is a much more elegant solution to this problem, using the reduce function:

Array.prototype.unique = function() {
    return this.reduce(function(accum, current) {
        if (accum.indexOf(current) < 0) {
            accum.push(current);
        }
        return accum;
    }, []);
}

UPDATE (to answer your follow-up question)

If you want the function to take a parameter to decide whether it should modify the original array, you could try something like this:

Array.prototype.unique = function(mutate) {
    var unique = this.reduce(function(accum, current) {
        if (accum.indexOf(current) < 0) {
            accum.push(current);
        }
        return accum;
    }, []);
    if (mutate) {
        this.length = 0;
        for (let i = 0; i < unique.length; ++i) {
            this.push(unique[i]);
        }
        return this;
    }
    return unique;
}


There is some reasonable general algorithmic and python-specific advice here.

The lesson that needs to precede everything is, until you know where you're spending your time, you can't work out how to speed things up. It's well worth learning to use python's cProfile or another profiling tool.

Here's a run with the profiler of your example.

C:\Users\Josiah\Desktop>python -m cProfile -s cumtime astar.py
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 3)]
         6911416 function calls (6911411 primitive calls) in 8.103 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    8.103    8.103 {built-in method builtins.exec}
        1    0.000    0.000    8.103    8.103 astar.py:2(<module>)
        1    0.042    0.042    8.102    8.102 astar.py:59(pfind)
    15538    6.918    0.000    6.918    0.000 astar.py:43(check_List)
     2082    0.645    0.000    1.087    0.001 {method 'sort' of 'list' objects}
  6719169    0.442    0.000    0.442    0.000 astar.py:37(sortbyF)
    16658    0.019    0.000    0.031    0.000 astar.py:28(__init__)
    15539    0.008    0.000    0.018    0.000 astar.py:22(update)
    16660    0.010    0.000    0.010    0.000 astar.py:13(__init__)
    15539    0.008    0.000    0.010    0.000 astar.py:40(manhattan)
    64394    0.004    0.000    0.004    0.000 {built-in method builtins.abs}
    33161    0.003    0.000    0.003    0.000 {built-in method builtins.len}
     2083    0.002    0.000    0.002    0.000 {method 'pop' of 'list' objects}
     8494    0.001    0.000    0.001    0.000 {method 'append' of 'list' objects}
     2083    0.000    0.000    0.000    0.000 {method 'values' of 'dict' objects}
        1    0.000    0.000    0.000    0.000 {built-in method builtins.print}
        2    0.000    0.000    0.000    0.000 {built-in method builtins.__build_class__}
      6/1    0.000    0.000    0.000    0.000 astar.py:53(recursion)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 astar.py:12(Node)
        1    0.000    0.000    0.000    0.000 {method 'reverse' of 'list' objects}
        1    0.000    0.000    0.000    0.000 astar.py:27(Child)

cumtime is the amount of time spent in a function and all functions it calls.
tottime is the amount of time just spent in the function.

What you can see is that the whole run takes 8.1 seconds, and 6.9 of those are spent directly inside check_List. That's 85% of the whole program's runtime, and basically the only place that's worth optimising. After all, even if you got everything else to take no time at all, you'd only reduce your runtime by 15%. Your only options are call check_List less or make it faster.

The purpose of check_List is to determine whether successor is the fastest way seen thus far to get to wherever successor goes to. You've done that by looping over a list. It would be faster to maintain and check a dictionary of all the places you've seen thus far.

That is, change check_list to check_dict

def check_dict(openDict, successor):
    if (successor.x, successor.y) in openDict:
        return openDict[(successor.x, successor.y)].f < successor.f
    return False

and instead of

            if check_List(openlist, suc):
                continue

            openlist.append(suc)

You'd want

            if check_Dict(openDict, suc):
                continue

            openlist.append(suc)
            openDict[(suc.x, suc.y)] = suc

My variation, which changes nothing except replacing check_list with check_dict as above, runs in 0.025 seconds instead of 8.1.

You might notice that that is significantly better than an 85% speed up, which seems odd because 15% of the run time wasn't actually in check_list at all.

As it happens, my variation fixes a subtle bug that I didn't see initially. As above, check_list is meant to prevent you from revisiting nodes that you've already found a way to. It does that by exhaustively checking all the nodes that you are currently considering for a next step. However, that's not the same! Because of current = openlist.pop(0) there are some entries that you have found routes to, but are no longer part of openlist! Because you don't have any indicator to avoid going back to them, you bounce back and forth among your early nodes.

Patching that bug by separately storing each node you pop off into current and searching them as well in check_list gets almost as good performance as using the dictionary. Well, it doesn't. It takes 0.125 seconds on my machine, which is a whole five times slower than the dictionary, and liable to get worse as the graph gets bigger. But it's a good sight better than 8 seconds!


I suggest you whitelist allowable characters instead of blacklisting invalid characters. It's easier to list what's allowed than to chase all possible invalid characters.
Suggesting you move out the regex from the function to avoid recreating it on every call. The pattern is actually an object. Also, I'd suggest throwing an error instead of returning a message. Usually better to test.
The function checks if a string is a palindrome or not. Boolean is the correct return type. Errors should only be used when encountering something unexpected.
A lot, especially when you're blacklisting instead of whitelisting.
Small scale, yes. On larger apps, suggesting the use of a full test framework for more options.


Your code contains at least one bug, therefore this review is a little bit shorter than usual since you need to fix that bug either way.

So let's instead have a look at testing and how you can find bugs like this.

Testing

I'll start with testing since the presented code contains bugs. That's due to the carry logic. It works for your small examples, but QuickCheck can come up with several examples that won't work.

First, we need some additional functions:

import Data.List (foldl')
import Test.QuickCheck

type Digit = Int8

fromDigits :: [Digit] -> Integer
fromDigits = foldl' (\a x -> a * 10 + x) 0 . map fromIntegral

toDigits :: Integral n => n -> [Digit]
toDigits n | n < 0 = []
toDigits 0 = [0]
toDigits n = reverse . map fromIntegral . go $ n
  where
    go 0 = []
    go n = let (q,r) = n `quotRem` 10 in r : go q

We should test that fromDigits and toDigits work correctly:

prop_digitIdentity1 (NonNegative x) = fromDigits (toDigits x) === x

prop_digitIdentity2 =
    forAll validDigits $ \x ->
      toDigits (fromDigits x) === x
  where
    validDigits = fixEmpty . dropWhile (== 0) <$> listOf (choose (0,9))
    fixEmpty [] = [1]
    fixEmpty xs = xs

QuickCheck tells us that our properties hold:

*Main> quickCheck prop_digitIdentity1
+++ OK, passed 100 tests.
*Main> quickCheck prop_digitIdentity2
+++ OK, passed 100 tests.

Now it's time to write a test for add:

prop_add (NonNegative x) (NonNegative y) =
    toDigit x `add` toDigit y === toDigit (x + y)

If we run this now we get a counter example:

*Main> quickCheck prop_add
*** Failed! Falsifiable (after 63 tests and 5 shrinks):
NonNegative {getNonNegative = 50}
NonNegative {getNonNegative = 50}
[1,0] /= [1,0,0]

So add doesn't work for [5,0] [5,0]. Essentially, it doesn't work whenever the carry needs to propagate. I didn't look into this in detail, though.

Further remarks

padToSameLength should get a type signature. Also, take n (repeat x) is replicate n x.

We can make padToSameLength a little bit easier to read if we add additional whitespace:

padToSameLength :: Num a => [a] -> [a] -> ([a],[a])
padToSameLength xs ys =
  if lenDiff < 0
      then (padWithLeadingZeros xs (lenDiff * (-1)), ys)
      else (xs, padWithLeadingZeros ys lenDiff)
  where
      lenDiff = length xs - length ys
      padWithLeadingZeros list nr = take nr (repeat 0) ++ list

Or we could remove the if completely, since replicate with non-positive arguments yields an empty list:

padToSameLength :: Num a => [a] -> [a] -> ([a],[a])
padToSameLength xs ys = (pad diff xs, pad (-diff) ys)
  where
    diff = length ys - length xs
    pad n ps = replicate n 0 ++ ps

Use map g instead of foldr f [] where applicable

If you have a function f value list = g value : list, then foldr f [] list is the same as map g list. This certainly holds for an empty list:

foldr f [] []     = map g [] = []

So let's say it holds that foldr f [] xs == map g xs, we have to check that foldr f [] (x:xs) == map g (x:xs) for all x:

foldr f [] (x:xs) = x `f` foldr f [] xs
                  = g x : foldr f [] xs -- induction
                  = g x : map g xs
                  = map g (x:xs)

Therefore, we can simplify getSumWithCarry:

add :: [Int8] -> [Int8] -> [Int8]
add xs ys = toIntList $ foldr addCarry [] sumWithCarry
  where (paddedXs, paddedYs) = padToSameLength xs ys
        sumWithCarry = map getSumWithCarry $ zip paddedXs paddedYs

        -- Turn the list of sums with carry into a list of sums
        toIntList [] = []
        -- If the first pair has a carry of one, add that to the list.
        -- This ensures that the resulting list can grow one digit
        toIntList xs@((_,carry):_) | carry >0  = carry : map fst xs
                                   | otherwise = map fst xs

        -- Combines two digits to their sum and their carry
        getSumWithCarry (x,y) | x + y >= 10 = ((x + y) - 10, 1)
                              | otherwise   = (x + y, 0)

Use zipWith f xs instead of map (uncurry f) . zip xs

However, map f $ zip xs ys is the same as zipWith (curry f) xs ys, so let's further simplify add:

add :: [Int8] -> [Int8] -> [Int8]
add xs ys = toIntList $ foldr addCarry [] sumWithCarry
  where (paddedXs, paddedYs) = padToSameLength xs ys
        sumWithCarry = zipWith getSumWithCarry paddedXs paddedYs

        toIntList [] = []
        toIntList xs@((_,carry):_) | carry >0  = carry : map fst xs
                                   | otherwise = map fst xs

        getSumWithCarry x y | x + y >= 10 = ((x + y) - 10, 1)
                            | otherwise   = (x + y, 0)

We cannot get rid of foldr addCarry, since addCarry v l isn't g v : l for any suitable l.

Use a simpler algorithm (first)

Usually, with addition, we want to start with the least significant digit. This is a lot easier if we reverse the digits first:

addBase :: Integral n => n -> [n] -> [n] -> [n]
addBase base as bs =
    cleanup $ mapAccumL go $ zipWithPad 0 (+) (reverse as) (reverse bs)
  where
    go carry sum = (carry + sum) `quotRem` base
    cleanup      = -- exercise, but very similar to addCarry

zipWithPad :: a -> (a -> a -> a) -> [a] -> [a]
zipWithPad a f xs ys = -- left as exercise


The structure is kinda confusing. empty_name? does a lot more than just tell you if the name's empty, and so does folder_exists?. Meanwhile, the constructor is the first place you ask for a name - but it's not checked there. create_remote_repo doesn't just create a repo, it also sets it as upstream for the local one. Which, in turn, means that create_local_repo must be called before create_remote_repo, but that isn't made explicit in the code.

In all, you methods just seem to be doing more, or doing something different than what they claim.

There's also a straight-up bug: empty_name? will never return true. If the string's empty it'll just call itself repeatedly until you finally give in and enter a string. At that point, it'll return all the way back through the stack, and... return false in the end. The true line does nothing by itself.
folder_exists? does something similar; it'll also always return false.

You class is also called Repo, though it doesn't actually model a repository. A name like RepoGenerator would be more accurate, though I'm on the fence about whether a class is even necessary in this case. You basically just call Repo.new and it does everything and the script exits; there's little need to keep state.

I'd also avoid the hardcoded file path constants. They make the script unusable for anyone but you - and perhaps even for yourself if you switch computer.

However, regardless of implementation, I find the function of this script somewhat more suspicious.

Your remote repo isn't actually "remote". It's just as local as your other one, it just happens to get copied by Dropbox. And since it's copied from computer to computer there's no guarantee it's in sync. If you have 2 computers, you basically end up with 2 "remote" repos, and 2 local ones.

Moreover, you don't want Dropbox messing with git's own files. If something gets corrupted by Dropbox, your "remote" repo may break. Or worse: It breaks silently. You then pull from that repo, and now you've broken your local repo too.

You might as well simply place your "local" repo in Dropbox, and call it a day. If you want a proper remote repo, use GitHub, Bitbucket, or Beanstalk - or set up your own server.

Secondly, you could just set up a ~/.gitignore_global file on your computer(s) to make sure files like .DS_Store etc. are always ignored. No need for a local .gitignore in every repo that just lists the same files every time.

If you do want to list some files, use a heredoc:

ignore_list = <<-LIST
# System files
.Thumbs.db
.DS_Store

# IDE files
.idea

# Generated/downloaded files
/vendor
/node_modules

LIST

Other stuff:

You don't handle special characters (e.g. whitespace) in your paths. A name like "my awesome repo" would probably pass all your checks, but fail when it has to actually create a repo. Take a look at the Shellwords module and do something like: %x{ git init #{name.shellescape} }
In fact, if a command fails, your script will probably just keep going. For instance, let's say that git init fails: Your script will happily continue with git add . (which fails) and git commit (which fails too). Kinda pointless.
In other words, if you run a shell command, you'll probably want to check its return value (e.g. $?.success? - $? gets set when you execute a shell command). You can also consider combining a few commands and let the shell handle things, e.g. git add . && git commit -m 'Initial commit'
In git parlance, the first commit is the initial commit. Not "initialize commit" - in fact, that doesn't really make much sense.

To sum up, and to answer your questions directly:

  Is it correct to use a class for that?

You can, although it's probably not called for in this case. Your class, as it is right now, is just a collection of methods. You can't really use a Repo instance for anything. A module would be fit the bill better, though for a simple script like this, you might as well just write some methods.

  What can I make better?

Well, see above :)
Basically, refactor it so your methods only do what they say, and only say what they do; don't repeat yourself; etc. etc..

  Are there any security gaps in it?

"Security gaps" is debatable. I doubt this script will somehow get you hacked, or something. There are safety gaps though, such as not escaping strings before using them in commands, and not checking that previous commands actually worked.
And there's the idea of have two local repos, where one just happens to get copied by Dropbox, which is sort of odd.

  Is the usage in for true and false in the empty_name? and folder_exists? methods correct?

Well, no, not quite. As mentioned, those methods can't actually return anything but false every time. ?-methods are basically yes/no questions, but yours do a bunch of stuff - seemingly to avoid answering "yes". Just make them "honest", and just have them say true or false.


Algorithm for finding inversions in Merge Sort

For performance reasons, in Merge Sorts, it is common to have just one temporary array for the data, and then you use positions and lengths to work inside the relevant parts of the data.

The above is hard to describe without a code exammple, so the following will have to do.... a typical merge sort algorithm has a recursive method that looks something like:

public void mergeSort(int[] array, int[] temparray, int offset, int length) { ... }

Then, inside that system you do not need to keep creating internal arrays. The array-portion is merged in to the temparray, then copied back (or visa-versa - copied in to the temp array, then merged back).

Still, if you insist on creating mini-arrays for each merge set, you should at least consider using the native code in Java that does the bulk of the work.... for example, you could 'lose the right/left array methods, and your mergeSort could look like:

static void mergeSort(int[] array){

    if(array.length > 1){

        int mid = array.length / 2;

        int[] left = Arrays.copyOfRange(array, 0, mid);
        int[] right = Arrays.copyOfRange(array, mid, array.length - mid);

        mergeSort(left);
        mergeSort(right);

        merge(array,left,right);
    }
}

As for the merge method, it is OK, but it is done as a 'pull' mechanism.... it pulls the values in to the final array by comparing the values from the source arrays. I find it easier to use a push mechanism.... Again, hard to describe without code:

static void merge(int[] array, int[] left, int[] right){

    int iLeft = 0;
    int iRight = 0;
    int iOut = 0;
    /** Traverse through the source arrays */
    while(iLeft < left.length || iRight < right.length){
        if(iLeft < left.length && (i_right >= right.length || left[iLeft] <= right[iRight]) {
            array[iOut++] = left[iLeft++];
        } else {
            array[iOut++] = right[iRight++];
        }
    }

}


What you have implemented is a back-to-basics number-system in base 62 Your IntList List is a mechanism of having the equivalent of "units", "tens", "hundreds", except you are in base 62 so it's "units", "sixty-twos", .....

When you increment a value, and it overflows, you then set it back to zero, and increment the next column instead.

In addition, you have a special case for the first time around, where you have to bypass the logic to ensure you have the right initial value returned.

So, there's a trick for the first time around that's easy to implement. The trick is to think of the array as holding the "next" value to return. Your code then becomes:

    string BruteForceString = "";

    foreach (int CurrentInt in IntList)
        BruteForceString += CharList[CurrentInt];

    // Now calculate the **next** password

    ......

    return BruteForceString;

Note how your initial array already contains the "next" password when initialized. Then, you can convert that to a string, and then increment the array to be ready for the next call.

But, I want to suggest that you are doing it all horribly wrong... ;-)

What you should be doing is using a simple long value to store your next value, and then using integer division and modulo to work your base-62 system.

Additionally, your variable names are quite horrible.... but that's OK, we will get rid of them all except the worst....

private ulong IntPasswordsGenerated = 0;

public string GenerateString()
{

    string password = "";
    ulong base = CharList.Length;

    // get the current value, increment the next.
    ulong current = IntPasswordsGenerated++;

    do
    {
        password = CharList[current % base] + password;
        current /= base;
    } while (current != 0);

    return password;
}

The magic is almost entirely in this line here:

   ulong current = IntPasswordsGenerated++;

hat takes a copy of the "next" password, and then afterwards increments what the next password will be.

Using division and modulo is likely a lot faster than the multiple loops required to check and validate the multiple array elements in your custom number system.

Finally, by taking a copy of the next password, and by keeping the password as a single ulong instance variable, it becomes relatively simple to lock on a small section of code and then make your method able to run in multiple threads... allowing you to brute force more passwords at once though parallel processing. All you need to do that is drop the ulong to a long, and then use the Interlock.increment() method to do a thread-safe, atomic increment (assuming you have a 64-bit machine).


.Net BouncyCastle - CSR and Private Key Generation

ArrayList and Hashtable were superceded by List<T> and Dictionary<TKey, TValue>, respectively, in .NET 2.0.

The first parameter of the X509Name constructor, ordering, specifies the order in which the OID/string pairs will be processed. However we're using new ArrayList(attrs.Keys) for this parameter, and the documentation for Hashtable states "The order of the keys ... is unspecified", so we can't rely upon the keys being returned in the same order that we inserted them.

If the order isn't important in your case, replace ArrayList/Hashtable with List<T>/Dictionary<TKey, TValue>:

var attributes = new Dictionary<DerObjectIdentifier, string>
{
    { X509Name.CN, domainName },
    { X509Name.O, companyName },
    { X509Name.L, city },
    { X509Name.ST, state },
    { X509Name.C, countryIso2Characters }
};

if (division != null)
{
    attributes.Add(X509Name.OU, division);
}

if (email != null)
{
    attributes.Add(X509Name.EmailAddress, email);
}

var subject = new X509Name(attributes.Keys.ToList(), attributes);

If the order is important to you, then we need another solution since "The order of the keys in the Dictionary<TKey, TValue>.KeyCollection is unspecified".

The obvious solution is to use a List<KeyValuePair<DerObjectIdentifier, string>>, but this gets very verbose:

var attributes = new List<KeyValuePair<DerObjectIdentifier, string>>
{
    new KeyValuePair<DerObjectIdentifier, string>(X509Name.CN, domainName),
    ...
};

One trick I read about is to define a helper class like this

private class KeyValuePairList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
{
    public void Add(TKey key, TValue value)
    {
        this.Add(new KeyValuePair<TKey, TValue>(key, value));
    }

    public IEnumerable<TKey> Keys
    {
        get { return this.Select(item => item.Key); }
    }

    public IEnumerable<TValue> Values
    {
        get { return this.Select(item => item.Value); }
    }
}

The Add method lets us use the same initializer syntax we used for the Dictionary.

And then you can use the X509Name(IList, IList) constructor.

var attributes = new KeyValuePairList<DerObjectIdentifier, string>
{
    { X509Name.CN, domainName },
    { X509Name.O, companyName },
    { X509Name.L, city },
    { X509Name.ST, state },
    { X509Name.C, countryIso2Characters }
};

if (division != null)
{
    attributes.Add(X509Name.OU, division);
}

if (email != null)
{
    attributes.Add(X509Name.EmailAddress, email);
}

var subject = new X509Name(attributes.Keys.ToList(), attributes.Values.ToList());


Tuples can be used as dictionary keys, so creating a second dictionary for reverse lookups can be as simple as:

reverse_lookup = {(lineID, vertex): idx
                  for idx, (lineId, _, vertex)
                  in instance.indexList.items()}


template<class C, class T>
auto contains(const C& v, const T& x)
-> decltype(end(v), true)
{
    return end(v) != std::find(begin(v), end(v), x);
}

Changes:

Removed the superfluous check for emptyness.
Parameterized on the container too, so all containers possible.

Removed from consideration if v is not a container of some sort.

Return the condition directly, no need for sticking it into a condition.

Of course, if you do many containment-tests on big containers, using an optimized container with optimized algorithms instead of vector might be a good idea, though measure it.

A bit more complicated, but using the container-provided find() for best performance where applicable:

#include <algorithm>

template<class C, class T>
inline auto contains_impl(const C& c, const T& x, int)
-> decltype(c.find(x), true)
{ return end(c) != c.find(x); }

template<class C, class T>
inline bool contains_impl(const C& v, const T& x, long)
{ return end(v) != std::find(begin(v), end(v), x); }

template<class C, class T>
auto contains(const C& c, const T& x)
-> decltype(end(c), true)
{ return contains_impl(c, x, 0); }


First the really easy advice:

use strict mode https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
use const instead of let for stuff you know you're not supposed to change (symbol, player1, player2); declaring it const helps you keep some assumptions later
use === instead of == generally; I think the only legitimate use for == is for using it with null when you allow undefined or results of typeof if you feel like you're a JS human minifier :)
prefer camel case since JS already does it and it would look weird to have two casing strategies in the same codebase
use better naming in general: I'm talking about array in function checkforOwin(array) - array is extremely generic (what array?!?) I would call it board so I know what I'm dealing with; the fact that it's implemented as an array is a detail
I'd also like a function named checkforOwin to just check and return true/false than exit the process xD
who's O in this same function name? I thought we're comparing with the variable player1; stick to one or the other, not both; you'd have to update quite a bit of code if you change the initial statement of let player1 = "X"

...and the more involved:

I would use nested arrays for the board because I can't easily picture what board[7] is; but I can picture what board[2][1] is
those really long if statements look very repetitive; they look a lot like patterns on a board so instead let's turn that code into data so we can manage it easier; we can rewrite the patterns like this:

const isOWinner = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 4, 8],
// ...
].some((indices) => indices.every((index) => board[index] === player1))

That big condition blob in your if statements can be rewritten like this. Because it's an array you can store it somewhere; load it; merge with other patterns or extend or whatever you can do with arrays. Code that looks like data should be represented as data.
In fact let's use the same data in both functions and merge them into one:

function checkForWin (board, player) {
  const isWinner = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 4, 8],
    // ...
  ].some((indices) => indices.every((index) => board[index] === player))

  if (isWinner) {
    console.log(player + 'wins')
    process.exit()
  }
}

And now you just call checkForWin(board, player1) or checkForWin(board, player2)


A simple option would be to use reflection to check for properties that are virtual and has the Id-suffix. This is where I came up with, working for me;

public static IQueryable<T> IncludeAll<T>(this IQueryable<T> queryable) where T : class
{
   var type = typeof (T);
   var properties = type.GetProperties();
   foreach (var property in properties)
   {
       var isVirtual = property.GetGetMethod().IsVirtual;
       if (isVirtual && properties.FirstOrDefault(c => c.Name == property.Name + "Id") != null)
       {
           queryable = queryable.Include(property.Name);
       }
   }
   return queryable;
}

I hope this answers your question.


Concurrent programming adds a lot of complexity only by the fact that it is concurrent - this alone is reason enough to use concurrency API. One of the rules of good programming is to not reinvent a wheel - which means

always use available libraries instead of coding yourself unless you have a very good reason to do it

This applies above all to JDK, in your case to the java.util.concurrent package.

Here is a very simple solution, which is so simple only because of concurrent package in JDK - it uses lambda expression so you'll need Java 8, but it's easy to replace is with a Runnable:

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadStartTest {

  public static void main(String[] args) {
    int count = 5;

    CountDownLatch latch = new CountDownLatch(count);
    CyclicBarrier barrier = new CyclicBarrier(count);
    ExecutorService pool = Executors.newFixedThreadPool(count);

    Random random = new Random();
    for (int i = 0; i < count; i++) {
      pool.execute(() -> {
        try {
          System.out.println("Thread starts");
          // startup
          Thread.sleep(random.nextInt(100));
          // wait for other threads
          System.out.println("Thread waits");
          barrier.await();
          // process whaterver should be processed
          System.out.println("Thread works");
          Thread.sleep(random.nextInt(1000));
          System.out.println("Thread finished");
        } catch (Exception e) {
          System.err.println("Worker thread inrerrupted");
        } finally {
          latch.countDown();
        }
      });
    }

    try {
      // wait for the threads to be done
      latch.await();
      System.out.println("== End == ");
    } catch (InterruptedException e) {
      System.err.println("Starting inrerrupted");
    }
    pool.shutdown();
  }

}

It does all you need without the need to cope with complex lock/notify sequences with possible deadlocks - just using what the language offers.

If you increase the number of threads you'll notice how the threads start to wait before all even got started, yet all wait for other before starting processing.

Explanation

First let me stress that the concurrent package has very powerful asynchronous concepts that make concurrent programming almost easy :-), so I would suggest trying to get familiar with it and refrain from complex and hard to debug state machines with lock/notify.

Now here we have some constructs from the java.util.concurrent package playing together:

ExecutorService
CyclicBarrier
CountDownLatch

Simple speaking the ExecutorService manages a pool of threads and distributes work between them – it is not guaranteed that each work unit gets a new thread though. Anyway it frees you from creating threads on your own, additionaly you can not only execute Runnable without a return value but also Callable instances, where you can get a return value using Futures. This is powerful, istn't it - submit code to be executed asynchronously and retrieve the result at some time in the future - all that in a very short and simple and expressive code.

In this case the ExecutorService gets created with Executors.newFixedThreadPool(count), so we have exactly the same number of threads as work units, which is important - more about it later.

From Javadoc:

  CyclicBarrier is a synchronization aid that allows a set of threads to
  all wait for each other to reach a common barrier point.
  CyclicBarriers are useful in programs involving a fixed sized party of
  threads that must occasionally wait for each other.

This is exactly the case here – you wish that all your threads wait for each other before continuing. The parameter to the constructor defines how many threads should wait – in this case exactly the same value as the number of started threads, so each of the threads waits for the count threads get to to that point by calling barrier.await(). After calling the barrier.await() count times the barrier and thus all the threads are released and can continue.

The CyclicBarrier can be reused, this is why it is called “Cyclic” – just call reset() and you can repeat the whole operation.

Again from the JavaDoc:

  CountDownLatch is a synchronization aid that allows one or more
  threads to wait until a set of operations being performed in other
  threads completes.

In this case the main thread waits in latch.await until all the threads finish the work and let the latch’s counter get down to zero by calling latch.countDown().

Actually we could make a version without the CountDownLatch – which is then even simpler and uses the ExecutorService awaitTermination method – here the ExecutorService waits until all its threads are finished, so that they do not need the latch. The one drawback of this strategy is that we have to actively cope with timeouts, since the awaitTermination method requires a timeout parameter:

Version without CountDownLatch

public static void main(String[] args) {
  int count = 50;

  CyclicBarrier barrier = new CyclicBarrier(count);
  ExecutorService pool = Executors.newFixedThreadPool(count);

  Random random = new Random();
  for (int i = 0; i < count; i++) {
    pool.execute(() -> {
      try {
        System.out.println("Thread starts");
        // startup
        Thread.sleep(random.nextInt(10));
        // wait for other threads
        System.out.println("Thread waits");
        barrier.await();
        // process whaterver should be processed
        System.out.println("Thread works");
        Thread.sleep(random.nextInt(1000));
        System.out.println("Thread finished");
      } catch (Exception e) {
        System.err.println("Worker thread inrerrupted");
      }
    });
  }

  pool.shutdown();
  try {
    // wait 1 minute for the threads to be done
    pool.awaitTermination(1, TimeUnit.MINUTES);
    System.out.println("== End == ");
  } catch (InterruptedException e) {
    System.err.println("Starting inrerrupted");
  }
}

Now this solution has its own disadvantage: if the thread pool's size is smaller than the number of threads it will dead lock in barrier.await(), because all running threads are waiting for more to come yet no more threads can get executed since the pool has no more available threads. You can try it yourself:

ExecutorService pool = Executors.newFixedThreadPool(count - 1);

And it hangs!

Now I have a 3rd version for you, which doesn’t deadlock – to remove the factor limiting the number of threads I’ll give on ExecutorService up and create Threads manually, in this case I have to revert back to CountDownLatch to be able to wait for the threads to finish:

Version without ExecutorService

public static void main(String[] args) {
  int count = 50;

  CountDownLatch latch = new CountDownLatch(count);
  CyclicBarrier barrier = new CyclicBarrier(count);

  Random random = new Random();
  for (int i = 0; i < count; i++) {
    new Thread(() -> {
      try {
        System.out.println("Thread starts");
        // startup
        Thread.sleep(random.nextInt(10));
        // wait for other threads
        System.out.println("Thread waits");
        barrier.await();
        // process whaterver should be processed
        System.out.println("Thread works");
        Thread.sleep(random.nextInt(1000));
        System.out.println("Thread finished");
      } catch (Exception e) {
        System.err.println("Worker thread inrerrupted");
      } finally {
        latch.countDown();
      }
    }).start();
  }

  try {
    // wait for the threads to be done
    latch.await();
    System.out.println("== End == ");
  } catch (InterruptedException e) {
    System.err.println("Starting inrerrupted");
  }
}

Even in this version it remains pretty short and simple thanks to lambda in Java 8.


Use one event listener that propagates the event.
The correct collection of listeners in $.e.win is selected with event.type.

$.each($.e.win, function(eventName) {
  $(window).on(eventName, propagateEvent);
});

function propagateEvent(event) {
  var listeners = $.e.win[event.type];
  for (var i = 0; i < listeners.length; i++) {
    listeners[i].call(this, event);
  }
}


Object Oriented Graph Hierarchy with Depth First Search

General
Depth first search generally applies to trees (because it has a depth, no cycles). You have implemented a general purpose graph (which can contain cycles and thus is not a tree (and does not have a depth).
Code Review
Pragmas are compiler specific. They are fine if you use them taking this into context.
#pragma once

This pragma is basically useless as it is non portable. Use the appropriate include guards unless you want to be locked into your current compiler only.
Not sure why you need to make isVisitied a member.
class BiGraph :public Graph
{
    std::vector<bool> isVisited;

The only reason you seem to need it was because areConnected() returns it by reference.
const std::vector<bool>&  areConnected(int sourcevertex)

I assume you did this to save the cost of copying the vector out. This is a false optimization. C++ is highly optimized and it is unlikely that a return by value would be copied out. The compiler has aggrissive RVO/NRVO optimization that would build the result at the destionation. In C++11 move semantics are introduced and compliment the RVO/NRVO optimization and in the few cases were they can not be built in place move semantics kick in and the content is moved optimally out of the method.
So declare this function
const std::vector<bool>  areConnected(int sourcevertex) const;

The specialization std::vector<bool> is broadly considered a mistake. It is optimized for size (unlike nearly everything else in C++ which is optimized for speed).
Because it optimized for size it has several drawbacks and does not act like a normal std::vector<> (which is why it is normally avoided). Now if you think you need to optimize for size then fair enough but normally people prefer to use std::vector<char>
Simpler Issues
Sure.
void ZeroBoolArray(std::vector<bool>& arr)

But if you fix the code as I suggeste above you don't need this function.
There is a simpler way to write this:
for (auto &x : arr)
{
    x = false;
}

// Easier to write as:
x = std::vector<bool>(x.size());   // Might be slightly more expensive.

Please one variable per line. This includes initializee list.
// This is unreadable
BiGraph::BiGraph(int maxvertexcount_, std::string name_):graph(maxvertexcount_), maxVertexCount(maxvertexcount_), name(name_), isVisited(maxVertexCount)
{

}

// Rewrite as:
BiGraph::BiGraph(int maxvertexcount_, std::string name_)
    : graph(maxvertexcount_)
    , maxVertexCount(maxvertexcount_)
    , name(name_)
    , isVisited(maxVertexCount)
{}
// PS I hate the trailing `_` there is no need to have it.
// If you re-write as:
BiGraph::BiGraph(int maxvertexcount, std::string name)
    : graph(maxvertexcount)
    , maxVertexCount(maxvertexcount)
    , name(name)
    , isVisited(maxVertexCount)
{}
// this works just as well and is unambiguous.

Why only check fVertex?
void BiGraph::addAdjacentImpl(int fVertex, int sVertex)
{
    if (fVertex > maxVertexCount)
    {
        throw std::out_of_range(name + ": trying to add vertex which doesn't exist");
    }

You should probably also check sVertex. But unless you explicitly want that error message you don't need the test; just use at() method.
void BiGraph::addAdjacentImpl(int fVertex, int sVertex)
{
    graph.at(fVertex).push_back(sVertex);
    graph.at(sVertex).push_back(fVertex);
}

Also you don't check if the vertex has already been added.
Sure this works fine. But it would be better to use the Visitor Pattern.
void BiGraph::traverse(int sourceVertex)

We covered this function above:
const std::vector<bool>& BiGraph::areConnectedImpl(int sourceVertex)

// I would write as:
const std::vector<char> BiGraph::areConnectedImpl(int sourceVertex) const
{
    std::vector<char>  isVisited.
    traverse(sourceVertex, isVisited);
    return isVisited;
}

If your destructor does nothing then don't declare it. The compiler generated version will work perfectly well.
BiGraph::~BiGraph()

Sure: This printImpl() seems easy enough. But it could be improved.
void BiGraph::printImpl() const

Rather than assume you will print to std::cout take a parameter for the output stream to be used. It can default to std::cout but this gives you the flexability to use other streams (like files/string streams etc).
Also in C++ it is standard to define an output operator to print an object.
Prefer "\n" over std::endl. The std::endl will also flush the stream which will usually make the code sub optimal. The stream is already flushed automatically if needed and if not needed will flush at optimal points so there is no need to manually force a flush.
Prefer the range based for loop if you don't need the index (currently your j loop is wrong (you should print the value at each index).
void BiGraph::printImpl(std::ostream& str = std::cout) const
{
    for (size_t i = 0; i < graph.size(); i++)
    {
        str << i << ": ";
        for (auto j: graph[i])
        {
            str << j << ' ';
        }
        str << "\n";
    }
}
std::ostream& operator<<(std::ostream^ str, Graph const& g)
{
    g.print(str);
    return str;
}


Prioritizing one column over the other column of the same table

I believe there is not much to improve in here.

If you really want to make a one call to sql server, then you can move this logic to sql procedure.

You can visually improve first query and use FirstOrDefault:

var myClassPkColumn = _context.MyClass.FirstOrDefault(x => x.PkColumn == reference);

if (myClassPkColumn != null)
{
    return new MyClass[] { myClassPkColumn };
}

If you know that your PkColumn is always less or equal 3 characters, then you can add if statement and skip first query completely in case your reference has bigger length.

if (reference?.Length <= 3)
{
    // query by PkColumn column
}

If you want to combine two queries into one you can add this OrderBy:

var myClassResult = _context.MyClass
                    .Where(myClass => myClass.PkColumn.Equals(reference) ||
                        myClass.Description.Contains(reference))
                    .OrderBy(x => x.PkColumn == reference ? 0 : 1)
                    .Take(8)
                    .ToList();


First of all, it might help to explain the problem domain; you might have an XY problem here. The first application for "4x4x4 bitboards" that pops into my head is that you're dealing with Rubik's Revenge... but representing cubelets by single bits is not of obvious utility to me, and rotating the entire cube by 90 degrees is even less useful.

Next, this does seem like the sort of thing that has a known solution somewhere, so I'd definitely recommend doing a thorough Google search. (Asking StackOverflow might also be appropriate; but that's just offloading the Google search onto somebody else. It would be polite to do some searching yourself first, and report the results.) I didn't do any searching myself other than a quick fruitless skim through HAKMEM; but if you find out "the" answer, I'd be mildly interested to hear about it.

Okay, so, let's assume that we've got a 4x4x4 bitboard that looks like this:

uint64_t board_with_one_bit_set(int x, int y, int z)
{
    int index = (x + 4*y + 16*z);
    return 1uLL << index;
}

Notice that "rotating a bitboard" is a special case of "permuting the bits in a word." That is, we expect our result to have the same parity as the input — and in fact the same bits, just in a different order. So mathematically it might make more sense to think of this as a permutation of a 64-element sequence, rather than as a bunch of imperative shifts and masks.

To avoid brain farts, I decided to write a little Python script to generate the bit-shifting code from the permutation. Here's the input:

original = [
    63, 62, 61, 60,
    59, 58, 57, 56,
    55, 54, 53, 52,
    51, 50, 49, 48,
                   47, 46, 45, 44,
                   43, 42, 41, 40,
                   39, 38, 37, 36,
                   35, 34, 33, 32,
                                  31, 30, 29, 28,
                                  27, 26, 25, 24,
                                  23, 22, 21, 20,
                                  19, 18, 17, 16,
                                                 15, 14, 13, 12,
                                                 11, 10, 9,  8,
                                                 7,  6,  5,  4,
                                                 3,  2,  1,  0,
]
rotated_right_around_x_axis = [
    51, 50, 49, 48,
    35, 34, 33, 32,
    19, 18, 17, 16,
    3,  2,  1,  0,
                   55, 54, 53, 52,
                   39, 38, 37, 36,
                   23, 22, 21, 20,
                   7,  6,  5,  4,
                                  59, 58, 57, 56,
                                  43, 42, 41, 40,
                                  27, 26, 25, 24,
                                  11, 10, 9,  8,
                                                 63, 62, 61, 60,
                                                 47, 46, 45, 44,
                                                 31, 30, 29, 28,
                                                 15, 14, 13, 12,
]

(I think this is right. "Rotating right around the x axis" means pointing your right thumb in the direction of increasing x, which I think of as "to the left", and curling your fingers in the direction of the rotation, which I think of as "top-moves-away". However, even with this much effort to avoid brain farts, I might have messed it up.)

Here's the Python code for converting the input into a C++ function body:

def to_cpp11_hex(mask):
    return "0x%04X'%04X'%04X'%04X" % (
        ((mask >> 48) & 0xFFFF),
        ((mask >> 32) & 0xFFFF),
        ((mask >> 16) & 0xFFFF),
        ((mask >> 0) & 0xFFFF),
    )

def print_function_body(original, rotated):
    bits_by_rotation = {}
    for b in xrange(64):
        o = original.index(b)
        r = rotated.index(b)
        rotl_amount = ((o - r) + 64) % 64
        bits_by_rotation.setdefault(rotl_amount, []).append(r)
    print '    uint64_t r = 0;'
    for amount, bits in sorted(bits_by_rotation.iteritems()):
        mask = sum(1 << b for b in bits)
        print '    r |= rotl(o, %d) & %s;' % (amount, to_cpp11_hex(mask))
    print '    return r;'

print_function_body(original, rotated_right_around_x_axis)

This script generates functions like the following:

inline constexpr uint64_t rotl(uint64_t x, int k)
{
    return (x << k) | (x >> (64-k));
}

uint64_t rotate_left_around_x_axis(uint64_t o)
{
    uint64_t r = 0;
    r |= rotl(o, 4) & 0x0000'00F0'0000'0000;
    r |= rotl(o, 8) & 0x0000'0000'0000'0F00;
    r |= rotl(o, 12) & 0x000F'0000'0000'0000;
    r |= rotl(o, 16) & 0xF000'0000'00F0'0000;
    r |= rotl(o, 24) & 0x0000'000F'0000'0000;
    r |= rotl(o, 28) & 0x0000'F000'0000'00F0;
    r |= rotl(o, 36) & 0x0F00'0000'000F'0000;
    r |= rotl(o, 40) & 0x0000'0000'F000'0000;
    r |= rotl(o, 48) & 0x0000'0F00'0000'000F;
    r |= rotl(o, 52) & 0x0000'0000'0000'F000;
    r |= rotl(o, 56) & 0x00F0'0000'0000'0000;
    r |= rotl(o, 60) & 0x0000'0000'0F00'0000;
    return r;
}

uint64_t rotate_right_around_x_axis(uint64_t o)
{
    uint64_t r = 0;
    r |= rotl(o, 4) & 0x0000'0000'00F0'0000;
    r |= rotl(o, 8) & 0x0000'F000'0000'0000;
    r |= rotl(o, 12) & 0x0000'0000'0000'000F;
    r |= rotl(o, 16) & 0x000F'0000'0F00'0000;
    r |= rotl(o, 24) & 0x0000'0000'0000'00F0;
    r |= rotl(o, 28) & 0x00F0'0000'F000'0000;
    r |= rotl(o, 36) & 0x0000'000F'0000'0F00;
    r |= rotl(o, 40) & 0x0F00'0000'0000'0000;
    r |= rotl(o, 48) & 0x0000'00F0'0000'F000;
    r |= rotl(o, 52) & 0xF000'0000'0000'0000;
    r |= rotl(o, 56) & 0x0000'0000'000F'0000;
    r |= rotl(o, 60) & 0x0000'0F00'0000'0000;
    return r;
}

I don't immediately see any improvements. I had various ideas, such as trying to incrementally rotate o by repetitions of

    r |= (o = rotl(o, 4-or-8)) & MASK;

or limiting all the masks to 32 bits for x86-64-friendliness

def print_function_body_32bit(original, rotated):
    bits_by_rotation = {}
    for b in xrange(32, 64):
        o = original.index(b)
        r = rotated.index(b)
        rotl_amount = ((o - r) + 64) % 64
        bits_by_rotation.setdefault(rotl_amount, []).append(r)
    print '    uint64_t r = 0;'
    for amount, bits in sorted(bits_by_rotation.iteritems()):
        mask = sum(1 << b for b in bits)
        print '    r |= rotl(o, %d) & %s;' % ((amount + 32) % 64, to_cpp11_hex((mask >> 32) & 0xFFFFFFFF))
    print '    r <<= 32;'
    bits_by_rotation = {}
    for b in xrange(0, 32):
        o = original.index(b)
        r = rotated.index(b)
        rotl_amount = ((o - r) + 64) % 64
        bits_by_rotation.setdefault(rotl_amount, []).append(r)
    for amount, bits in sorted(bits_by_rotation.iteritems()):
        mask = sum(1 << b for b in bits)
        print '    r |= rotl(o, %d) & %s;' % (amount, to_cpp11_hex(mask & 0xFFFFFFFF))
    print '    return r;'

which generates function bodies like

uint64_t rotate_right_around_x_axis(uint64_t o)
{
    uint64_t r = 0;
    r |= rotl(o, 36) & 0x0000'0000'0000'0000;
    r |= rotl(o, 44) & 0x0000'0000'0000'0000;
    r |= rotl(o, 48) & 0x0000'0000'000F'0000;
    r |= rotl(o, 56) & 0x0000'0000'0000'0000;
    r |= rotl(o, 60) & 0x0000'0000'00F0'0000;
    r |= rotl(o, 4) & 0x0000'0000'0000'000F;
    r |= rotl(o, 16) & 0x0000'0000'0000'00F0;
    r |= rotl(o, 24) & 0x0000'0000'0000'0000;
    r <<= 32;
    r |= rotl(o, 8) & 0x0000'0000'0000'0000;
    r |= rotl(o, 16) & 0x0000'0000'0F00'0000;
    r |= rotl(o, 28) & 0x0000'0000'F000'0000;
    r |= rotl(o, 36) & 0x0000'0000'0000'0F00;
    r |= rotl(o, 40) & 0x0000'0000'0000'0000;
    r |= rotl(o, 48) & 0x0000'0000'0000'F000;
    r |= rotl(o, 52) & 0x0000'0000'0000'0000;
    r |= rotl(o, 60) & 0x0000'0000'0000'0000;
    return r;
}

which are nevertheless longer (in terms of number of assembly instructions) than the more "naïve" 64-bit version.

Writing an appropriate benchmark for the various possibilities, and writing out the permutation matrices for rotated_right_around_y_axis and rotated_right_around_z_axis, are left as exercises for the interested reader.

It would also be supremely interesting to feed these "rotation-permutation" functions to a superoptimizer and see what it produces. However, my wild-ass guess is that the optimal instruction sequence is in excess of 40 instructions, which would (I think) make it intractable for the current state-of-the-art in superoptimizers. But I could be wrong. Anyway, if you find out, it would be interesting to post the results here.


A simple web-app code - user registration. Is the layering ok?

I know you're asking strictly for feedback about the layers (which look fine to me), but in case you're looking for other feedback too:

if(username.equals("")
        || password.equals("")
            || email.equals("")){

You need to null check these values. getParameter can return null so you will get a NullPointerException if they don't exist.

List<String> errors = new ArrayList<String>();
errors.add("Registiration was not successful. Maybe username/email was already taken?");
httpServletRequest.setAttribute("errors",errors);

Can be done in one line if you want:

errors.add(Arrays.asList("Registiration was not successful. Maybe username/email was already taken?"));


Transferring data from a client to a server is an expensive procedure, and should be minimized as much as possible.  If the purpose of your PHP is to simply provide formatted time data, I would highly recommend letting your client do as much processing and formatting as possible

For example, what happens if the client loses internet connection?  The process will fail and the counter will not count down.

What if the connection to the server is slow or inconsistent?  The responses from the server may not return in the expected order, resulting in a countdown timer with unpredictable behavior.

Proposed solution:

PHP script processes date and returns UNIX timestamp
HTML page contains static divs with element IDs accessible to jQuery
On $(document).ready, only once, use the $.get function instead of $("#id").load to load the timestamp from the server and parse it as a Date object
Start your timer with a callback that processes the date and populates the div structure once per second.

Sample code, as requested:

recdisp.php:

<?php
    date_default_timezone_set("Asia/KolKata");
    $time=1434402728+3600000*24*10000;//some time in future.
    echo $time;
?>

timer.html:

<!doctype html>

       ...

Seconds

I will let you fill in the blanks