jquery checking nested input with repetitive code

In general, you would have an easier time doing this if your "nested rows" were actually nested. However - that leads to a variety of other layout problems, etc.

That said - here is a simpler way to accomplish what I think you're looking for:

jQuery code:

$(".checkAll").click(function (e) {
    e.preventDefault();

    // Find the row whose button was clicked.
    var $row = $(this).closest('tr');

    // Capture the associated "level" class.
    var cls = $row.children('td:first-child').attr('class');

    // Create a collection of rows, in which you can store the child-rows
    var $children = $row;

    // Start with the next row, and...
    var $current = $row.next();

    // ... for every subsequent row which is *not* on the same level as the
    // one you started with...
    while ($current.length && ($current.children('td:first-child').attr('class') !== cls)) {
        // Add the row to the collection.
        $children = $children.add($current);
        // Then move on to the next row.
        $current = $current.next();
    }

    // Capture all of the *checkboxes* within the matching rows
    var $checks = $($children).find('input[type="checkbox"]');

    // If ALL checkboxes are checked, uncheck them.
    // Otherwise, check them all.
    if ($checks.length == $checks.filter(':checked').length)
        $checks.prop('checked', false);
    else
        $checks.prop('checked', true);
});

Here is a working jsFiddle showing the code in-action.


Checking if two numbers have the same sign

First up, your code has bugs. What if one of the numbers is 0? 0 should be positive, but your code treats it as negative in some tests, and positive in others. When comparing against 0 you should use >=, not just >.

The actual code is quite readable, though, and the performance is probably not horrible. I would recommend a single return statement though. A single return statement is easier if you check for "the same sign", and not "opposite signs".

Take your code:

bool sameSign(int num1, int num2)
{
    if (num1 > 0 && num2 < 0)
        return false;
    if (num1 < 0 && num2 > 0)
        return false;
    return true;
}

Fix the 0-handling, and you have:

bool sameSign(int num1, int num2)
{
    return num1 >= 0 && num2 >= 0 || num1 < 0 && num2 < 0
}

Now, that's pretty good, and I would happily "pass" that in a code review, but, can you do some tricks?

The simplest (code wise) is to use XOR:

return (num1 ^ num2) >= 0

That compares the bits, and if they are the same, it sets the resulting bit to 0. If the sign bits are the same, the resulting sign-bit is 0, and thus a positive (or 0) value.


I tried do it a different way, when you asked this question on StackOverflow.. You find my version below, first I'll try to give you some feedback on your version :

I see you regularly use isDefined together with pattern matching or if / else. I would replace this by matching for Some / None or even better with a combination of map and getOrElse or with fold :

o.map(f).getOrElse(b)
o.fold(b)(f)

These are more ideomatic ways to handle an Option and unwrap the Option for you where you want to use it (calling get on an Option is something you should try to minimize).
It seems like you could have reused newParentId in the places where you wrote s"$parentId.$id", this would mean that newParentId should be placed outside the if else.
I am not sure if you can change the signature of MyCase, but I am not sure what extra the Option brings for elems, but this may be moot if you want to differentiate between None and Map.empty[String, MyCase]], if you don't then no collection or an empty collections is pretty much the same.

Here's what I came up with :

def getMapWithChildIds(config: Config): Map[String, Seq[String]] = {
  def mkId(prefix: String, key: String): String =
    if (prefix.isEmpty) key else prefix + "." + key

  def go(map: Map[String, MyCase], prefix: String): Map[String, Seq[String]] =
    map.flatMap { case (key, elem) =>
      val fullKey = mkId(prefix, key)
      // this will handle an unactive MyCase the same way as a MyCase with no elems
      Option(elem).filter(_.isActive).flatMap(_.elems).fold(
        Map(fullKey -> Seq.empty[String]))(
        submap => {
          val directSubKeys = submap.keys.map(mkId(fullKey, _)).toList
          // map entry for this key + entries for sub keys
          Map(fullKey -> directSubKeys) ++ go(submap, fullKey)
        })
    }

  go(config.elems, "")
}

Which gives for :

val noMap: Option[Map[String, MyCase]] = None

val config =
  Config("a", true,
    Map(
      "5" -> MyCase("id?5", true,
        Some(Map(
          "1" -> MyCase("id?5.1", true,
            Some(Map(
              "1" -> MyCase("id?5.1.1", true, noMap),
              "2" -> MyCase("id?5.1.2", true, noMap)
            ))
          ),
          "2" -> MyCase("id?5.2", true, noMap)
        ))
      ),
      "6" -> MyCase("id?6", true,
        Some(Map(
          "1" -> MyCase("id?6.1", true, noMap)
        ))
      )
    )
  )

The following result :

val map = getMapWithChildIds(config)
// Map[String,Seq[String]] = Map(5.2 -> List(), 5.1.2 -> List(), 5 -> List(5.1, 5.2), 5.1.1 -> List(), 6 -> List(6.1), 6.1 -> List(), 5.1 -> List(5.1.1, 5.1.2))

map.toList.sortBy(_._1).foreach(println)
// (5,List(5.1, 5.2))
// (5.1,List(5.1.1, 5.1.2))
// (5.1.1,List())
// (5.1.2,List())
// (5.2,List())
// (6,List(6.1))
// (6.1,List())


Probably the single biggest (or most obvious, anyway) improvement would be to write an actual insertion sort. What you have right now appears to be a bubble sort rather than an insertion sort.

Rather than swapping elements that are out of order an insertion sort divides the array into a sorted part and an unsorted part. In the beginning, the sorted part is just the first element. Then it looks at the first element of the unsorted part, copies it into a temporary location, and copies elements in the sorted part "forward" a spot until it gets to an element smaller than the temporary. That makes a "hole" for the new element to go into, and it puts that element there (then repeats for the remaining unsorted elements).

Given an array v of n elements, the loops look something like this:

for (int i=1; i<n; i++) {
    tmp = v[i];
    int j;
    for (j=i; j>0 && tmp<v[j-1]; j--)
        v[j] = v[j-1];
    v[j] = tmp;
}


Returning an array containing values from two passed in arrays

You could offload some of the work to Arrays.copyOf and System.arraycopy:

public static int[] append(int[] first, int[] second) {
  int[] result = Arrays.copyOf(first, first.length + second.length);
  System.arraycopy(second, 0, result, first.length, second.length);
  return result;
}


Arduino code and PING))) ultrasonic rangefinder

VeryLongIdentifiersInCamelCase do not make your code explicit. They just add noise.

The definition
const float speedOfSoundInAirInCentimeterPerMicrosecond =
  speedOfSoundInAirInMetersPerSecond / 10000.0;

is very hard to read. 10000 stands out as weird. After all, there are 1000000 microseconds in a second. It took me quite a time to realize that two orders of magnitude are hidden in meters-to-centimeters conversion.

By default, pulseIn timeouts in 1 second. In reality it means that there is no obstacle within 170 or so meters (aka 500 feet). I seriously doubt your hardware is capable detecting an echo at such distances. It feels safe to shorten the timeout for the sake of better responsiveness.

The production quality code must deal with the ambient noise, which will result in false positives. At least, test that the signal you detected is indeed an echo - that is, it is about as long as the ping. You should also special-case inPulse returning 0. Currently, you are returning 0 distance, whist in fact it means the distance is practically infinite.

Unless I am seeing things, either the code, or documentation is wrong. According to the spec

if value is HIGH, pulseIn() waits for the pin to go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds

which means it returns the duration of the echo, not the turnaround time you are after. Unfortunately, I don't have the hardware to play with.
Does your code give reasonable results?


This is an interesting problem but I'm afraid that my feedback will be somewhat limited:

Consider vectorizing your velfun to be represented with matrix multiplications
Your x/y/z should be combined into one matrix
You should add axis labels, and some form of colour indicator to make your graph more legible - here I've added an arbitrary "start-to-finish progress" colour
Rather than label, you likely meant to use title

The code I'm suggesting produces exactly the same results as yours. The problem is that I have no idea whether those are correct. I suggest that you re-post on https://physics.stackexchange.com/ with more details on your physics problem to get confirmation as to whether your RK is implemented correctly. You should include a picture of your graph.
Suggested
from typing import Tuple

import numpy as np
import matplotlib.pyplot as plt

A = 0.2
B = 1.0
C = 0.20

N_STEP = 10_000  # stopping time
H = 0.01         # step length

def new() -> np.ndarray:
    M = np.array([
        [0, 0, A],
        [B, 0, 0],
        [0, C, 0],
    ])
    N = np.array([
        [C, 0, 0],
        [0, 0, A],
        [B, 0, 0],
    ])

    # Define function to compute velocity field
    def velfun(p: np.ndarray) -> np.ndarray:
        return M@np.sin(p) + N@np.cos(p)

    X = np.empty((3, N_STEP))
    a = np.array((1, 0, 0), dtype=np.float64)
    X[:, 0] = a

    for k in range(1, N_STEP):
        # Provisional Euler step
        u = velfun(a)
        p = a + H*u

        # Compute velocity at provisional point
        up = velfun(p)

        # Compute average velocity
        ua = 0.5*(u + up)

        # Make final Euler step
        # using average velocity
        a += H*ua
        X[:, k] = a

    return X

def plot(x, y, z):
    # Plot results
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.set_title('x (with RK2)')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    colour = np.linspace(0, 1, len(x))

    ax.scatter3D(x, y, z, s=0.5, c=colour)

def main():
    # plot(*old())
    plot(*new())
    plt.show()

if __name__ == '__main__':
    main()

Be warned: I have very little understanding of what this code is actually doing, so my variable names are bad.


Creating a description of an item from an inventory

As you use item's name to search the item information, so you can design the name as the key of items hash table.

items = {
    "apple":
        {
            #type, edible,color information
        },
    ...
}


Managing PostgreSQL transactions for concurrency

Taking Craig's suggestion, I've had the following running in a test environment for one week with no issues:

public function runInTransaction(callable $callable)
{
    $success = false;
    $count = 0;
    $this->beginTransaction($isolationLevel);
    $this->exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
    try {
        while (!$success && $count < 5) {
            try {
                $callable();
                $success = $this->commit();
            } catch (\PDOException $e) {
                // Catch concurrency issues and retry after
                // random scaled back-off delay.
                if ($e->getCode() == '40001' || $e->getCode() == '40P01') {
                    // Serialized transaction failure or deadlock.
                    usleep(rand(100, 200) * ($count + 1));
                } elseif ($e->getCode() == '25P02') {
                    // "In failed sql transaction."
                    $this->rollback();
                    usleep(rand(100, 200) * ($count + 1));
                    $this->beginTransaction($isolationLevel);
                } else {
                    throw $e;
                }
            }
            $count++;
        }
    } catch (\Exception $e) {
        if ($this->inTransaction()) {
            $this->rollback();
        }
        throw $e;
    }
    if (!$success) {
        throw new \RuntimeException("Could not commit transaction");
    }
}


How to overcome static referencing errors in Java/basic programming?

Is my program ok?

Well, I guess it works. However, it can be structured far better.

Basic Object Oriented Programming in Java

In Java (and all of this is also true for C#), every object has a type which is represented by a so-called class. We can define operations on each type, which we call methods. Some methods operate on an individual instance of a type. Other operations are not inherently bound to instances, and operate on the whole class. We call this second kind of operations static methods.

Likewise, data can either belong to a specific instance, or is shared across all instances, in which case it's called static. Every method (static and non-static) can refer to static data, because that is shared. However, static methods cannot reference instance data, because a static method can't tell from which instance you'd like the data – and sometimes, no instance may exist at all. Static methods are mostly useful for general helpers.

It is really important to grok the difference between static and non-static methods in order to use Java effectively (the same holds for any other class-based programming language).

Meaning of the main

What is the main and why do we need it? The main originated as a feature of the C programming language. It defines an entry point into the program. At startup, your classes are initialized and then the main methods gets called with the command line arguments in an array as parameter. The main method doesn't return a value (it is void), because returning from it aborts the process.

The main is static because it's a helper method to get your control flow going – it is not coupled to any instance. It is therefore common in a main to create an instance of the surrounding class, and work with that.

Constructors

A constructor is a special method used to initialize a fresh instance. All it usually does is assigning its arguments to the corrects data fields of the instance. It isn't recommended to do the actual work here – put that into another method.

In your code, everything after the initialization can be moved into the main method where it belongs. Note that methods are invoked on a specific instance with the dot operator. The main now looks like:

public static void main(String[] args) {
    Matrix matrix = new Matrix();

    System.out.println("M");
    matrix.printMatrix();

    matrix.transpose();

    System.out.println("M'");
    matrix.printMatrix();
}

Now we are already getting into the code review zone of this answer.

Design spotlights

A method should do one thing only and – no “and”!

Every method should do one thing only. Exaggerated: While a description of your method uses the word “and”, it is doing to much. Split the functionality into more methods. For example, your transpose method does this: “It prints an empty line and swaps columns with rows of the matrix”. Is printing an empty line really necessary in a method called “transpose”?

The same goes for your version of the constructor: “It initialized the matrix and prints it out and transposes it and prints it out again” – but we already cleaned that up above.

Composability

An advantage of having each method doing one concept only makes it easier to compose them in a different way to do new things. There are a few important things that can make this easier:

Don't hardcode stuff – parameterize it

Don't hardcode things that aren't universal constants. Actually, don't hardcode things at all. For example, you assign static int mat_size = 3 – but what if I want to use a 5×5 matrix? You don't provide any functionality that actually depends on the number three. Instead, the size is a property of each instance. Therefore, we'll remove the static modifier, and initialize it in the constructor.

The constructor is another example of hardcoding: The whole test matrix is specified there. It would be better to move that data out of the constructor, and have the constructor take an array as argument instead. I'd rather initialize a new matrix like:

// array literals :) – however, I'm unsure about the exact syntax
double[3][3] testData = { { 1, 0, 0 },
                          { 5, 1, 0 },
                          { 6, 5, 1 } };
Matrix matrix = new Matrix(3, testData);

We can now initialize a matrix with arbitrary other values, not only that specific data set.

Immutability

When objects don't change their internal state over time, programs often get a bit simpler. Mathematics does this as well: When we transpose a matrix M, the M still has its old values. The transposition produces a new and distinct matrix, which we can call M' (you even do this in your printout). There is no reason our transpose method shouldn't return a new matrix either. Now we get something along the lines of:

public Matrix transpose() {
    double[size][size] newData = new double[size][size];

    for(int i = 0; i < size; i++) {
        for(int j = 0; j < i ; j++) {
            newData[i][j] = get(j, i);
            newData[j][i] = get(i, j);
        }
        newData[i][i] = get(i, i);
    }

    return new Matrix(size, newData);
}

This changes our main:

public static void main(String[] args) {
    Matrix matrix = new Matrix();

    System.out.println("M");
    matrix.printMatrix();

    Matrix transposed = matrix.transpose();

    System.out.println("M'");
    transposed.printMatrix();
}

No side effects

When a method has any effect except returning some data, it has side effects. Such effects might be changing the state of some object (thus voiding the point about immutability), or printing out some data. These side effects make it more difficult to combine these methods in a new way.

Specifically, printMatrix is an offender here. Also because it can't be changed to print to anything other than System.out. What happens when I want a string representation to display on a GUI? I can't simply use your awesome Matrix class :(

Here, it would be better to implement the toString() function, which returns a string representation of your object. There is already a default implementation for every object, but we can override it. Then, our main will look like:

public static void main(String[] args) {
    Matrix matrix = new Matrix();

    System.out.println("M");
    System.out.println(matrix.toString());

    Matrix transposed = matrix.transpose();

    System.out.println("M'");
    System.out.println(transposed.toString());
}

That is more ugliness here, but massively clears up the rest of your code. The toString might be:

public String toString() {
    StrinBuilder sb = new StringBuilder();
    for(int i = 0; i < size; i++) {
        for(int j = 0; j < size ; j++) {
            sb.append(" " + (int) get(i, j));
        }
        sb.append("\n");
    }
    return sb.toString();
}
// apologies if I mixed up the StringBuilder API

A closing note on naming things

In Java, names are written in camelCase. Class names are capitalized. Any other names start with a lowercase letter: Matrix refers to a class, while matrix is a local variable, field, or method. As an exception, constants are written all-uppercase and seperated by underscores. Because for normal names the parts of a word are distinguished by capitalization, no underscores are ever used.

It is advisable to use meaningful names like matrix or transformedMatrix, not shortcuts like m or t or m_. Choosing longer names makes it easier to read a piece of code for someone who isn't used to your shortcut notation.


In the HTML, give some id to your div with links, like this:

  Item 1
  Item 2
  Item 3
  Item 4

Then change your JavaScript like this:

$("#links > a").click(function(){
   $('.item-block').hide();
   $("#"+this.id.replace("item-","")).show();
})


Binary Search given sorted array Unit test

BinarySearch

The BinarySearch class should be public since it contains utility methods that are generally useful. To do this, write public class BinarySearch instead of class BinarySearch.

The binSearch method should be static since it does not access any fields from the BinarySearch class. After all, that class doesn't have any fields that could be accessed. To do this, write public static int binSearch instead of public int binSearch.

When you make the binSearch method static, you no longer need the new BinarySearch() in the unit test. This is good since it sounds weird to have a "new binary search". It's confusing to hear this, since "binary search" is an algorithm and not a countable thing. It makes more sense to speak of "the binary search algorithm", avoiding the word "new". On the other hand, "new house" or "new sheet of paper" sounds much more natural.

The helper method currently is:

private static int search(int start, int end, int key, int[] sortedArray) {

The order of the parameters is not the usual one. Usually the array comes first, before its indexes. In this case, this would mean:

private static int search(int[] sortedArray, int start, int end, int key) {

When you compare your code with the predefined Arrays.binarySearch and the helper function, you can see that the code is quite similar, which is a good sign.

One useful thing that the predefined Arrays.binarySearch does is that if the element is not found, it returns a hint about the index where it would be found. This is useful to see the closest existing value.

BinarySearchTest

Your existing unit tests look good. You can leave out the word test at the beginning of the method names to make the names a little shorter. They are quite long, but that's ok.

There are test cases missing:

An element from the middle cannot be found, for example 5 in [1, 2, 6, 10].
The array contains duplicate values, for example 3 in [1, 2, 3, 3, 3, 3, 3, 3, 3].

In the latter case, it is unspecified whether binSearch should return 2 or 3 or any other index. All you can do in your unit test is to check that `array[binSearch(array, key)] == key.


Comparing two arrays to see if they contain objects with different IDs

function areDifferentByIds(a, b) {
    var idsA = a.map( function(x){ return x.id; } ).unique().sort();
    var idsB = b.map( function(x){ return x.id; } ).unique().sort();
    return (idsA.join(',') !== idsB.join(',') );
}

This is the simplest I could make it. I think such small functions need to be as self contained as possible, and not need other functions. This makes them more readable, maintainable, and of course reusable. I therefor removed the getIds function. If you use that elsewhere you can keep it.

You might want to store the function (x) { return x.id; } inside a variable, and reuse it on both maps

I also think it is faster, because join is quite fast, and it doesn't require a for-loop.

EDIT my next attempt

function areDifferentByIds(a, b) {
    var idsA = a.map( function(x){ return x.id; } ).unique();
    var idsB = b.map( function(x){ return x.id; } ).unique();
    var idsAB = a.concat(b).unique();
    return idsAB.length!==idsA.length
}

secondly, you could make it more generic, by adding the property you want to check to the arguments of the function. Something like:

function areDifferentByProperty(a, b, prop) {
    var idsA = a.map( function(x){ return x[prop]; } ).unique();
    var idsB = b.map( function(x){ return x[prop]; } ).unique();
    var idsAB = a.concat(b).unique();
    return idsAB.length!==idsA.length
}

thirdly, I would much rather name it areEqualBy___. Seems more intuitive to me, but that's just me.


The comment in add_vertex is confusing and at contradicts what the code does.  If vertex already exists in _graph, the existing vertex will be replaced with an empty one, then the size increased (causing the internal _size to be incorrect).  Depending on what behavior you want when adding a vertex that already exists, you can use _graph.try_emplace, _graph.insert_or_assign, or just _graph[vertex] (to add a new entry if it does not exist, and do nothing if it does).

There is no benefit to maintaining a distinct _size variable.  As shown above, it can get out of sync with the actual size.  It is better to just call _graph.size() whenever the user calls Graph::size.

In remove_vertex, you should check the return value from _graph.erase to see if something was actually removed.  If nothing was removed there's no benefit to running any of the other code in the function.  Also, the if (it == v.second.end()) check should not return, as you avoid scanning the rest of the vertexes in _graph to remove edges that connect to the vertex that was just removed.  Alternatively, you can just replace that whole loop body with a call to either v.second.remove or v.second.remove_if.  (The same change can be made in remove_edge.)


Assign value of nested array as array key

I suppose the result you want to have is this:

    Array
    (
        [1] => Array
            (
                [stuff] => values
                [units] => Array
                    (
                        [12] => Array
                            (
                                [stuff] => values
                            )
                        [41] => Array
                            (
                                [stuff] => values
                            )
                    )
            )
    )

In this case you can use the code:

    public function fixArray($originalBatches) {
        $batches = array();
        foreach($originalBatches as $batch) {
            $units = array();
            $batch_id = $batch['batch_id'];
            unset($batch['batch_id']);
            foreach ($batch as $key => $value) {
                if (is_numeric($key) && !empty($value['unit_id'])) {
                    $units[$value['unit_id']] = array_slice($value, 1);
                    unset($batch[$key]);
                }
            }
            $batches[$batch_id] = array_merge($batch, array('units' => $units));
        }
        return $batches;
    }

Still the use of the 2 foreach is not a very good practice. You can change the code accordingly to use array_walk. This would be much faster.


This is in addition to what @tim already said.

The dumpList method takes a List,
and then you make 2 .get(i) calls in every iteration of the loop.
Keep in mind that the List interface doesn't ensure random access.
For example I can call this method with a LinkedList parameter,
in which case the .get(i) calls will be costly.
Either change the method parameter to ArrayList or similar random access list,
or change the way you iterate (I recommend), for example like this:

private static void dumpList(String string, List<Object> list) {
    int i = 0;
    for (Object item : list) {
        if (item instanceof List) {
            dumpList(string + i, (List) item);
        } else {
            System.out.println(String.format("%s%d %s", string, i, item));
        }
        ++i;
    }
}

Instead of doing if (item instanceof String) and then if (item instanceof List),
it's better to do if (item instanceof List) and an else.
This solves 2 problems at once:

Adds support for other element types, not only String and List,
which otherwise would have been ignored
The second if should have been either an else if or an else,
because if the first if was true, it's pointless to evaluate the second

I changed the string + i + " " + l.get(i) to the (in my opinion) more readable String.format("...", ...) style.

Finally, I renamed l to list.
Single-letter variable names are acceptable as loop counters, like i, j, k,
otherwise it's better to give meaningful names.


Version 2 - print new even-length arrays from two arrays

It's unclear to me why you didn't chose to use a tree. From your example you know:

A[0] has the children B[0:].
A[1] has the children B[1:].
A[2] has the children B[1:].
B[0] has the children A[2:].
B[1] has no children.
B[2] has no children.

From this you should be able to see that you'll just have to walk the tree to get the values.

To get all the values you walk the tree with the roots being all the values in A. And you filter odd results.

class Node:
    def __init__(self, value):
        self.value = value
        self.children = []

    def walk(self, path=None):
        path = (path or ()) + (self.value,)
        yield path
        for child in self.children:
            yield from child.walk(path)

def solution(A, B):
    A = [Node(a) for a in A]
    B = [Node(b) for b in B]

    for parents, children in ((A, B), (B, A)):
        for parent in parents:
            parent.children = [
                child
                for child in children
                if child.value > parent.value
            ]

    for start in A:
        for values in start.walk():
            if len(values) % 2 == 0:
                print(values)


I would consider refactoring direction into an enum, instead of a magic number. This would allow to encapsulate the related logic in this type.

It might look like that:

    enum Direction {
        UP(0, 1),
        RIGHT(1, 0),
        DOWN(0, -1),
        LEFT(-1, 0);

        final int xVector;
        final int yVector;

        private final Direction FIRST = Direction.values()[0];
        private final Direction LAST = Direction.values()[Direction.values().length];

        Direction(int xVector, int yVector) {
            this.xVector = xVector;
            this.yVector = yVector;
        }

        Direction rotatedLeft() {
            return this == FIRST
                    ? LAST // cycle complete
                    : Direction.values()[ordinal() - 1]; // previous value
        }

        Direction rotatedRight() {
            return this == LAST
                    ? FIRST // cycle complete
                    : Direction.values()[ordinal() + 1]; // next value
        }
    }

And then the Robot code becomes (including some subjective clean up, unrelated to the object-oriented aspect itself):

class Robot {
    private int x;
    private int y;
    private Direction currentDirection;

    Robot() {
        this(0, 0);
    }

    Robot(int x, int y) {
        this.x = x;
        this.y = y;
        currentDirection = Direction.UP;
    }

    public void move(String moves) {
        for (char code : moves.toCharArray()) {
            // a matter of taste, I like to extract logic
            // out of looping constructs for clarity
            move(code);
        }
    }

    private void move(char code) {
        switch (code) {
            case 'R': {
                currentDirection = currentDirection.rotatedRight();
                break;
            }
            case 'L': {
                currentDirection = currentDirection.rotatedLeft();
                break;
            }
            case 'F': {
                // you'd call the println thing here.
                // as it's not part of the requirements I assumed it to be a debugging artifact
                this.x += currentDirection.xVector;
                this.y += currentDirection.yVector;
                break;
            }
        }
    }

    public void reset() {
        x = 0;
        y = 0;
        currentDirection = Direction.UP;
    }

    public String position() {
        return x + ":" + y;
    }
}

I think this is more object-oriented, and also an improvement.

You could take it one step further and encapsulate the x and y coordinates in a little standalone class (Position). Like so:

    class Position {
        static final Position DEFAULT = new Position(0, 0);

        final int x;
        final int y;

        public Position(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public Position movedInto(Direction direction) {
            return new Position(x + direction.xVector, y + direction.yVector);
        }

        @Override
        public String toString() {
            return x + ":" + y;
        }
    }

Then in the Robot class you replace x and y fields with Position position, and you no longer recalculate the position in the Robot class, as you can simply go:

case 'F': {
    position = position.movedInto(currentDirection);
    break;
}

in the move method.

Plus:

    public void reset() {
        position = Position.DEFAULT;
        currentDirection = Direction.UP;
    }

    public String position() {
        return position.toString();
    }

Yet another idea would be to encapsulate the move codes themselves into a class or classes. It's sometimes hard to say where to draw the line, as making code more and more OO comes at the cost of more boilerplate, and can be a form of overengineering.

I admit I haven't tested my refactored version, I only approached the question in terms of code design.


Socket.io wrapper for an app with ReactJS components

It looks like you've written the code that already exists.

  this way multiple subscriptions for the same events can be avoided but all the interested React components can be notified on an event update

Why would you want to avoid this? There is no overhead in a function call. In fact, this is exactly how Socket.io client works (based on Emitter component):

Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
  this._callbacks = this._callbacks || {};
  (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
    .push(fn);
  return this;
};

Then there is this hack. If the client will connect in less than a second, you'll miss 'connect' event:

setTimeout(function(){  // register a little late to avoid multiple callbacks.
    socket.on('connect', function(){
        console.log('connect fired');
        for(var i=0;i<callOnConnect.length;i++){
            callOnConnect[i]();
        }
    });
},1000);

Last, it's a good practice to unsubscribe from events in componentWillUnmount. Your wrapper doesn't allow this.


Using a structure and waitgroups is silly for something this simple.
Just make two channels and fire off two goroutines. You don't care which one finishes first just read from both channels in whatever order is convenient (or even do something like someOtherFunction(<-c1, <-c2)).

E.g.:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    c1 := make(chan float64, 1)
    c2 := make(chan int, 1)

    go func() {
        // simulate spending time to do work to get answer
        time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
        c1 <- 1.2
    }()

    go func() {
        time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
        c2 <- 34
    }()

    x := <-c1
    y := <-c2
    fmt.Println(x, y)
}

https://play.golang.org/p/Qoh5IvFROo


user673679 already mentioned that a lot of string copying is going on. Indeed, std::string_view could be used here to just keep references to the original input strings, saving both time and space.

Give your variables meaningful names

Your variable names should tell you something about the contents of the variable, not of the type of the variable. So don't write std::vector<std::string> vector_of_strings, but give it a more descriptive name such as input if it's the input to your program, and possibilities instead of vector_of_vector_of_strings.

Also avoid variable names that are too alike, such as separator and sep in your main() function. In this case, you can avoid it by writing the code like so:

bool first = true;

for (const auto &word: sentence) {
    if (first)
        first = false;
    else
        std::cout << " ";

    std::cout << word;
}

Don't abbreviate too much, just write carthesian_product instead of cart_product. The latter abbreviation is not common and might confuse others that do not know that you mean Carthesian product here.

Use more algorithms?

Since you are already using some of the C++ standard library algorithms, why not use more? For example, instead of writing a for-loop to create the vector of vector of strings, write:

std::transform(input.begin(), input.end(),
               std::back_inserter(possibilities),
               [](std::string words){
                   return split(words, '|');
               });

Although arguably, it doesn't improve readability much here.

Split off more functionality into their own functions

The main() function could be cleaned up and made more readable if you moved some of its parts to properly named functions. For example, instead of creating the vector of vector of strings inline, it would be nice it you could just write:

auto possibilities = split_possibilities(input);

Also, consider creating a join() function, so writing out all the permutations could be written as:

for (auto &sentence: sentences) {
    std::sort(sentence.begin(), sentence.end());

    do {
        std::cout << join(sentence, " ") << '\n';
    } while(std::next_permutation(sentence.begin(), sentence.end());
}


PostgreSQL simple query with repeated function calls

I think this part:

CASE WHEN a.idpai IS NULL THEN a.nome
ELSE concat(a.nome, ' (', b.nome, ')')
END AS nome

Can be replaced with:

CONCAT(a.nome,  ' (' || b.nome || ')') AS nome

If b.nome is NULL, then "' (' || b.nome || ')'" will also be NULL (concatenating strings using '||' with NULL values will result in NULL. CONCAT() ignore null values, so will return only a.none in this case

In other words: if b.nome is present, it will output "a.nome (b.nome)", otherwise "a.nome"

You can test it yourself, here's my sqlfiddle:

http://sqlfiddle.com/#!1/d41d8/744/0

Also, you can try to use a subselect to prevent having to repeat this CONCAT;

http://sqlfiddle.com/#!1/a9571/7/0

I haven checked if this improves performance, but it reduces the amount of repeated code and may be better maintainable


Before you do other things you should separate and encapsulate, this means you should put certain logic into their own methods that specialize in doing only one thing. If you put e.g. the loops in such method methods, you won't need any comments. Here's an example of how it could be done with C# 7. Also notice the changed names. There's no need for the a/an/the prefixes.

This is just a start and there is much more to improve. I left it out intentionally.

public void CreateCsv(DataTable data, string path, string title)
{
    string CreateFileName() => string.Concat(path, title, @"-", guid, @".csv");

    void WriteHeader(StringBuilder csv)
    {
        var header = new List<string>();
        foreach (var column in data.Columns.Cast<DataColumn>())
        {
            header.Add(column .ColumnName);
        }
        csv.AppendLine(string.Join(Delimiter, header));
    }

    void WriteData(StringBuilder csv)
    {
        foreach (var row in data.Rows.Cast<DataRow>())
        {
            var values = new List<string>();
            foreach (var column in data.Columns.Cast<DataColumn>())
            {
                values.Add(row[column.ColumnName].ToString());
            }
            csv.AppendLine(string.Join(Delimiter, values));
        }
    }

    string WriteCsv()
    {
        var csv = new StringBuilder();
        WriteHeader(csv);
        WriteData(csv);
        return csv.ToString();
    }

    File.WriteAllText(CreateFileName(), WriteCsv());

    Console.WriteLine();
    Console.WriteLine(String.Concat(@"just completed: ", title, @"-", this.guid, @".csv"));
}


A generic REST API consuming Python library

import requests, json

class RestConsumer(object):

    def __init__(self,base_url,append_json=False,**kwargs):
        self.base_url = base_url
        self.uriparts = []
        self.append_json = append_json
        self.kwargs = kwargs

Since you treat attributes "special", I recommend putting _ in front of these attributes so that are clearly offset.

    def __getattr__(self,k):

I recommend not using the random letter k for the name.

        if k=='spc':
            return self.spc

__getattr__ only gets invoked if the attribute cannot be found. Since spc will be found this won't ever get used.

        if not k[0] == '_':
            self.uriparts.append(k)
        else:
            if k[1:3]=='in':
                self.uriparts.append(k[3:])

What's the point of this rule? _infoo means foo?

            elif k[1:3] == 'uh':
                self.uriparts.append(k.replace('_','-'))

uh?

        return self

I don't like the way you've implemented this. Accessing attributes modifying the object's state is deeply counter-intuitive.

    def spc(self,k):
        self.uriparts.append(k)
        return self

spc is not a clear name. Its hard to guess what it means.

    def __call__(self, **kwargs):
        uri_constructed = '/'.join(self.uriparts)
        self.uriparts = []
        self.uri_constructed = "%s%s"%(uri_constructed,'.json') if self.append_json else uri_constructed
        self.url = '/'.join([self.base_url,self.uri_constructed])
        return self.get(self.url,**kwargs)

    def get(self,url,**kwargs):
        print url
        r = requests.get(url,**kwargs)
        return json.loads(r.content)

    def post(self,**kwargs):
        r = requests.post(**kwargs)
        return json.loads(r.content)

get prints while post doesn't. Probably neither should be printing, a log facility might be useful.

The way you've designed this, some useful things won't work:

public_timeline = twitter.statuses.public_timeline
while True:
      print public_timeline()

or

user = s.users.spc(55562)
print user.questions.unanswered()
print user.questions.answered()

I suggest that instead of modifying the object, you return new objects. That way it will work in an intuitive manner.

Instead of spc I suggest that you provide a __getitem__. That way you can do:

 s.users[55562].questions.unanswered()

Which I think will make it cleaner.


Average across direction-specific average speeds and probabilities

The biggest issue with this code is it iterates over a DataFrame. Iterating over a DataFrame negates any performance improvements gained by using pandas. As much as possible, use operations that apply to the entire Series or an entire DataFrame at once. Allow the C code to do the looping for you so the data doesn't get pulled into slow Python objects.

There is no reason to download the data into a file using wget. This data can be downloaded directly into memory, and pandas supports http urls.

Look at where you place comments before blocks of code. These are perfect places to split up your code into functions.

"""Process unweighted wind data to file."""
import pandas as pd

URL = ('https://raw.githubusercontent.com/scls19fr/windrose/master/samples/'
       'amalia_directionally_averaged_speeds.txt')
OUTPUT_PATH = 'wind_rose.csv'

def load_wind_data(data_url):
    """Load wind data from url into a dataframe.

    Args:
        data_url(str|io):
            A URL, path, or buffer containing wind data.

    Returns:
        A dataframe containing wind data
    """

    dat = pd.read_csv(data_url, sep=r'\s+', header=None, skiprows=1,
                      names=['direction', 'average_speed', 'probability'])
    return dat

You can use the names argument of read_csv instead of setting columns.
wget is not used and the url is passed into read_csv since read_csv supports http.

def average_wind_data(dat):
    """Average and weight wind data.

    Args:
        dat(pd.DataFrame):
            A dataframe containing unweighted wind data.
    Returns:
        A dataframe containing weighted, averaged wind data.

    1. average frequency across speeds
    2. compute average speed weighted by frequencies
    (the scheme is to average across both midpoints. this
     shift the centers by 2.5 degrees and bin by 10)
    """

    avg_df = pd.DataFrame()
    # shift(-1) leaves the NaN value at the end of the dataframe
    adj_sum_dat = dat + dat.shift(-1)
    avg_df['direction'] = (dat['direction'][::2] + 2.5).values
    avg_df['probability'] = (adj_sum_dat['probability'][::2]/2).values
    unweighted_speed = dat['direction'] * dat['average_speed']
    adj_speed_sum = unweighted_speed + unweighted_speed.shift(-1)
    avg_df['speed'] = (adj_speed_sum/adj_sum_dat['direction'])[::2].values
    return avg_df

Use shift() on Series or DataFrame objects to do vector operations on adjacent data. Use slice notation to get even data points ([::2] means all the entire index stepped over by 2). Do vector operations on entire series instead of each item on the series. This section of code is about 6x faster than the original iteration code.

def main(input_url, output_path):
    """Load wind data at input_url and save processed data to csv.

    Args:
        input_url(str|io):
            Location of wind data.
        output_path(str):
            File location to save processed wind data.
    """
    dat = load_wind_data(input_url)
    processed_df = average_wind_data(dat)
    processed_df.to_csv(output_path)

if __name__ == "__main__":
    main(URL, OUTPUT_PATH)

IO should be done at the top level of execution.


JavaScript function to convert an array to an array of strings (formatted)

First impressions:

too much nesting, too many nested returns
inconsistent style, inconsistent naming

You already recognized the potential for refactoring. The simplest possible technique for refactoring is renaming variables:

Your code currently uses camelCase (printPriceList, samePrice), underscores (category_id, price_min) and something else (pcontent). For me, it doesn't matter that much which style you chose as long as you use it consistently and as long as you use descriptive names.

Other stylistic suggestions:

It is a habit of mine to split complex chains such as...

const result = elements
    .filter(...)
    .map(...);

...into separate assignments with self-documenting names:

const blabla = elements.filter(...);
const result = blabla.map(...);

I prefer to terminate statements with semicolons instead of having to think about the rules of JavaScript's automatic semicolon insertion.
Instead of the 'print' prefix which signals some kind of active output e.g. to a stream, you could use e.g. 'format'.

The most helpful refactoring is to extract code fragments that can be grouped together into their own functions:

Printing a product price:

function print_product_price({price_min, price_max}) {
    if (price_max === 0) {
        return 'free';
    } else if (price_min === price_max) {
        return `$${price_min}`;
    } else {
        return `$${price_min} - $${price_max}`
    }
}

Printing a product:

function print_product(product) {
    const price = print_product_price(product);
    return `${product.title} (${price})`;
}

Printing a category:

function print_category(category, products) {
    const category_products = products.filter(product => product.category_id === category.id);

    const category_rows = [
        `*${category.title}*`,
        ...category_products.map(print_product)
    ];

    return category_rows.join('\n');
}

Using Lodash, the above .filter expression could be written as _.filter(products, { 'category_id': category.id }) - suggested by @Gerrit0.
And finally printing the price list:

function print_price_list(categories, products) {
    return categories.map(category => print_category(category, products));
}

As you can see, due to extracting those functions, no secondary or deeper nesting is needed.


Reflecting and counting points on a 2D grid

Instead of initializing your arrayList when you create the instance of the class, do it when you have the num_of_points value from the scanner.

arrayList = new ArrayList<Point>(num_of_points);

This will mean the array list doesn't need to resize itself (potentially slow operation). In the example you have given with only 4 points it won't make any difference, but if there were a larger number of points you may save some time!

Where you get the value from the scanner char c you trim the value, which you shouldn't need to do as the Scanner should stop when it sees a delimiter (in this case, a space).

In the queryC method, you have a for loop...

for (int b = 0; b < len; b++) {
    pnt = arrayList.get(b);
}

...that does nothing, so you can remove it.

A few notes on code style...

In the main method your for loops go from X down to 0, but in the query methods you go from 0 up to X. Just wondering why?
You also use (0 - pnt.x) where you could use -pnt.x.

Hope this helps.


Use same case prefix for type "Stack" and functions "stack" --> "gStack" or whatever.
Use correct print specifier.  This implies that either OP does not have all warnings enabled or is using a weak compiler.  Suggest remedying that.

// printf("Size of stack is %d.\n", s1.stackSize);
printf("Size of stack is %u.\n", s1.stackSize);

Use consistent sign-ness

// int newStackSize;
unsigned newStackSize;

In push(), newStackSize test should be corrected or eliminated.

// if (temp == NULL || newStackSize == 0)

if (temp == NULL && newStackSize > 0)

// or if confident newStackSize will never be 0 here
if (temp == NULL)

Silently failing push() due to OOM is a concern.
pop() should do similar OOM protection as pop().  Even though it sounds silly that reducing memory usage should ever fail.
Consider putting all memory allocation into one helper function.  (BTW: destroy() did not free p->elementData.

static int stack_realloc(int **ptr, unsigned *oldsize, unsigned newsize) {
  if (newsize > 0) {
    void *newptr = realloc(*ptr, newsize);
    if (newptr == NULL) return 1; // fail
    *ptr = newptr;
  }
  else {
    free(*ptr);
    *ptr = NULL;
  }
  *oldsize = newsize;
  return 0; // success;
}

// push()
unsigned newStackSize = p->stackSize + p->capacityIncrement;
if (stack_realloc(&p->elementData, &p->stackSize, newStackSize);

// pop()
// change from == to >=
if(p->stackSize - p->elementCount >= p->capacityIncrement / 2 + p->capacityIncrement) {
  unsigned newStackSize = p->stackSize - p->capacityIncrement;
  // No problem is realloc failed, just continue with current stack
  stack_realloc(&p->elementData, &p->stackSize, newStackSize);

// destroy()
stack_realloc(&p->elementData, &p->stackSize, 0);
// Do not free `p`.
// free(p);


I find a couple of the names misleading. What you call gcf I have only previously heard called HCF (highest common factor) or, more commonly, GCD (greatest common divisor). So I expect that function to be called gcd, and the one which is called gcd to be reduce. Of course, you also have a function called reduce which is basically just gcd with a different calling convention. I would be tempted to move the sign-handling into gcd, eliminate reduce, and then rename.

I'd also prefer to call invert something like recip (for reciprocal). It's less likely to cause a name collision, and also IMO describes better what it does.

function reduce(f0) {
  var f = gcf(Math.abs(f0.n), f0.d);
  f0.n /= f;
  f0.d /= f;
  return f0;
}

I presume that you modify the input and also return it because you want to support a fluent style, but I can't actually see any evidence of that here. I've already suggested refactoring this function away, but if I hadn't then I would suggest making it return a new object and treating fraction objects as immutable. That favours maintainability and probably also helps JIT.

function multiply(f1, f2) {
  return createFraction(
    f1.n * f2.n,
    f1.d * f2.d
  );
}

This function is worth special-casing in a fraction implementation. You already know that each fraction is reduced, so the only common factors can be crosswise. By separately reducing (f1.n, f2.d) and (f2.n, f1.d) you can keep the intermediate values smaller and reduce the risk of overflow. (I see you've made the corresponding optimisation in add).


Logging the caller ip in a asmx web service using NLog

One possible change would be to use object initializer to set up the properties:

var logInfo = new LogEventInfo(level, logger.Name, message)
{
    Properties = { { "method", method }, { "calling_ip", calling_ip } }
};

But I'm not sure this actually improves the code much, especially since using this syntax this way is uncommon, so it can be confusing.


As Magus pointed out in the comments, making everything static can present some issues. Using these static properties in other classes makes those classes tightly coupled to the Cache class. Why should you care? Consider this class:

public class Bar
{
    public int DoSomething()
    {
        return 5 + Cache.CachedNumber;
    }
}

You've lost your ability to test DoSomething() in isolation from the rest of your code. Any time you test DoSomething(), it relies on a specific implementation of Cache. It also makes it difficult to use the Bar class with different cache types (in memory, database, file system, etc.). Ideally, Bar would look something like this:

public class Bar
{
    private ICacheProvider Cache { get; set; }

    public Bar(ICacheProvider cache)
    {
        this.Cache = cache;
    }

    public int DoSomething()
    {
        return 5 + Cache.CachedNumber;
    }
}

Now we can:

Test that DoSomething is doing its job, regardless of flaws in the ICacheProvider instance (by passing a mock ICacheProvider that always returns CachedNumber = 3, for example).
Pass in different ICacheProvider implementations that can very depending on my use case, and Bar will still work without caring about them.

Also, I would suggest not using something as vague as Cache or ICacheProvider (used for illustration). Once you start caching a lot of things, you may want to cache different properties differently, at which point your super cache class will become too large to maintain. Consider breaking it up into meaningful repositories that can implement caching however they want, or something similar.


Overall the code is quite easy to read, but it is more complicated than it needs to be.

    fractorial = {}
    for i in range(2, number + 1):
        prime_factorization = prime_factor(i)
        update_fractorial(prime_factorization, fractorial)

    print(compute_fractorial_value(fractorial))

I would expect the name fractorial to be either the final integer or the function which computes it. Perhaps fractorial_factorization would be a clearer name.

compute_fractorial_value doesn't actually do anything specific to fractorials. Perhaps compose_factorization or multiply_powers?

The algorithm used to compute the prime factorisation of the fractorial is correct, but overkill. If \$p\$ is a prime and \$a\$ is a positive integer, under what condition is \$p^a\$ a factor of the \$n\$th fractorial?

def prime_factor(number):
    primes = [2, 3, 5, 7, 11, 13, 17, 19]
    dict = {}
    i = 0
    while i < len(primes):
        p = 0
        while number % primes[i] == 0:
            number = number // primes[i]
            p += 1

        if p != 0:
            dict[primes[i]] = p

        i += 1

    return dict

Apart from the hard-coded primes, this is a standard implementation. I would suggest that p is more conventionally used to denote primes[i], so perhaps power would be a less surprising name.

def update_fractorial(prime_factorization, fractorial):
    for key in prime_factorization:
        if key in fractorial:
            if prime_factorization[key] > fractorial[key]:
                fractorial[key] = prime_factorization[key]
        else:
            fractorial[key] = prime_factorization[key]

        # Or should I replace the if/else statements with:
        #
        # if key in fractorial:
        #   if prime_factorization[key] < fractorial[key]:
        #      break
        #
        # fractorial[key] = prime_factorization[key]
        #
        # since it is shorter.

Shorter still, and more explicit:

def update_fractorial(prime_factorization, fractorial):
    for key in prime_factorization:
        if key not in fractorial or prime_factorization[key] > fractorial[key]:
            fractorial[key] = prime_factorization[key]

Although it's preferable to avoid repeating the lookup. The efficient way of doing this is

def update_fractorial(prime_factorization, fractorial):
    for key, val in prime_factorization.items():
        if key not in fractorial or val > fractorial[key]:
            fractorial[key] = val

def compute_fractorial_value(fractorial):
    value = 1
    for key in fractorial:
        value *= key ** fractorial[key]

    return value

Apart from the previous comment about the name, the only thing I'd say here is that if you really want to scale this up, multiplying lots of small numbers is best done on a tree-like basis. I.e. you pair up the numbers, multiply each pair, pair up again, multiply again, ... But that's overkill for this problem.

main()

This is half-way between the naïve approach of not defining main() at all and just dumping its contents at the end, and the "best practice" approach of

if __name__ == "__main__":
    main()

Might as well get used to the best practice approach now.


Continuously receive messages async from Azure Service Bus Queues

First, some notes:

You shouldn't be using Task.Factory.StartNew() unless you have to, Task.Run() is better.

I think you're using Task.Run() (and Task.Factory.StartNew()) and ContinueWith() too much. Only use Task.Run() when you actually need to run the code on another thread. And ContinueWith() is almost always better written using await.
If you're using it to support cancellation, you can just use ThrowIfCancellationRequested() instead.

Don't use == false, ! is much clearer.

Your your code, the processing can be Started two times. You should probably guard against that.

Your Start() and Stop() methods seems to be written with support for restarting in mind. It might be simpler to forbid that.

Now, about the structure of your code: I think a much clearer way to write your code would be to use a loop, instead of recursion. That way, your top level method can be made very clear:
while (!_cancellationSource.IsCancellationRequested)
{
    await ReceiveMessageAsync();
    await Task.Delay(TimeSpan.FromMinutes(1));
}

The ReceiveMessageAsync() method could then look like this, which is a lot shorter and much more readable:
private async Task ReceiveMessageAsync()
{
    var message = await _queueClient.ReceiveAsync(TimeSpan.FromMinutes(1));

    if (message != null)
    {
        _cancellationSource.ThrowIfCancellationRequested();
        ProcessMessage(message);
    }
}

Note that this version behaves differently than yours with regards to exceptions. In your code, if an exception happens, it's either silently ignored (if it's in ReceiveAsync()) or it just silently stops receiving (if it's in ProcessMessage()). Both are very bad and make errors hard to debug. With my code, any exception stops receiving and is reported to the top-level Task.
You should then devise some way of reporting any exceptions on that Task.
A simple solution would be to store the Task in Start() and then rethrow any exceptions in Stop(). A cleaner solution might be to change void Start() into something like Task RunAsync() and report exceptions using the returned Task.
You could also consider not stopping if some specific exception happens (e.g the server is temporarily unavailable). But that should happen only for some specific exceptions and those exceptions should be logged anyway, to help with debugging.


It's hard to say anything since it seems rather a pseudo-code. Anyway, two notes which you might find useful:

I guess you could replace the switch-case structure with polymorphism. Two useful reading:

Refactoring: Improving the Design of Existing Code by Martin Fowler: Replacing the Conditional Logic on Price Code with Polymorphism
Replace Conditional with Polymorphism

Are you sure that returning null in the default is fine? I'd consider returning an empty list (as it returns when type == null) or throwing an exception (IllegalStateException, for example) if it's a programming error. (See: The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies)


Efficiently counting '1' bits in the first n bits

first issue: you hardcode 8 as the number of bits per sizeof unit: portability says it should be CHAR_BIT which may be something else on some architectures

second issue: both members of int80 are signed, only hi should be while lo can be unsigned

if you can guarantee that offset is between 0 and 80 then you don't need to test for 0, and just document that exceeding the bounds is undefined behavior

static __always_inline __constant int32 countBitmap(int80 const bitmap, uint32 const offset) {
    int32 count = 0;
    if (offset <= sizeof (bitmap.hi)*CHAR_BIT) {
        count = POPCOUNT64(bitmap.hi >>> (sizeof (bitmap.hi)*CHAR_BIT - offset));
        // logical right shift to do away with the AND
    }else{
        count = POPCOUNT64(bitmap.hi)+
                POPCOUNT16(bitmap.lo >>> (sizeof (bitmap)*CHAR_BIT - offset));
    }
    return count;
}

here there is only 1 branch compared to the 2 you had before (possibly 3 depending on how MIN was implemented)


Generating a table based on an array of objects

TL;DR Fully functionnal example :

//Columns defines table headings and properties to be placed into the body
const columns = [{ heading: 'Name', property: 'name' }, { heading: 'Age', property: 'age' }, { heading: 'Sex', property: 'sex' }, { heading: 'Breed', property: 'breed' },]

//Data is the array of objects to be placed into the table
const data = [{ name: 'Sabrina', age: '6', sex: 'Female', breed: 'Staffordshire' }, { name: 'Max', age: '2', sex: 'Male', breed: 'Boxer' }]

const App = props =>

const Table = ({ columns, data, propertyAsKey }) =>

{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}	)}

            {data.map(item =>
                <tr key={`${item[propertyAsKey]}-row`}>
                    {columns.map(col => <td key={`${item[propertyAsKey]}-${col.property}`}>{item[col.property]}	)}

            )}

ReactDOM.render(<App/>, document.getElementById('root'))

The main thing that would highly reduce this code is the map function. This function can be applied on an array, execute a callback on every item in the array and returns a new array.

By using it you can reduce the following code :

let headerRow = [];

columns.forEach(col => {
    headerRow.push(
        <th key={`header-${col.heading}`}>{col.heading}
    );
});

Can be reduced to this with the exact same result :

const headerRow = columns.map(col => <th key={`header-${col.heading}`}>{col.heading}	)

You can now include this function directly into your JSX :

{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}	)}

And the same thing with nested mapping for the body :

    {data.map(item =>
        <tr key={`${item[key]}-row`}>
            {columns.map(col => <td key={`${item[key]}-${col.property}`}>{item[col.property]}	)}

    )}

Your full buildTable function is now reduced to the following :

buildTable = (columns, data, key) => {
    return (
        <>

{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}	)}

                {data.map(item =>
                    <tr key={`${item[key]}-row`}>
                        {columns.map(col => <td key={`${item[key]}-${col.property}`}>{item[col.property]}	)}

                )}

        </>
    );
};

If you want to go a little further you can also delete this function and embed this code in your render function JSX. I will also convert your component into a stateless function, since you are not using any state value :

const Table = ({ columns, data, propertyAsKey }) => //Deconstructs your props

{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}	)}

            {data.map(item =>
                <tr key={`${item[propertyAsKey]}-row`}>
                    {columns.map(col => <td key={`${item[propertyAsKey]}-${col.property}`}>{item[col.property]}	)}

            )}

(You may add brackets and a return statement after the arrow sign, its up to you)

It is also not required to have a fragment as a parent element in your render, as long as there is a single element, it is fine :

class App extends React.Component {
  render() {
    return (

    );
  }
}

Your App component could also be converted to a stateless component:

const App = props =>


When you ask if your first solution is faster, if you are talking about theory it isn't faster. To understand why you need to understand the the difference between big O complexity and actual run time. For the purposes of this question, it is important only that you realize that big O complexity does not guarantee that a piece of code with O(n^2) run time will run faster than O(n) for all inputs merely that for some very large inputs O(n^2) will be faster. More exactly, Big O complexity merely talks about the growth rate of a function at really large values. Without getting into it too much you can imagine that the if we have x^2 and 1000000x, I can guarantee that at some input x^2 will surpass 1000000x. Similarly, if I have x^2 + x I can guarantee that at some  point the x^2 term will be so much bigger than the x term that the any increase in in our input will essentially just increase the function by approximately x^2.  If that doesn't make sense, then I would suggest brushing up on big O here https://medium.com/karuna-sehgal/a-simplified-explanation-of-the-big-o-notation-82523585e835 .

Now for your problem, the big O complexity of the hash map based solution is O(n) the big O for the brute force double loop solution is O(n^2). Now as mentioned about big O does not guarantee that an O(n^2) piece of code will always run faster that an O(n) piece of code for all inputs. Big O is a mathematical guarantee only for large inputs. All big O says is that for some large input O(n^2) will be faster O(n). Let me give you a specific example of why despite a greater big O the double loop solution might be faster for a constrained input. let's say that your two loop solution runs in n^2 time exactly and your hash map solution runs in 1000000000*n time.  Well technically your hash map solution would benchmark much much slower for reasonable sized inputs, but eventually if the input were big enough then your hash map solution would run faster.  Now, maybe you only care about the performance for a constrained sample size. That's great. This is why you will always have to run a benchmark to compare solutions. Big O is not meant as a tool to guarantee that a certain piece of code will run faster for all inputs, only as a tool to theoretically reason about performance for extremely large inputs.  Knowing the time complexity in O notation, won't give you any sort of idea what might be faster for a given constrained input size.  That's why in the real world, understanding big O is important, but it is also very important to run performance benchmarks based on how big you actually expect your input to get.  I've repeated this central theme in different ways throughout this post but I will summarize again here Big O only guarantees run time for some extremely large input (think as the limit of your input goes to infinity) it says absolutely nothing about some constrained input.  I could reasonably come up with a Big O problem where an O(n^2) piece of code would never run faster than an O(n) piece of code given the constrained of the amount of memory on your computer. Basically, use big O to get a general idea of run time when writing your code, and then if you see some performance issues benchmark to find improvements.

Now in the case of this question, someone with a little more understanding of what's actually happening in Go might be able to tell you exactly what operation is making your hash map solution slower for those inputs. My guess... when you call make(map[int]int, 0) you are allocating space on the heap, which is likely taking a good amount of time.


Pythonic data processing? Should I use an iterator?

Firstly, a loopless solution (not actually tested)

big_gaps = np.diff(timestamps) >= big_gap

As you did

front_gaps = np.logical_and.accumulate(big_gaps)

This produces an array which is True until the first False in big_gaps.

end_gaps = np.logical_and.accumulate(big_gaps[::-1])[::-1]

We do the same thing again, but this time we apply on the reversed array.

big_gaps = np.logical_or(front_gaps, end_gaps)

Now that we have arrays for the front and end portions, combine them

n = np.sum(front_gaps), np.sum(end_gaps)

Take the sums of the gaps arrays, 1 = True, 0 = False to figure out the values for n

keep = np.logical_not(big_gaps)

Invert the logic to figure out which ones to keep

return timestamps[keep], values[keep]

Produce your actual values

A few comments on pieces of your code

@staticmethod
def _trimmed_ends(timestamps, values, big_gap = 60*60*24*7):

I'd make a constant: ONE_WEEK = 60*60*24*7, as I think it would make this clearer

big_gaps = (np.diff(timestamps) >= big_gap)

You don't need those parens

n = (0, 0)

This is a tuple here, but you modify it later. That won't work.

And finally, no you shouldn't use an iterator, for the reasons you mention.


First, a word on naming:

The name you've chosen for your type, _arraylist is a bad name for a library interface
type. Names starting with _ are not pleasant to work with in user code. They are commonly
used inside library internals. Better names would be ArrayList or array_list.

Actually, in your usage example, you have ArrayList. Does this mean that in the header,
which is not included here, you have something like this?

typedef _arraylist ArrayList;

If you did define an opaque type in the header, like above, that would be a good practice.
But then you should not use any reference to _arraylist in your code. Use always the typedef'd name to avoid confusion.

The function name prefix should also follow exactly the name of the type, so for ArrayList all functions should be prefixed the ArrayList_, e.g.:

ArrayList * ArrayList_create();

Also, I would suggest that you avoid tightlypacked names, like in arraylist_getsize(). Adding an
underscore to separate words makes them a lot more readable. E.g.: ArrayList_get_size().

Problems with memory:

Lets look at arraylist_create():

struct _arraylist *arraylist_create() {
    struct _arraylist *list = malloc(sizeof(struct _arraylist));
    assert(list != NULL);
    list->size = 0;
    list->data = calloc(2, sizeof(void *));
    assert(list->data != NULL);
    list->data[0] = NULL;
    return list;
}

First thing unusual here is the assertions. Assertions are not the proper way to
handle a memory allocation failure. Plus, they are commonly disabled on release builds,
so on release, if you'd happen to run out of memory, the program would just crash silently.
You should probably return a NULL in this case (maybe also log to stderr) and let the caller handle this error as he/she sees fit.

Second problem here is with calloc(). You are allocating 2 void pointers, however, size is set to zero.
I don't really get the point of this. Since your structure is more like and array of arrays then a list,
what you should do is allocate the array of pointers with some predefined default size, then allocate the
individual arrays as needed. Growing the array of pointers on demand. How arraylist_create() should look like:

ArrayList * ArrayList_create() {
    ArrayList *list = malloc(sizeof *list);
    if (list == NULL) {
        return NULL;
    }

    list->size = 0;
    list->data = calloc(INITIAL_BASE_ARRAY_SIZE, sizeof(void *));
    if (list->data == NULL) {
        free(list); // Don't leek memory here!
        return NULL;
    }

    return list;
}

Another big memory issue is the constant re-allocations done by arraylist_add() and arraylist_remove().

Remove should not shrink the sequence. Keep that space around if the array grows again in the future. You can add an explicit way to let the user shrink the storage if necessary (a la std::vector::shrink_to_fit()).

Adding to the array can be made to run in amortised-constant time if you pre-allocate storage with a larger size then the requested. (Again inspired by the STL vector).

sizeof mistake:

This will not return what you expect:

size_t arraylist_getsizeof(struct _arraylist *list) {
    /* Returns the size of the internal array in memory */
    return sizeof(*list->data);
}

The sizeof operator always returns the size of the type it is applied to.
It cannot infer the size of an array pointed by a pointer, because it is a
compile-time operation. arraylist_getsizeof() will always return the same value,
the size of a void pointer, which will be 4 or 8, depending on the architecture.

Use assertions to check for invariants:

You should assert that the *list parameter of every function is valid. This is a precondition of every function, they cannot work without a valid ArrayList instance, so you should assert that once the function enters.

Miscellaneous:

You don't need to check if the pointer is null before freeing it. In arraylist_deallocate() the if (list->data != NULL) check is uneeded.

arraylist_deallocate would be more symmetric with arraylist_create if named arraylist_destroy.


It looks like you need a variation of the prefix sum algorithm applied to your list. In Scala this can be accomplished with scan:

val xs = List("home", "mens", "clothing", "jackets")
xs.scan("")(_ + "/" + _).tail


Notify owner of post and other commenters

First of all I would add a method to Post:

# app/models/post.rb
def notify_others_about_new_comment(comment)
  recipients = [user]               # the author of the original post
  recipients << users               # people that wrote a comment
  recipients.delete(comment.user)   # writer of the new comment

  recipients.uniq.each do |recipient|
    Notification.create(
      recipient_id: recipient.id,
      sender_id: comment.user.id,
      notifiable: self,
      action: 'commented'
    )
  end
end

And just call that method in your controller:

if @post_comment.save
  @post.notify_others_about_new_comment(@post_comment)
  #...
end


Using XSLT to turn content of WYSIWYG stored in XML into HTML

You should change your mindset when working with XSLT: look at it as a functional language, where you declare rules for the transformation of elements. Think about it in terms of events: when a p element is found in input, I expect this and that in the output.

First, regarding the definition of your data. You should ask for (or create) a more formal description of the data. There are different formats available to describe the structure (grammar), DTD and XML Schema being the more common. There are more simple alternatives such as RELAX NG and Schematron.

My guess, from your stylesheet and your descriptions:

there is always a <system-index-block> at the top
there is a list of <story> elements in <system-index-block>
there is mixed HTML contents in <story>, with
,
,
, and text allowed

I am not sure about the last part: is it possible to have both text and div or paragraph at the top level in a story?

<story>
  Text before a
Paragraph
 in between or
Div
 even after ?
</story>

You should break your unique template rule into several template rules, one or several for each element. Then to direct the flow from rule to rule, do not use for-each but rather apply-templates:

<xsl:template match="system-index-block">

  <xsl:apply-templates />
</xsl:template>

<xsl:template match="story[p|div]">
   <xsl:apply-templates mode="copy" />
</xsl:template>

<xsl:template match="story">

    <xsl:apply-templates mode="copy" />

</xsl:template>

Note that I used the mode "copy" above: you can now create different rules for the same nodes depending on the mode, for example:

<xsl:template match="text()" />

<xsl:template match="text()" mode="copy">
    <xsl:copy />
</xsl:template>

Also, you will probably get into trouble because you only declared a namespace for the xsl prefix. You typically need a prefix/namespace declaration for the input and output formats. You will then need to use the prefix in match/select expressions and in the tag names for the output, for example, with input prefix bound to your input namespace and html bound to the html namespace:

<xsl:template match="input:story">

    <xsl:apply-templates mode="copy" />

</xsl:template>

To go further, here are pointers that you will probably find useful:

Namespaces and XSLT Stylesheets
Identity transformation


To streamline the permission handling you may want to wrap ACE creation in a function and set the ACL just once at after all ACEs were added:

function New-Ace {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$true, Position=0)]
    [Security.Principal.NTAccount]$Account,
    [Parameter(Mandatory=$false, Position=1)]
    [Security.AccessControl.FileSystemRights]$Permissions = 'ReadAndExecute',
    [Parameter(Mandatory=$false, Position=2)]
    [Security.AccessControl.InheritanceFlags]$InheritanceFlags = 'ContainerInherit,ObjectInherit',
    [Parameter(Mandatory=$false, Position=3)]
    [Security.AccessControl.PropagationFlags]$PropagationFlags = 'None',
    [Parameter(Mandatory=$false, Position=4)]
    [Security.AccessControl.AccessControlType]$Type = 'Allow'
  )

  New-Object Security.AccessControl.FileSystemAccessRule(
    $Account, $Permissions, $InheritanceFlags, $PropagationFlags, $Type
  )
}

$domain = 'DOMAIN'

$acl = Get-Acl $path

'Administrators', "$domain\Domain Admins" | ForEach-Object {
  $acl.AddAccessRule((New-Ace $_ 'FullControl'))
}
$acl.AddAccessRule((New-Ace "$domain\FS-$NAME-RW" 'Modify'))
$acl.AddAccessRule((New-Ace "$domain\FS-$NAME-R" 'ReadAndExecute'))

Set-Acl $path $acl

Other improvements might include determining the administrators and domain admins group names independent of the system's locale by their well-known SIDs, e.g.:

$administrators = ([wmi]"Win32_Sid.Sid='S-1-5-32-544'").AccountName

$domain_admins  = Get-WmiObject -Class Win32_Account |
                  Where-Object { $_.SID -like '*-512' } |
                  Select-Object -Expand Caption

Another thing you could do is map names to permissions like this:

$permissions = @{
  'Administrators'        = 'FullControl'
  "$domain\Domain Admins" = 'FullControl'
  "$domain\FS-$NAME-RW"   = 'Modify'
  "$domain\FS-$NAME-R"    = 'ReadAndExecute'
}

and use the hashtable as input for the ACE creation:

$permissions.Keys | ForEach-Object {
  $acl.AddAccessRule((New-Ace $_ $permissions[$_]))
}

Of course this implies that all ACEs have the same type and flags, otherwise you'd have to use a more elaborate data structure.


Now, I don't know much about webscraping, but I don't think there's much you can do to make this method of going about it any faster. You're restricted by how fast Internet Explorer can retrieve the website. There's also the fact that VBA is a single threaded language. So, multi-threading is out of the question.... or is it?

I would tackle this problem a little differently. I would create a swarm of VBScript scripts to retrieve the data you're after. This works by using VBA to writing many VBScript files to a drive location and using a shell to execute them. Each VBScript is responsible for writing the data it finds to the appropriate cell in Excel.

You can find a reasonable example of this (including a workbook with the code) here courtesy of Daniel Ferry.


Generic toString() for JPA base entity class

So, there are a couple of things that can be done with this. First, use methods! Short, well-named methods can make it much easier to read the code. Second, use short-circuiting logic. continue is your friend. Most of your comments don't really contribute much, or can be obviated with good method names. You can also set the size of the ArrayList at creation time, because you know how many fields you're going to be dealing with. In my opinion, something like this looks a lot cleaner:

@Override
public String toString() {

    final Field[] fields = this.getClass().getFields();
    final List<String> fieldsToPrintOut = new ArrayList<String>(fields.length);

    AccessibleObject.setAccessible(fields, true);

    for (final Field field : fields) {
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }

        final Object fieldValue;
        try {
            fieldValue = field.get(this);
        } catch (final IllegalAccessException ex) {
            logger.catching(ex);
            continue;
        }

        if (!isCollection(field)) {
            fieldsToPrintOut.add(field.getName() + "=" + fieldValue);
            continue;
        }

        if (!isParameterized(field) || !isBaseEntity(field)) {
            continue;
        }

        final List<String> ids =
                ((Collection<BaseEntity>) fieldValue).stream().map(p -> p.getId().toString()).collect(Collectors.toList());
        fieldsToPrintOut.add(field.getName() + ids);

    }
    return MessageFormat.format(this.getClass().getSimpleName() + fieldsToPrintOut);
}

private static boolean isCollection(final Field field) {
    return Collection.class.isAssignableFrom(field.getType());
}

private static boolean isParameterized(final Field field) {
    return field.getGenericType() instanceof ParameterizedType;
}

private static boolean isBaseEntity(final Field field) {
    final Class<?> genericType =
            (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];

    return BaseEntity.class.isAssignableFrom(genericType);
}


Maximum product of a triplet in array in linear time

Your code is straightforward and easy to read. It also doesn't do anything unnecessary. You chose the variable names perfectly, got the indentation correct and provided good test cases. Since you mentioned in the title that there code needs to run in linear time, it is perfect.

I don't see where you throw the exception to make the first of your tests succeed. I bet that test fails currently. That test also imports InvalidArgumentException from a strange package instead of using the standard IllegalArgumentException. Are you coming from a .NET background?

Your code is rather long. If you prefer maintainability and readability over a few nanoseconds of execution time (complexity \$\mathcal O(n\log n)\$), you should rather write:

int[] nums = numbers.clone();
Arrays.sort(nums);

int n = nums.length;
return Math.max(
    nums[n - 3] * nums[n - 2] * nums[n - 1],
    nums[0] * nums[1] * nums[n - 1]);


nope! [grin]

this is almost entirely about style, not performance. you will note that most points are about readability ... the following line is quite true ...

better readability gives better understanding gives better maintainability.

[1] never use aliases or short names in a script that will be shared or reused
why? code is READ far more often than written, so make it easy to read.

[2] use consistent indents
your indentation makes it needlessly unclear where each stage begins and ends. see [1] for why that is important.

[3] you need comments describing the purpose of the code
again, someone who reads your code next month [perhaps you] needs some sort of idea as to the intent of your code.

[4] avoid long lines
you have two lines that run well off to the right. since PoSh knows that things like pipe symbols WILL be followed by more stuff, you can wrap after such. that also applies to commas, open parens, and other such "more to come" items.

why bother? once again, it is about reading. there is a reason why most wide-format publications to use multiple columns ... people tend to read more comfortably when the lines require minimal side-to-side eye movement. that works out to about 80 to 100 chars per line.

make use of the vertical space you have available. folks scan vertically somewhat more easily than horizontally.

[5] use consistent variable case
you use lowercase and PascalCase. try to stick with ONE such style ... and PascalCase is the one usually recommended.

[6] read the officially referenced unofficial style & best practices guide
this ...

PoshCode/PowerShellPracticeAndStyle: The Unofficial PowerShell Best Practices and Style Guide
— https://github.com/PoshCode/PowerShellPracticeAndStyle

[7] remove unused code
you define $Result ... but never use it. i would remove that.

[8] define the type for your parameter
your $FolderName parameter type is not defined. i suspect it is [string], tho.

[9] avoid sending things across a pipe if you can
you send $_ to Get-NetFirewallApplicationFilter via a pipe. pipeline ops are slower than direct ops & it looks like you could call that out by using the parameter name directly.

here's how i would rework your code layout ...

Param (
    [Parameter(
        Mandatory)]
        [string]
        $FolderName
    )

Get-NetFirewallRule |
    Where-Object {
        $_.Direction -eq "Outbound" -and
        $_.DisplayName -like "*appcontainer*"
        } |
    ForEach-Object {
        # i wonder if the next two lines could be done as
        #    Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $_
        $_ |
        Get-NetFirewallApplicationFilter |
        ForEach-Object {
            $Acl = Get-Acl $FolderName
            $Sec= New-Object System.Security.Principal.SecurityIdentifier($_.Package)
            $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
                $Sec,
                "FullControl",
                (1 -bor 2),
                0,
                "Allow"
                )
            $Acl.SetAccessRule($AccessRule)
            $Acl |
                Set-Acl $FolderName
            } # end 2nd FE-O
        } # end 1st FE-O


Processing form values for each day of week

Well, every time you see a repeated code, you could think of a loop.

if I am not mistaken, only a weekday is changed, so it could be used to form the loop:

$schedule = [];
$weekdays = ['mon','tue','wed','thu','fri','sat','sun'];
foreach ($weekdays as $day)
{
    $schedule[] = round(abs(strtotime($_POST[$day][1]) - strtotime($_POST[$day][0])) / 3600, 2),
    $schedule[] = round(abs(strtotime($_POST[$day][3]) - strtotime($_POST[$day][2])) / 3600, 2),
}


Is there a better way to thread this class function?

How many instances of foo are you going to have?  Spawning a large number of threads or forking a large number of processes isn't going to scale well in terms of both CPU and memory resources.

Another approach that generally has better scalability is a thread pool.  The basic idea is that you have a fixed number of threads that pull and execute tasks from a queue, resulting in better resource utilization.


I would suggest loading the external file and initializing the dialog prior to the event...kind of like:

$(document).ready(function(){
    // make the dialog
    $("#dialog-confirm").load("/help/nameSearch.htm").dialog({
           autoOpen: false,
           resizable: false,
           height: screen.height - 300,
           position: {
               my: "left top",
               at: "left top",
               of: "#Table1"
           },
           width: '790px',
           height: 'auto',
           modal: true,
           buttons: {
               "Okay": function () {
                   $(this).dialog("close");
               }
           },
           hide: { effect: "drop", direction: "up" },
           show: { effect: "drop", direction: "down" }
       });
    }).keypress(function (e) {
       if (e.keycode == $.ui.keyCode.ENTER) {
           $(this).dialog("close");
       }
    });

    $("#Help").click(function () {
        $("#dialog-confirm").dialog( "open" );
    });

});

That way, any delay caused by the loading of the file/creation of the dialog is handled on page load instead of on button click.

Note the addition of the autoOpen:false option. That keeps it from opening on init.


Instantiating a Database connection class in PHP

Is a "user" a "database"?

That doesn't sound right.
A database is a tool or service that provides fast access to data via queries,
and a user sounds like a representation of a real-life user,
described by a set of characteristics.
A representation of a user may use a database to store its data,
but it is not a database.

In short, User should not extend Database.
A User could be a container for user data,
and User instances could be created by a UserFactory or UserRepository which could be implemented to fetch the user data from a database or some other backend.

Getting fields from a database

Instead of SELECT * queries,
it's recommended to name the required fields explicitly.
This can reduce the amount of data transferred from the database,
and it eliminates dependence on the ordering of columns.

What is getConnect ?

The getConnect function returns the Database singleton instance,
not a "connect".
Getting a "connect" seems meaningless.
getInstance is a more common name in singleton implementations.

public or private

As a good rule of thumb,
make everything private,
and then change some of them public as necessary.

The less implementation details are visible, the better.
Implementation details that are not visible give you the flexibility to change those details without affecting the users.


Timing single operation to not be repeated for a fixed time

First of all, it looks like as a workaround for another bug. You might want to fix that bug instead of this workaround.
Comments like the following are unnecessary:

 /**
 * Logger for this class
 */

It just repeats the code and forces readers to read more than necessary.
Service.getInstance() is repeated. Create a local variable for it.
Synchronizing on public objects (like RecoverServiceCommand.class) is error-prone.  I'd use a private lock object instead. See: Avoid synchronized(this) in Java?
A minor change could be extracting out a boolean needsRestart local variable which would make the intention of the expression a little bit more clear.

Reference: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler

  Put the result of the expression, or parts of the expression,
  in a temporary variable with a name that explains the purpose.

Currently the code is tightly coupled with the Service and the Utils classes. If you want to write unit tests it's not too easy because it needs a working Service instance and it depends on the system time too. To make it easier to test you could pass the dependencies to the constructor:

private static final ReentrantLock lock = new ReentrantLock();

private final Service service;

private final Ticker ticker;

private final long updateInterval;

public RecoverServiceCommand(final Service service, final Ticker ticker,
        final long updateInterval) {
    this.service = checkNotNull(service);
    this.ticker = checkNotNull(ticker);
    checkArgument(updateInterval > 0, "updateIntarval must be bigger than zero");
    this.updateInterval = updateInterval;
}

@Override
protected void doExecute(final Object... arg0) throws CommandException {
    final long now = ticker.read();
    lock.lock();
    try {
        final boolean needsRestart =
            (now - service.getLastUpdate()) > updateInterval;
        if (needsRestart) {
            service.restartService(now);
        } else {
            log.warn("Messaging queues not restarted because "
                + "it was already restarted not so long ago");
        }
    } finally {
        lock.unlock();
    }
}

Here is a few tests with EasyMock:

import static org.easymock.EasyMock.expect;

import org.easymock.EasyMockSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.common.base.Ticker;

public class RecoverServiceCommandTest {

    private EasyMockSupport mockery;
    private Service service;
    private Ticker ticker;

    @Before
    public void setUp() {
        mockery = new EasyMockSupport();
        service = mockery.createMock(Service.class);
        ticker = mockery.createMock(Ticker.class);
    }

    @After
    public void tearDown() {
        mockery.verifyAll();

    }

    @Test(expected = IllegalArgumentException.class)
    public void testInvalidUpdateInterval() throws Exception {
        final long invalidUpdateInterval = 0;

        mockery.replayAll();

        new RecoverServiceCommand(service, ticker, invalidUpdateInterval);
    }

    @Test
    public void testUpdateIsRequired() throws Exception {
        final long updateInterval = 100;

        final long currentTime = 300L;
        expect(ticker.read()).andReturn(currentTime);
        expect(service.getLastUpdate()).andReturn(199L);
        service.restartService(currentTime);

        mockery.replayAll();

        final RecoverServiceCommand command =
            new RecoverServiceCommand(service, ticker, updateInterval);
        command.doExecute();
    }

    @Test
    public void testUpdateIsNotRequired() throws Exception {
        final long updateInterval = 100;

        final long currentTime = 300L;
        expect(ticker.read()).andReturn(currentTime);
        expect(service.getLastUpdate()).andReturn(200L);

        mockery.replayAll();

        final RecoverServiceCommand command =
            new RecoverServiceCommand(service, ticker, updateInterval);
        command.doExecute();
    }

}

I've used the Ticker class from Guava. It's easy to mock it and it has a systemTicker which you can use in production code. The check methods are also in Guava.


Condensing multiple conditionals into function

The Chrome, Firefox, and Safari duplicated code exists as the first part of every conditional and those three can be moved outside. Then have all of the other logic in an else. You'll end up with the $('#userName').length and /ip(hone|od|ad)/i.test(searchEngine) being empty. The reason I haven't provided a code example is because only you can decide if that's a problem or not.


func evt_bookModel(bookModel: BookModel, didUpdateCurrentBook book: Book) {
    var index: Int?
    for (key, value) in DataStore.defaultInstance.books.enumerate() {
        if value.id == book.id {
            index = key
            break
        }
    }

    if let _ = index {
        bookView.updateBook(book, atIndex: index!)
    }
}

I see a few problems in this block of code alone.

Ultimately, this could be written far more simply as:

func evt_bookModel(bookModel: BookModel, didUpdateCurrentBook book: Book) {
    for (key, value) in DataStore.defaultInstance.books.enumerate() where value.id == book.id {
        bookView.updateBook(book, atIndex: index)
        break
    }
}

This eliminates a variable, and better yet, eliminates a force unwrap (that isn't even necessary if you just used the if let correctly).

class BookModel {

    private(set) var currentBook: Book!
    weak var observer: BookModelObserver?

    func updateCurrentBook(book: Book) {
        currentBook = book
        observer?.evt_bookModel(self, didUpdateCurrentBook: currentBook)
    }
}

We've got more unnecessary optional problems in this class.  There's not a particularly good reason for currentBook to be an implicitly unwrapped optional in this case.  It can cause nothing but problems.

There's currently nothing else to this class, so it's unclear why we need to keep a reference to the book at all, but our updateCurrentBook can be changed slightly to do the same thing, not need any unwrapping code, and not need the implicitly unwrapped optional (which again is only going to lend itself to a future Stack Overflow "fatal error found nil while unwrapping optional" question).

class BookModel {
    private(set) var currentBook: Book?
    weak var observer: BookModelObserver?

    func updateCurrentBook(book: Book) {
        currentBook = book
        observer?.evt_bookModel(self, didUpdateCurrentBook: book)
    }
}

Of course, this might be even better if we just used the didSet property observer method on the property itself:

class BookModel {
    private(set) var currentBook: Book? {
        didSet {
            if let newBook = currentBook {
                observer?.evt_bookModel(self, didUpdateCurrentBook: newBook)
            }
        }
    }

    weak var observer: BookModelObserver?
}

But now it seems weird that currentBook could be set to nil and the property observers not notified of that.  So here's what makes most sense to me:

class BookModel {
    var currentBook: Book {
        // a willSet probably also makes sense
        didSet {
            observer?.evt_bookModel(self, didUpdateCurrentBook: newBook)
        }
    }

    weak var observer: BookModelObserver?

    init(book: Book, observer: BookModelObserver? = nil) {
        self.book = book
        self.observer = observer
    }
}

In this case, the book property always has a good value.

Or, alternatively, we make it fully optional.  It doesn't matter if it's public or private.

Here's the biggest problem with your original implementation:

let fooBookModel = BookModel()
let fooBook: Book = fooBookModel.currentBook // crash, book is nil, it was never set

This is perhaps not how the class is intended to be used, but nothing at all about your code prevents this usage.

My sample prevents the empty initializer and forces this:

let barBook = Book()
let fooBookModel = BookModel(barBook)
let fooBook = fooBookModel.currentBook

Here, the currentBook property can never be nil.  And the property observer code is handled in a far more Swift-standard way versus the sort of Swift-weird setter approach in the original implementation.


Determining the cardinality of sets defined by recursively following indexes

You are visiting every node to check their chain, but if they've already been visited by a previous chain they don't need to be checked again.

So you can have a single "visited" HashSet outside the main loop which can be used to check whether they have been visited in the outside loop and used to break the inside loop.

Then in each of the outside loop iterations you can continue if you have previously visited.

Note also that you don't need to return and store the actual cycle, just the length.

public int solution(Integer[] A) {

     int arrayLength = A.Length;
     int maxsize = 0;
     int count = 0;
     Set<Integer> visited = new HashSet<Integer>();

     if(arrayLength <= 0)
     return 0;

     for(int i = 0; i < arrayLength; i++) {
       if(visited.contains(i))
            continue;

       int tempNum = A[i];
       count = 0;
       while(!visited.contains(tempNum)){
           visited.add(tempNum);
           tempNum = A[tempNum];
           count++;
       }

       if(count > maxsize) {
          maxsize = count;
       }
    }
     return maxsize;
 }


Returning the sum of all multiples of a number up to 1000

range takes an optional third argument, which is the step size for the sequence. For example:

range(0, 10, 3) # Returns [0, 3, 6, 9]

Python also has a built-in sum function that adds up all the numbers in an array, so you could refactor your code to look like this:

def get_multiple_sum(num):
    return sum(range(0, 1000, num))

Performance-wise, this should be much faster, as it doesn't perform 1000 remainder operations and uses a library function which may be optimized by the interpreter.