Avoiding object slicing within abstractions and their derivations

Allowing a Shape to be assigned to a circle does not sound like it is very safe. I suppose there are situations where it can be used but I would advice against it in the general case
Also I would use Curiously Recurring Template Pattern to get around having to write the assignment operator-er in every derived class.
class Shape
{ // STUFF
};

template<typename T>
class ShapeCopyable: public Shape
{
    T& operator=(const Shape& s)
    {
        T const& c = dynamic_cast<T const&>(s);  // Throws on bad cast.
        assign(c);

        return *this;
    }
};
class Circle: public ShapeCopyable<Circle>
{
    // Stuff
};

In addition to what @Chris Jester-Young covered (so everything he said):
The Base class of a hierarchy with virtual methods should also have a virtual destructor. Otherwise you are going to start having issues with memory management when you start dynamically creating objects on the fly.
class Shape {
public:
    virtual ~Shape() {}

Don't define the copy constructor or assignment operator if nothing special needs to be done. Let the compiler generated version do the work for you. Unless you have something special in the destructor or have RAW pointer members this is unlikely. PS you should not have RAW pointer members either.
    // Remove this:
    virtual Shape& operator=(const Shape& s);

Don't like getters/setters. They break encapsulation and expose the internal implementation of the object. You should consider why you need to pass the state of the object out (is the function that uses the values really a member function).
Interactions on the object should usually be done internally to the object. This will get rid of most of your needs for getters and setters. If you still have a need after the analysis fine.
    // Don't like them.
    // Make but sometimes you need them but minimze your
    // exposure by using methods that manipulate the object rather
    // than moving the manipulation to an external actor.
    std::string getName() { return name; }
            int getEdges() { return edges; }
            int getRadius() { return radius; }
           void setRadius(int r) { radius = r; }

A vector of pointers. Red flag who owns the pointers.
    std::vector<Shape*> shapes;

A'hh you are pushing stack objects onto the vector.
    shapes.push_back(&c2);

Maybe it should be a vector of reference wrapper to Shape std::vector<std::reference_wrapper<Shape>>.
Getting a circle from a shape.
    c3 = *shapes[0];

Not sure that should really happen. The interface to Shape should be how you manipulate the object. Needing to convert the object to a circle seems unnecessary in most situations (you should probably have virtual functions that do the actions you need). Sometimes things have unique actions then you need to convert them back.But in these situations just use dynamic_cast directly (this also shows you are doing the conversion very explicitly).
Based on comments below:

I will need to pull name's and description's to display to the user

Its easier to ask the object to display itself rather the pull details about the object and then display them.
The simplist example is just printing information to a stream:
// Original Way
Circle    c(5);
std::cout << "Circle: "  << c.getName()
          << " Edges: "  << c. getEdges
          << " Radius: " << c.getRadius()
          << "\n";

// What I would do is make the serialization of the object to a stream
// a member method that does the work.

class Shape
{
    virtual void print(std::ostream& stream) const = 0; // Can print a Shape
                                                  // Must be specialized for
                                                  // Specific types.

    friend std::ostream& operator<<(std::ostream& stream, Shape const& shape)
    {
        shape.print(stream);
        return stream;
    }
};

// Now you print like this:
Circle    c(5);
std::cout << c << "\n";

You don't need to expose the members just because you need serialization. Doing it this ways adds consistency so that all objects of a particular type are serialized in the same way. If you need to change what it looks like you have a single place in the code that needs modifying.
We can extend the above to other graphical representations.
struct DisplayInterface
{
     // This is an interface for drawing shapes on a display.
     // You can imagine it has the standard drawing functions.
     // But imagine a base set.
     void drawLine(Pt const& tr, Pt const& bl);
     void drawCircle(Pt const& tr center, unsigned int radius);
     void drawPolygon(std::vector<Pt> const& pts);
     void drawText(Pt const& bl, unsigned int fontSize, std::string const& str);
};

// Now in your drawing code you pass the DisplayInterface to the object
// So it can draw itself. So usually the drawing system provides an
// interface that all drawable objects need to implement.

struct Drawable
{
    virtual void display(DisplayInterface& di) = 0;
};

class Shape: public Drawable  // All shapes are drawable
{                             // But each shape must implement
                              // Its own display()
};

class Circle: public Shape
{
     virtual void display(DisplayInterface& di)
     {
          di.drawCircle(Pt(0,0), radius);
          di.drawText(Pt(0,15), 12, name);
     }
};


Have I overdone it again?

I think it's not bad at all. I don't think you overdid anything.

  Is there anything else I should or should not do?

Notice that the condition primes.Count != nPrime of the while loop is unnecessary evaluated many times:
when nothing was added to the list,
the re-evaluation is pointless.

You could improve this by changing it to an infinite loop with while (true),
and moving the original condition to the point right after adding a prime to the list. If the target count is reached, break out of both loops.

TOP: while (true)
{
    int sqrtNPrimeVal = (int) Math.Sqrt(nPrimeVal);

    foreach (int i in primes)
    {
        if (nPrimeVal % i == 0) { break; }

        if (i >= sqrtNPrimeVal)
        {
            primes.Add(nPrimeVal);
            if (primes.Count == nPrime)
            {
                break TOP;
            }
            break;
        }
    }

    nPrimeVal += 2;
}

But I think a bigger problem with this code is the poor naming,
especially of variables:

nPrimeVal implies a prime value, possibly the n-th prime. But that's not the case, making it very misleading. possiblePrime would be better.
nPrime implies.... I don't really know what. It's the target count, so I'd name it targetCount
NPrimeGenerator is not a great name. The method returns the n-th prime number, so GetNthPrime would seem more natural

It's good that you skip even numbers when searching for the next time.
What would be even better is to use a sieve,
a popular choice being the Sieve of Eratosthenes.

Lastly,
a little thing,
but note that in the condition i >= sqrtNPrimeVal you can drop the equality (making it i > sqrtNPrimeVal),
as in the case of equality the condition will not be reached,
thanks to the break right before it.


Checking an "constant" IP address is an bad idea because of ISP with load balancing. IP address should change to less busy proxy.

In most of cases IP address belongs to the same block. It is called CIDR matching:

function cidr_match($ip, $range)
{
    list ($subnet, $bits) = explode('/', $range);
    $ip = ip2long($ip);
    $subnet = ip2long($subnet);
    $mask = -1 << (32 - $bits);
    $subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
    return ($ip & $mask) == $subnet;
}

usage:

if(!empty($_SESSION['ip'])){
  //192.168.001.xxx = 192.168.001.000/24
  if(!cidr_match($_SERVER['REMOTE_ADDR'],$_SESSION['ip'].'/24')){
     session_destroy();
  }
} else {
  $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}

http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing

Personally, i recommend to you to check IP address range and some client data (but data may be fake).

PS: do not store session data in MySQL, you should store them just in session.


Query WordPress database, returning an array of rows

If you're working with a custom table you have within your database, which you use for WP, then using $wpdb is the way to go. Just remember to use prepare, if there's any user submitted stuff included in the query.
If on the other the data is stored as posts (with custom post type) with associated post meta, then WP_Query with meta_query argument is more appropriate way to find the data. (It uses $wpdb in the end, but is the more typical way to query posts).


To my surprise, rewriting no_conflict as

def no_conflict(new_row, new_col, solution):
    for row, col in enumerate(solution):
        if col == new_col or row + col == new_row + new_col or row - col == new_row - new_col:
            return False
    return True

resulted in a factor of 2 speedup. I have no explanation.

Other tweaks I tried gave very marginal performance changes.

As for the general review, the code is quite straightforward and readable. The only recommendation is to compute start_time after taking inputs. As written, you are timing not only the algorithm but also user's typing skills.


Strictly to answer the question at hand, you have local variables for the individual contracts already, so you can just re-use them:

ohterClassMock.Verify(mock => mock.MethodToTest(It.Is<Contract>(c => contract.Equals(c))));
ohterClassMock.Verify(mock => mock.MethodToTest(It.Is<Contract>(c => contract2.Equals(c))));

This assumes you have implemented IEquatable<Contract> and/or overridden Object.Equals on your Contract object.

Given the behavior of most test and mocking frameworks, it will probably save you a lot of grief to go ahead and override Object.ToString so that failed tests will print out nicer expected/actual values than the fully-qualified type names.

Also, as an aside, you can create your list with a collection initializer if you do so after building your individual contracts:

var contracts = new List<Contract> { contract, contract2 };

Or, if your method takes in IEnumerable<Contract>, it may be even simpler to use:

var contracts = new [] { contract, contract2 };


Use a 4-space indent.
Don't repeatedly subtract 1 from the same unchanging value.
Simplify the compare conditional: just use else.
Take advantage of list.extend().
Drop the wrap-up conditionals: they aren't actually needed. Code like zs.extend(xs[xi:]) will work fine even if xi exceeds the list
bounds.
Shorten the variable names to lighten the code weight and increase readability. There's no loss of meaning here, because all of the short names are quite conventional and make sense in a generic function like this.
def merge_arrays(xs, ys):
    # Setup.
    xmax = len(xs) - 1
    ymax = len(ys) - 1
    xi = 0
    yi = 0
    zs = []

    # Compare and merge.
    while xi <= xmax and yi <= ymax:
        if xs[xi] <= ys[yi]:
            zs.append(xs[xi])
            xi += 1
        else:
            zs.append(ys[yi])
            yi += 1

    # Merge any remainders and return.
    zs.extend(ys[yi:])
    zs.extend(xs[xi:])
    return zs

Last night I wrote an iterator-base solution but somehow forgot that next()
supports a handy default argument: the code was awkward and Maarten
Fabré did a nicer
implementation. But if your willing to use
more_itertools.peekable()
you can achieve a simple, readable implementation. Thanks to
superb-rain
for an idea in the comments that helped me simplify further.
from more_itertools import peekable

def merge(xs, ys):
    xit = peekable(xs)
    yit = peekable(ys)
    while xit and yit:
        it = xit if xit.peek() <= yit.peek() else yit
        yield next(it)
    yield from (xit or yit)


The code itself is not so bad although it could use more {} and maybe more precise names then lastEval or match. Of course it shouldn't print to the console but return a usable result.

I can't tell how fast/slow it would be if it returned a result that can be printed outside the method. I compared it with another search algorithm and for 1.000.000 iterations mine is ~20ms faster.

I think the method could do better by returning a dictionary with the results.

Currently the original method runs twice over the item list. First by sorting them and then by searching for duplicates.

This could be improved by using a helper array to mark which item is already sorted and skip subsequent sortings thus run over the items only once.

The last optimization is to skip items that already have been checked. I think you are doing this with the alreadyMatched helper but I'm not sure about it.

Making the method generic and require T to be IComparable makes it possbile to reuse it for other collections with comparable items.

The value comparison takes place in a local function sequenceEqualFast.

Similarly it sorts the lists and keeps track of the sorting in the local sortList function.

public static Dictionary<List<T>, int> FindDuplicatesFast<T>(
    List<List<T>> values
) where T : IComparable
{
    var isDuplicate = new bool[values.Count];
    var isSorted = new bool[values.Count];

    // Key: first of duplicates
    // Value: count of duplicates
    var results = new Dictionary<List<T>, int>();

    var sequenceEqualFast = new Func<List<T>, List<T>, bool>((l1, l2) =>
    {
        if (l1.Count != l2.Count) { return false; }
        for (int k = 0; k < l1.Count(); k++)
        {
            if (l1[k].CompareTo(l2[k]) != 0)
            {
                return false;
            }
        }
        return true;
    });

    var sortList = new Action<int>(i =>
    {
        if (!isSorted[i])
        {
            values[i].Sort();
            isSorted[i] = true;
        }
    });

    for (int i = 0; i < values.Count - 1; i++)
    {
        if (isDuplicate[i]) { continue; }
        sortList(i);

        results[values[i]] = 1;
        isDuplicate[i] = true;

        for (int j = i + 1; j < values.Count; j++)
        {
            if (isDuplicate[j]) { continue; }
            sortList(j);

            if (sequenceEqualFast(values[i], values[j]))
            {
                isDuplicate[j] = true;
                results[values[i]] += 1;
            }
        }
    }
    return results;
}

I have run some more tests and these are the results.

Test collection

var rnd = new Random();

var itemCount = 100;
var testData = Enumerable.Range(0, itemCount).Select(e =>
{
    var count = rnd.Next(3, 5);
    return Enumerable.Range(0, count).Select(en => rnd.Next(0, 10)).ToList();
}).ToList();

var testCount = 10000;

Results

@Paparazzi
00:00:03.2791287

@t3chb0t
00:00:01.6763969


Is this code for getting the dependency tree of a file correct?

Not a lot of code to review,

To reduce confusion, I would use _.uniq() rather than point straight to uniq()
lowerCamelCase is preferred, child_node -> childNode
dep_tree is unfortunate, I like recursiveDependencies better
I would have set prev_deps = prev_deps || []; prior to return, it would make your recursive call less golfic:

return dep_tree(graph,child_node, prev_deps.concat(node) )


Choosing the generic type (and parameters)

The Fenwick tree stores cumulative values of its elements, and is based on the ability to compute the sum and difference of those elements. You made a very general implementation, where “sum” and “difference” are provided as closure parameters. But it cannot be ensured that these are proper inverse operations of each other, and a slight variation of your multiplicativeTree example demonstrates the problem:

let multiplicativeTree = FenwickTree(count: 4, neutralElement: 1,
                                     forward: *, reverse: /)

multiplicativeTree.update(index: 0, with: 5)
print(multiplicativeTree.accumulated(at: 0))    // 5   OK

multiplicativeTree.update(index: 0, with: 10)
print(multiplicativeTree.accumulated(at: 0))    // 10  still OK

multiplicativeTree.update(index: 0, with: 13)
print(multiplicativeTree.accumulated(at: 0))    // 10  what?

multiplicativeTree.update(index: 0, with: 11)
print(multiplicativeTree.accumulated(at: 0))    // 0   what???

I would require the elements to conform to the AdditiveArithmetic protocol instead. That protocol

requires addition and subtraction, making the forward and reverse parameter obsolete,
requires a .zero element, making the neutralElement parameter obsolete, and
provides semantics: according to SE-0223, it “roughly corresponds to the mathematic notion of an additive group.”

AdditiveArithmetic is adopted by all binary integer and floating point types, that probably covers most use-cases. If you really need a data structure where updating a value is done via multiplication then you can define a custom type which implements AdditiveArithmetic accordingly.

The declaration and initialization then simplifies to

class FenwickTree<T: AdditiveArithmetic>  {

    private let count   : Int

    private var data    : [T]
    private var tree    : [T]

    init(count: Int) {
        self.count = count
        self.data = Array(repeating: .zero, count: count)
        self.tree = Array(repeating: .zero, count: count + 1)
    }

    // ...
}

and sums/differences can just be computed with + and -, making the code even better readable.

Accessing the elements

There is a

func update(index: Int, with newValue: T) {

to set new value at an index, but no method to get a single value. I would suggest to implement the subscript method instead, with both a getter and a setter:

subscript(index: Int) -> T {
    get {
        return data[index]
    }
    set {
        // ... update `data` and `tree`
    }
}

And not much more work is needed to make FenwickTree a (mutable, random access)  Collection.

A wider range of ranges ...

The accumulated(in:) method becomes much more flexible if it takes a RangeExpression parameter instead of a Range:

func accumulated<R>(in range: R) -> T
where R: RangeExpression, R.Bound == Int
{
    let realRange = range.relative(to: 0..<count)
    let cumulatedLow = accumulated(at: realRange.lowerBound - 1)
    let cumulatedHigh = accumulated(at: realRange.upperBound - 1)
    return cumulatedHigh - cumulatedLow
}

Now you can call it with half-open, closed, or partial ranges:

additiveTree.accumulated(in: 1..<2))
additiveTree.accumulated(in: 1...3))
additiveTree.accumulated(in: 2...))
additiveTree.accumulated(in: ..<4))
additiveTree.accumulated(in: ...3))

The last line is equivalent to your

additiveTree.accumulated(at: 3))

which means that accumulated(at:) is no longer needed as a public method (which solves the problem of the similar names of those methods.)

Further suggestions

The index operations

 treeIndex += treeIndex & -treeIndex
 treeIndex -= treeIndex & -treeIndex

look like magic to the first reader of your code. I would move that to helper methods (which the compiler inlines) and document it.

The tree[0] element is never accessed. With slight modifications of the index calculations you can save one element in that array, i.e. initialize it as

  self.tree = Array(repeating: .zero, count: count)

For example, the accumulation would be

func accumulated(at index: Int) -> T {
    guard index >= 0 else { return .zero }
    var sum = tree[0]
    var treeIndex = index
    while treeIndex > 0 {
        sum += tree[treeIndex]
        treeIndex -= treeIndex & -treeIndex
    }
    return sum
}

Finally, a single element can be retrieved from the tree array alone, by computing the difference of two tree nodes (this is also described in the Fenwick article). Therefore, at the cost of slightly more computation, you can get rid of the self.data array and save memory.


Clean implementation of FTP File Cleaners

Wouldn't it make more sense to have IRemoteFileCleaner as the base class, and have FTPFileCleaner (which inherits from IRemoteFileCleaner as the class which all the others inherit from?


Promise.jsm demo of Promise.all and Promise.defer

Here's my implementation:

// So we define a function that loads images, and returns a promise for us to listen to
function loadImages(images){

  // We can take advantage of `map` which iterates through an array and makes an array
  // out of the returns of each iteration. In this case, we return a promise for each
  // url, for `Promise.all` to listen to later.
  var promises = images.map(function(url){

    // Create a Deferred object and image, and handle the resolution stuff.
    var deferred = Promise.defer();
    var image = new Image();
    image.onload = function(){deferred.resolve('image success: '+ url);};
    image.onerror = function(){deferred.reject('image failed: ' + url);};
    image.onerror = function(){deferred.reject('image aborted: ' + url);};
    image.src = url;

    // Return the promise, which will be stored in the array, thanks to `map`
    return deferred;
  });

  // Listen on the array of promises (aha moment: jQuery.when == Promises.all, more or less.)
  return Promise.all(promises);
}

// Now we use `loadImages`, loading an array of urls, and listening for notices
loadImages([
  'http://www.mozilla.org/media/img/firefox/favicon.png',
  'https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png'
]).then(function(value){
  console.log('loadImages successful: ' + value);
},function(error){
  console.log('loadImages failed: ' + error);
});

Additional notes:

Don't do [].forEach.call. Aside from looking very hackish, it creates an unnecessary array. Do Array.prototype.forEach.call instead.
I'd avoid using try-catch. While it's a good measure for errors, it's bad for optimization. Some optimizing compilers (I think V8) can't optimize code inside try-catch.
Name your variables and functions properly and verbosely.


While I don't see why ToIEnumerable is bad practice, in this specific case I think it is. You're comparing with only one object; why not just attach a where clause on to things? I.e.

return objects.Where((other) => other != this);

or possibly

return objects.Where((other) => !Object.ReferenceEquals(other, this));

Not only will this perform better than Except here, but it's easier to understand, and avoids the entire ToIEnumerable thing entirely.


You got the right approach by using dictionaries and helper function (coinEstSol). You should go further and provide the same kind of approach to coinEstimator.

Furthermore, having informations split in several collections, such as your coinWeight and coinCountWrap is not ideal as it gets harder to extend them latter. Instead, you could work with triplets reprensenting a coin: name, weight and wrap. You could also use collections.namedtuple to make for better understanding of what these values are.

I would use a list to store these coin informations as it allows for automatic building of the menu:

import collections

Coin = collections.namedtuple('Coin', 'name weight wrap')

COINS = [
    Coin('Cent', 126, 50),
    Coin('Nickel', 199, 40),
    Coin('Dime', 113, 50),
    Coin('Quarter', 226, 40),
]

def estimate(coin):
     question = 'What is the total weight of your {}s in grams?\n'.format(coin.name)
     weight = float(input(question))
     value = weight // coin.weight
     wrapper = value // coin.wrap
     if value % coin.wrap:
         wrapper += 1
     return coin.name, value, wrapper

def main():
    print("Welcome to the coin estimator.")
    print("Please enter the type of coins: ")
    for index, coin in enumerate(COINS, 1):
        print(index, coin.name)

    user_choice = int(input('Enter: '))
    name, value, wrapper = estimate(COINS[user_choice - 1])
    print('The total', name, 'you have is', value, 'You need', wrapper, 'wrapper(s)')

Be aware, also, that your float and int calls can raise ValueError if the user doesn't enter a numeric value. You can also get an IndexError if the choice from the user is over the number of coins defined. Depending of your needs, you may want to take care of that.


Simple string-root detection in a string-family

(this is not a good answer because... the answer needs performance analysis and comparison with alternative algorithms)

Only to show a tested and "unified" (str+array) algorithm... A "code" based on the defined (see question's statement) functions,

  function str_getRoot2($a,$b='',$minLen=1) { // "2" to avoid recurrence
    if (is_array($a)) // and $b is a seed.
       return array_getRoot($a,$b,$minLen);
    else  // $b is a root
       return str_getRoot($a,$b);
  }

Complete code, with an aditional retFamily parameter, and recurrence:

  /**
   * Get the commom start-string of two or more strings.
   * @version v1.2 of 2015-06-11.
   * @param $a mix, string for final operation, or array for scan.
   * @param $b string with probable commom root, or integer for array index.
   * @param $retFamily boolean for show "family".
   * @return string $root.
   * @see http://codereview.stackexchange.com/q/92700
   */
  function str_getRoot($a,$b='',$minLen=1,$retFamily=false) {
    if (is_array($a)) { // $b is a seed.
        $family = array();
        if (is_integer($b))
            $b = $a[$b];
        if (count($a)>1) {
            foreach ($a as $item) if ($item) {
                if (is_array($item)) die("array of array is invalid");
                if (!$b) $b=$item; // or trim($b)..trim($item)
                $r = str_getRoot($item,$b,$minLen); // go to str
                if ($r) {
                   if ($retFamily) $family[]=$item;
                   if ($r!=$b) $b=$r;
                } //if
            } // for
        } elseif (isset($a) && count($a)>0)
            $family[]= $b = $a[0];
        if ($retFamily) {
            array_unshift($family,$b);
            return $family;
        } else
            return $b;
    } else {  // $b is a root
        $rooLen = strspn($b ^ $a, "\0"); // split by diff
        return ($rooLen>=$minLen)? substr($a,0,$rooLen): '';
    }
  }

Examples of use: get family array with $fam4 = str_getRoot($words,'yourself',4);  or get specific root of a pair by        str_getRoot('yourself','your');


Concurrent byte array access in Java with different locking

The documentation of the ReadWriteLock says:

  Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is read compared to being modified, the duration of the read and write operations, and the contention for the data - that is, the number of threads that will try to read or write the data at the same time. For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched (such as a directory of some kind) is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Further, if the read operations are too short the overhead of the read-write lock implementation (which is inherently more complex than a mutual exclusion lock) can dominate the execution cost, particularly as many read-write lock implementations still serialize all threads through a small section of code. Ultimately, only profiling and measurement will establish whether the use of a read-write lock is suitable for your application.

In your code, the read operations are very short, they are only copying 16 bytes. Probably, the overhead of using a more complex lock is dominating the cost of execution as stated in the documentation.


I don't think it's best-practice to put any logic that isn't strictly presentation-specific directly into a code-behind event handler like this, let alone that a UserControl knows anything about any DomainService1 object.

If you're shooting for best-practices, you need to look into the Model-View-ViewModel pattern; it's not the job of any UI component to perform any kind of business or data logic.


Letter combinations of phone dial pad number

Putting the members of this class in the reverse order (map, then letterCombinations(), then main()) would be more customary.  The map should be private unless you have a good reason to do otherwise.  I would also avoid creating an anonymous subclass of HashMap, and initialize it this way:

private static final HashMap<Character, String> map = new HashMap<>(8);
static {
    map.put('2', "abc");
    map.put('3', "def");
    map.put('4', "ghi");
    map.put('5', "jkl");
    map.put('6', "mno");
    map.put('7', "pqrs");
    map.put('8', "tuv");
    map.put('9', "wxyz");
};

It would be more obvious that preres is a temporary variable if you scoped it properly.  Both res and preres could be named better — I've chosen results and nextResults, respectively.

Whenever possible, you should specify the initial capacity of an ArrayList.  The penalty for underestimating can be rather severe, as it requires reallocating and copying existing results.

digits.charAt(i) is a loop invariant that can be moved from the middle loop into the outer one.

All loops should have braces.  Omitting them is bad practice and will cause maintenance-induced bugs.

public static List<String> letterCombinations(String digits) {
    List<String> results = new ArrayList<String>();
    results.add("");

    for (int i = 0; i < digits.length(); i++) {
        String letters = map.get(digits.charAt(i));
        List<String> nextResults = new ArrayList<>(letters.length() * results.size());
        for (String str : results) {
            for (int j = 0; j < letters.length(); j++) {
                nextResults.add(str + letters.charAt(j));
            }
        }
        results = nextResults;
    }
    return results;
}

It's generally better to return List<String> rather than ArrayList<String>, to give you flexibility to change the implementation.  For example, here is a solution that uses just one LinkedList.

public static List<String> letterCombinations(String digits) {
    LinkedList<String> results = new LinkedList<>();
    results.add("");

    for (int i = 0; i < digits.length(); i++) {
        String letters = map.get(digits.charAt(i));
        for (int j = results.size(); j > 0; j--) {
            String intermediateResult = results.poll();
            for (int k = 0; k < letters.length(); k++) {
                results.add(intermediateResult + letters.charAt(k));
            }
        }
    }
    return results;
}


Rearrange list by modifying the original list, put even-index values at front

I'm not sure if you are actually trying to solve this problem in-place, but based on what you have done, you could condense your code by using Python list slices instead of separating even and odd indices in a for loop. Slices work by

list[start_index:end_index:step]

So, you could get the even indices with

l[::2][::-1]

which gets the even indices in reverse order, and the odd indices by offsetting the start by 1,

l[1::2]

This works because a step size of 2 means you get every other #, so starting at 0 results in all even indices and starting at 1 results in all odd indices. Without the start index it starts at 0, and without the end index it goes until the end of the list.

This combines into a single line, assigning using slice notation to keep the modification in-place,

l[:] = l[::2][::-1] + l[1::2]


The code in the if is duplicate, so we can extract it to a method that I will call gte (greater than or equal). The maxs and mins values are used at this comparison, so they will be moved to the new method too:

def gte(bounds1, bounds2)
    min_x, max_x, min_y, max_y = 0, 1, 2, 3

    bounds1[max_x] >= bounds2[min_x] && bounds1[max_y] >= bounds2[min_y]
end

The content in the if expression changes to:

gte(bounds1, bounds2) && gte(bounds2, bounds1)

But the if is not necessary because this expression already returns a boolean value, then we will return it directly. The keyword return is not required, then the method overlap? code looks like this:

def overlap?(stroke1, stroke2)
    bounds1 = get_bounds stroke1
    bounds2 = get_bounds stroke2

    gte(bounds1, bounds2) && gte(bounds2, bounds1)
end

Maybe you have a better name than gte, but remember that it must have a meaningful name!


Looping Array object with conditions and comparison the performance with ECMA VS Vanilla JS

It looks like the main difference between your original code snippet and the two revisions is that you're using .filter() instead of .forEach() - both of which came out around the same time, and both of which came out a while ago (IE 9 supports both).
It looks like you aren't doing any significant changes to the code that would improve speed, so you will only see marginal improvements to performance, if any. But, you can always benchmark each of them and find out for yourself how fast each version is.
The original solution is actually the best one among the three shown. There seems to be a big misunderstanding about what the filter() function is and how to use it. filter() is supposed to take an array and return a new array with some values filtered out. The values that get filtered out is decided by the function passed in. For example, if you want the even numbers in a list of numbers, you could do this:
const numbers = [1, 3, 4, 6, 7, 9]
const isEven = n => n % 2 === 0
console.log(numbers.filter(isEven)) // [ 4, 6 ]

You are not using filter() this way - you're just using is like an alternative forEach() function, which is a big no-no. You can just change the .filter() for .forEach() in each of your revisions. Once you have done that, both your original code and your first revision would work just fine. I wouldn't go with the second one though, there's too much inside the if conditions.
I don't really have any newer javascript feature to suggest for these code snippets, except that I generally recommend using the newer for of loop instead of forEach() - it's more powerful than .forEach(), and it fixes the issues that for-in loops had.


Creating Docker network with REST API using Python Django

Just for this .. is this all necessary? You could use the flask application , or mapping the each route to a script..

Short answer : No , there are others ways to build what you want that django is not more appropriate.

Long answer

First point

In your methods you are handling the permited methods at hand , the django have the decorators that handle this:

Allowed http methods
https://docs.djangoproject.com/en/1.11/topics/http/decorators/#allowed-http-methods

Some methods would:

@require_http_methods(["GET"])
def list_containers(request):
    pass

@require_http_methods(["GET"])
def list_images(request):
    pass

@require_http_methods(["GET","POST"])
def networks(request):

    if request.method == "GET":
        # retrieve networks and return them

    if method.method == "POST":
        # create network

urls.py

url(r'container/s', network.list_containers),
url(r'images/', network.list_images),
url(r'networks/', network.networks)

P.s : The views isn't following your structure , but is easily changed.

Second point

The mainly problem with your code is the routes: network/ and network/create to REST definition , the correct would be the route /networks receive the GET and POST and perform different actions ( retrieve and create respectively )

You could use the Django Rest Framework[1] ( the main framework to build restful application in django )

The DRF handle all these: method , routes , views ( viewsets ).

But if django is the bigger to this , you could use the flask framework and use the your routes and the restful frameworks that solves your problem too.

[1] http://www.django-rest-framework.org/

[2] http://flask.pocoo.org/ ( Framework )

[3] https://flask-restful.readthedocs.io/en/0.3.5/ ( FlaskRestful )


Scan a webpage to find the start time and date for an event

Your current approach is very fragile and might easily break if the markup changes even slightly - imagine, for example, opening and closing h4 being on separate lines while still being a valid HTML element.

I would use a proper HTML parser like BeautifulSoup instead (you mentioned you've already tried it). In order to locate the start and end dates, we may use the itemprop attribute:

from bs4 import BeautifulSoup

def get_even_date_range(html):
    soup = BeautifulSoup(html, 'html.parser')

    start_date = soup.find("time", itemprop="startDate")
    end_date = soup.find("time", itemprop="endDate")

    return (start_date.get_text() if start_date else None,
            end_date.get_text() if end_date else None)

Here, the get_even_date_range() function would return a tuple with start and end dates as items. It would return None if a date is not found. For the first sample input HTML, it would return:

('Monday March 13, 2017 - 05:30 PM', 'Monday March 13, 2017 - 07:00 PM')

And, for the second:

('Friday March 17, 2017 - 01:30 PM', None)

You can then go further and convert the date strings to datetimes using the datetime.strptime() and the %A %B %d, %Y - %H:%M %p format:

from datetime import datetime
from bs4 import BeautifulSoup

DATE_FORMAT = "%A %B %d, %Y - %H:%M %p"

def get_date(date_element):
    return datetime.strptime(date_element.get_text(), DATE_FORMAT) if date_element else None

def get_even_date_range(html):
    soup = BeautifulSoup(html, 'html.parser')

    start_date = soup.find("time", itemprop="startDate")
    end_date = soup.find("time", itemprop="endDate")

    return get_date(start_date), get_date(end_date)

Note that I've also moved the repetitive date retrieval logic to a separate reusable get_date() function.


Let's post a dry review first, before jumping in to the conceptual stuff:

You are allowing your end-users download any file on the server. All I need to do is to change the path to /etc/passwd on any form and submit, and I get your server's password file! And if I don't have permissions to that, no biggy, I can still download all of your owned files on the server.
Invalid HTML markup - <form> isn't allowed directly inside of <ul>. Only <li> is.
Separate logic and presentation - You shouldn't mix the part where the user sees your form, and the part where he downloads the file.

A better approach?

A better approach would be a PHP file which is capable of serving files. That PHP file needs to make sure that the file being requested is found in a very specific list of allowed directories (i.e. I allow from images/ and from static/ but not from anywhere else.

Then, when you download a file, all you need to do is to link (With an <a>) to

http://example.com/path/to/file_server.php?filename=somefile.jpg

And have the PHP file_server handle the serving of the requested file.

Getting Fancy

You can even use .htaccess and mod_rewrite to rewrite URLs like this:

http://example.com/static/somefile.jpg

to

http://example.com/path/to/file_server.php?filename=somefile.jpg

Making the fact that PHP is the one sending the file completely transparent to the user!


Finding b and e such that b to the power of e is closest to a given number

A big performance improvement can be made when you realize you don't need to loop over all the possible exponent e. The code calculates, for each possible e, the value of be, and calculating that power takes time.

The goal here is to find b and e such that be is the closest to an integer n. If we rewrite this, it also means finding b and e where \$e\log{b}\$ is closest to \$\log{n}\$. So for a given input number n, and a given base b, we know that the closest value we're looking for will have an exponent of \$e = \left\lfloor\frac{\log{n}}{\log{b}}\right\rfloor\$.

JS1 rightfully pointed out that calculating this formula can lead to rounding errors. Since we're dealing with whole numbers, we can add 0.5 before calculating the logarithm to account for that (I tested this for all numbers from 5 to 1000000). As such, for the inner loop, you can just have:

int sqrtNumber = (int) Math.sqrt(number);
double logN = Math.log(number + 0.5); // to account for rounding issues

int minDiff = Integer.MAX_VALUE;
for (int b = 2; b <= sqrtNumber; b++) {
    int e = (int) (logN / Math.log(b));
    int powerNumber = (int) Math.pow(b, e);
    if (number - powerNumber < minDiff) {
        minDiff = number - powerNumber;
    }
}

This code only makes a single power calculation, in order to know the actual difference between the power and the target number.

Here's a result of a JMH benchmark, comparing the initial code in the question and this revised code. The input number tested is 15000, 150000 and 1500000. This is very far to take 4 seconds for each case, but the revised code is 5 times faster (Windows 10, JDK 1.8.0_102 64 bits, i5 CPU @ 2.90 GHz).

Benchmark           (number)  Mode  Cnt  Score    Error  Units
StreamTest.initial     15000  avgt   30  0,023 ±  0,001  ms/op
StreamTest.initial    150000  avgt   30  0,068 ±  0,002  ms/op
StreamTest.initial   1500000  avgt   30  0,202 ±  0,002  ms/op
StreamTest.revised     15000  avgt   30  0,005 ±  0,001  ms/op
StreamTest.revised    150000  avgt   30  0,014 ±  0,001  ms/op
StreamTest.revised   1500000  avgt   30  0,041 ±  0,001  ms/op

Code of benchmark for completeness:

@Warmup(iterations = 10, time = 700, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 700, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(3)
public class StreamTest {

    @State(Scope.Benchmark)
    public static class NumberContainer {

        @Param({ "15000", "150000", "1500000" })
        private int number;

    }

    static int initialCode(int number) {
        int sqrtNumber = (int)Math.sqrt(number);
        int powerNumber;
        int minDiff = Integer.MAX_VALUE;
        for (int b = 2; b <= sqrtNumber; b++) {
            for (int e = 1; (powerNumber = (int) Math.pow(b, e)) <= number; e++) {
                if (number - powerNumber < minDiff)
                    minDiff = number - powerNumber;
            }
        }
        return minDiff;
    }

    static int revisedCode(int number) {
        int sqrtNumber = (int) Math.sqrt(number);
        double logN = Math.log(number + 0.5);
        int minDiff = Integer.MAX_VALUE;
        for (int b = 2; b <= sqrtNumber; b++) {
            int e = (int) (logN / Math.log(b));
            int powerNumber = (int) Math.pow(b, e);
            if (number - powerNumber < minDiff) {
                minDiff = number - powerNumber;
            }
        }
        return minDiff;
    }

    @Benchmark
    public int initial(NumberContainer c) {
        return initialCode(c.number);
    }

    @Benchmark
    public int revised(NumberContainer c) {
        return revisedCode(c.number);
    }

}


Yup, you can iterate the input fields. For this sort of thing you should also be using classes, instead of inline CSS. Using jQuery .each and .togggleClass you can create something like this:

function validate () {

  $('#form input').each(function () {
     var $el = $(this)
     $el.prev('label').toggleClass('invalid', $el.val());
  });

}

And your stylesheet has a rule like this;

label {
  color: #444;
}

label.invalid {
  color: #fff;
}

If you want to check if the form was valid then you can check for the existence of a field with that class. $('#form input.invalid').length. Or you can set a boolean in the each function if you want to separate the logic from the HTML.


I would find this easier to read if the first thing in the method was

        if (list == null || list.length < 2) {
            return null;
        }

This gets rid of the unlikely cases off the bat and saves us having to indent the rest of the logic inside two if statements.

            int listSize = list.length;
            int mod = listSize % 2;
            int half = listSize/2;
            int stop = mod > 0 ? half+1 : half;

This could just be

            int stop = (list.length + 1) / 2;

You never use mod or half elsewhere and can just replace listSize with list.length.  This will return the same results, as if the list has an odd size, adding one will give it an even size.  Then dividing by two will return the same result as half + 1, since half is rounded down.  If even, then adding one before dividing by two does nothing, as the odd number will be rounded down.

                outer: for(int currentIndex=0; currentIndex<listSize; currentIndex++){
                            if(currentIndex == stop){
                                break;
                            }

This could just be

          for (int currentIndex = 0; currentIndex < stop; currentIndex++) {

Although either way it returns an incorrect result for an input like

new int[] { 1, 2, 9, 5, 7 }, 12

You do

                                    int current = list[currentIndex];

inside the inner loop.

Do it before the inner loop instead.  Then you can just do it once rather than once for each iteration of the inner loop.  On the bright side, the compiler probably compiled this out anyway.

                                        twoSum = new int[]{currentIndex, otherIndex};
                                        break outer;

This could be just

                            return new int[]{currentIndex, otherIndex};

Then you don't need the labeled loop.  And

        return twoSum;

could be just

        return null;

No need for the twoSum variable at all.

Alternatives

This is an \$\mathcal{O}(n^2)\$ solution.  But this problem is solvable in linear time.  Consider

public static int[] findTwoSum(int[] numbers, int target) {
    if (numbers == null) {
        return null;
    }

    Integer[] complements = new Integer[target];

    for (int i = 0; i < numbers.length; i++) {
        if (complements[numbers[i]] != null) {
            return new int[]{complements[numbers[i]], i};
        }

        complements[target - numbers[i]] = i;
    }

    return null;
}

This works fine for modest sums where all the inputs are positive (like your example).  It will be much faster for large inputs.

If those constraints don't work for you, try

public static int[] findTwoSum(int[] numbers, int target) {
    if (numbers == null) {
        return null;
    }

    Map<Long, Integer> complements = new HashMap<>();

    for (int i = 0; i < numbers.length; i++) {
        Integer complementIndex = complements.get((long)numbers[i]);
        if (complementIndex != null) {
            return new int[]{complementIndex, i};
        }

        // it's possible that for large targets and a negative input
        // that we might overflow the int type
        long complement = (long)target - numbers[i];
        complements.put(complement, i);
    }

    return null;
}

Now it doesn't matter if the target sum is large or some of the numbers are negative.

Either version works by storing the locations of the complements for each value.  We only need to loop once and get/put are constant time operations for a HashMap.


I see a number of things that may help you improve your program.

Omit empty destructor

The compiler will automatically generate a destructor that would, in this case be identical to the empty one your wrote.  It's better to simply omit it and let the compiler do its thing.

Cleanly separate interface and implementation

In all, the files are fairly neatly divided, but I'd make a couple of changes.  First, I'd move the #include <cmath> to the .cpp file because it's an implementation detail (and as you'll see a bit later, might not be necessary).  Second, I'd remove the processOneSampleLinMidtread() and processOneSampleLinMidrise() from the .h file and make them static free-standing functions in the .cpp file.  More on that in a moment, too.

Avoid comparing floating point numbers for equality

It's generally a good idea to avoid comparing floating point numbers for equality, even if it's only comparing with zero.  See the oft-cited and still excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg for a readable technical discussion for why this is so.

Reconsider the interface

At the moment, there's no way to read back out how many bits are in effect and no way to find out what the digital encoding would have been for a particular input float.  I'd suggest a couple of changes to address that.  First, it is probably useful to provide functions for reading back the publically settable parameters.  Second, I'd suggest splitting the current processOneSample into two pieces: int encode(float n) which would return the binary encoding of the input n and float decode(int x) which would return the corresponding floating point value for the encoding x.

Reduce repeated calculations where practical

The expression powf(2.f, m_nBits - 1.f) is used very many times within the class, but it only depends on m_nBits and not on any other value.  For that reason, it would make more sense to calculate it once and store the result.

Avoid floating point where practical

It's often faster to do integer mathematics rather than floating point.  For that reason, and because we know that the result of powf(2.f, m_nBits - 1.f) is always going to be an integer, I'd suggest instead to calculate using the expression 1 << (bits - 1).

Use standard library features

Instead of the current code checking for upper and lower boundaries, it's much more succinctly expressed using std::clamp if you are using a C++17 compiler.  If not, it's not hard to write your own version.

Use const where practical

The processOneSample() routine does not (and should not!) alter the underlying object, so it should be declared const.

float processOneSample(float in) const;

Think about future uses

Many people agree that the YAGNI principle is a sound one, and I agree with that.  But there is a balance between only coding what's needed right now and anticipating at least the possibility that there may be future uses.  An example in this case is using other kinds of digitizing algorithms such as A-law or \$\mu\$-law for audio digitizing.  An alternative approach might be to have a base class (possibly virtual) and then derived classes that implement each kind of alternative encoding.

Think about whether you need a class at all

This may seem heretical for C++, but not everything needs to be an object.  Really what this code is about is turning one floating point value into another.  It may be that freestanding functions (with the appropriate parameters) might work as well.  It depends on how often you anticipate changing the parameters of the base object vs. how many times processOneSample is used.

Consider using a modern constructor style

An alternative to this constructor:

CQuantizer::CQuantizer(CQuantizer::qType type, int nBits, float amplitude)
{
    setType(type);
    setNBits(nBits);
    setAmplitude(amplitude);
}

might be this:

CQuantizer::CQuantizer(CQuantizer::qType type, int nBits, float amplitude) :
    m_nBits{nBits},
    m_amplitude{amplitude},
    m_type{type}
{}


C++ Not-So-Simple Entire HTML Generating Code v0.3

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

Prefer class to struct

The way it's currently defined, any code can modify the contents of the structure.  Better would be to make the data members private and provide necessary accessors to assure that the class is always complete and coherent.

Don't use parallel structures

Right now, the tag attributes and tag contents are stored in parallel vectors. The only association between an attribute and its value is that they have the same position within both vectors.  Instead, use a std::pair and create a vector of those.  That way, each attribute is a single entity.  We can replace the two vectors with this one:

std::vector<std::pair<std::string,std::string>> attributes;

Use "range-for" to simplify code

C++11 and newer allow the use of "range-for" which can really simplify code.  For instance, the current code has this loop:

unsigned int i2;
for(i2 = 0; i2 < myHTML.tagattrcontent.size(); i2++) {
    std::cout << myHTML.tagattrcontent[i2] << ":" << myHTML.attributes[i2] << std::endl;
}

If we follow the previous point and have a single attributes vector instead, we can rewrite this as:

for (const auto &attr : myHTML.attributes) {
    std::cout << attr.first << ":" << attr.second << std::endl;
}

Use const where practical

In the returnTag routine, the underlying HtmlTag is not altered.  Make this explicit by declaring that method const:

std::string returnTag() const {

Think of the user

As a user of this code, I think I'd prefer to remove an attribute by name rather than by position.  It's also not clear that returning the new count of attributes would be useful if the caller already has to keep track of the indexing.

Provide a constructor

It seems to me that it would be nice to be able to write code like this:

HtmlTag myHTML{"foo","bar",{{"spam","eggs"}}};

We can do that by providing the appropriate constructor.  In this case, it's actually quite simple:

HtmlTag(std::string name, std::string content, std::vector<std::pair<std::string,std::string>> attr) :
    tagname{name},
    tagcontent{content},
    attributes{attr}
{}

Note that I'm assuming the attributes are now pairs as previously suggested.

Use your own code

Why doesn't the generateHTML code use any HtmlTags?  Here's a way it could be rewritten to do so:

std::string generateHTML(std::string doctype, std::string headtext, std::string bodytext) {
    HtmlTag body{"body",bodytext};
    HtmlTag head{"head",headtext};
    HtmlTag html{"html",head.returnTag()+body.returnTag()};
    return "<!DOCTYPE " + doctype + " />\n\n" + html.returnTag();
}

If that's not the way you'd like to write the code, it may suggest some improvements that might be made to the HtmlTag class.


Generally speaking, you can resolve if/else logic by using multiple clauses for the same predicate, as multiple clauses implicitely represent 'or' or 'case', e.g.:
foo([[]], Child) :-
   Child = [c(New_Score,G1,Pos),P].
foo(Reverse_Path, Child) :-
   Child = [c(New_Score,G1,Pos),P|Reverse_Path].
bar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-
   memberchk(Child,NewAgenda),
   addChildren(Others,Reverse_Path,Current,NewAgenda,Target,BrandNewAgenda).
bar(Reverse_Path, Child, [], BrandNewAgenda) :-
   BrandNewAgenda = [Child].
bar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-
   New_Score =< FP,
   BrandNewAgenda = [Child|NewAgenda].
bar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-
   append(NewAgenda, [Child], BrandNewAgenda).

main(Reverse_Path, BrandNewAgenda) :-
   foo(Reverse_Path, Child),
   bar(Reverse_Path, Child, [], BrandNewAgenda).

This is just a rough sketch, there are a lot of loose ends here like variables Others, Target or Result (I guess you are juggling too many variables anyway), but I hope you get the gist of it:

Decompose into multiple simpler predicates that encode alternatives through multiple clauses.
Bind results to "out" variables in the clause head (like Child in foo/2 or BrandNewAgenda in bar/4).
Compose the smaller predicates in a "main" predicate that glues them togehter.


Taking a look at the course materials, I think you've missed the point. Applicative.hs has you define sequence :: Applicative f => List (f a) -> f (List a) before filtering, and looking briefly through the suggested progression it appears as though things are ordered such that there is always a “clever” answer to be built out of the things you've previously implemented.

That said, this question then gets both easier and harder. Easier because there is purpose built machinery to manipulate e.g. that weird non-Prelude List type. Harder because this isn't really standard Haskell anymore since all of our usual functions and typeclasses have been replaced by their evil twins.

I think the intended answer is that you map the predicate function over the list you're given, then use the sequence function you defined earlier to switch List (f Bool) to f (List Bool), then... I dunno. This is mirror world.

Here's how you'd write this function given the types from regular old base.

import Control.Applicative
import Data.Traversable

filtering :: (Applicative f) => (a -> f Bool) -> [a] -> f [a]
filtering f xs = (xs `filterBy`) <$> (sequenceA . map f $ xs)
    where
        filterBy :: [a] -> [Bool] -> [a]
        filterBy xs ps = map fst . filter snd $ zip xs ps

I assume the version you're looking for will be identical, but using sequence instead of sequenceA.

I think there is probably an even more clever solution—and I suspect it uses the reader instance (((->) a)) and a lifted filter—but I sure can't tease it out. Comments and edits welcome.


Rotating an array by mentioned digit to rotate

while the solution is functional. it is overly complex. rotation is a simple algorithm of index arithmetic: start with the first cell, with each iteration, you determine the source and destination indexes of one value, move that value into place, take the evicted value and set the next iteration to determine its new place.

so we start with idx 0 and determine its place is at idx 5. in the next iteration we start with idx 5 and determine its new place and so on.

static void leftRotate(int[] arr, int d) {
    int srcIdx, dstIdx;
    srcIdx = 0;
    int val = arr[srcIdx];
    // loop only used to count (i not used as index)
    for (int i = 0; i < arr.length ; i++) {
        dstIdx = srcIdx - d;
        if (dstIdx < 0) dstIdx = arr.length + dstIdx;  // rotate dst idx from start to end of arr
        int temp = arr[dstIdx];
        arr[dstIdx] = val;
        val = temp;  // set next iteration value to move
        srcIdx = dstIdx;  // set next iteration srcIdx
    }
}

also, printArray is redundant. use Arrays.tostring()

EDIT

thanks to @Imus, there is a nasty bug in my "simple" algorithm described above.
The bug occurs when the array is divisible by d. in this case, following src-dst-src-dst chain results in processing the same indexes in a loop, while missing other indexes.  The solution (that I found) is to detect such cases of "closed-loop" and advance the pointers one cell ahead. admittedly, it does make the solution more complex.

below is a fixed solution.

static void leftRotate(int[] arr, int d) {
    int srcIdx, dstIdx, loopDetectIdx;
    srcIdx = 0;
    loopDetectIdx = 0;  // detects processing in "closed loop"
    int val = arr[srcIdx];
    for (int i = 0; i < arr.length ; i++) {
        dstIdx = srcIdx - d;
        // rotate dst idx from start to end of arr
        if (dstIdx < 0) dstIdx = arr.length + dstIdx;
        int temp = arr[dstIdx];
        arr[dstIdx] = val;
        System.out.println(srcIdx + "-" + dstIdx + " " + Arrays.toString(arr));
        val = temp;
        srcIdx = dstIdx;
        // if we already processed srcIdx, move all pointers one cell forward
        if (srcIdx == loopDetectIdx) {
            srcIdx++;
            loopDetectIdx++;
            val = arr[srcIdx];
        }
    }
}


Counting number of 1's and 0's from integer with bitwise operation

Yes, there is a better way:

int CountOnesFromInteger(unsigned int value) {
    int count;
    for (count = 0; value != 0; count++, value &= value-1);
    return count;
}

The code relies on the fact that the expression x &= x-1; removes the rightmost bit from x that is set. We keep doing so until no more 1's are removed. This technique is described in K&R.

This approach is superior because it doesn't depend on an integer's size - it's totally portable - and it tests every bit in a fairly efficient way (with the comparison value != 0).

Also, you might want to replace 32 in main() with sizeof(int)*CHAR_BIT so that your code doesn't depend on an integer using 32 bits:

#include <stdio.h>
#include <limits.h>

int CountOnesFromInteger(unsigned int);

int main()
{
    unsigned int inputValue;
    short unsigned int onesOfValue;
    printf("Please Enter value (between 0 to 4,294,967,295) : ");
    scanf("%u",&inputValue);
    onesOfValue = CountOnesFromInteger(inputValue);

    printf("\nThe Number has \"%d\" 1's and \"%zu\" 0's",onesOfValue,sizeof(int)*CHAR_BIT-onesOfValue);
    return 0;
}


The first question is, why are you using pointers in the first place here? Allocation with new should only be used when required. Perhaps it is in this case, but I'd rethink your design. Are the errors polymorphic? If so, why? If not, why do you need to use pointers?

Many STL containers use either an error-code approach, that is, they return a std::pair<T, bool>, where the bool represents success/failure, or they deal
directly with iterators, and return an iterator to end() in the case of failure. Depending on the type of m_lstErrors, this could be a possibility (although obviously this won't work for a container adapter like std::stack).

Though it is not contained in the C++ standard library at the moment (it is slated for inclusion in C++14), std::optional was basically made for this purpose. In fact, it can be written using only C++11 features (and there's a reference implementation you could use here). Boost also contains a boost::optional type, although this lacks things such as move semantics and safe (explicit) bool conversion (although other than that, it is very similar in nature). This would change the code to look like this:

std::optional<std::tuple<tstring, int, tstring>> CCOMErrorHandler::PopError()
{
    typedef std::tuple<tstring, int, tstring> tuple_type;
    std::optional<tuple_type> error;
    if(!m_lstErrors.empty()) {
        error = *m_lstErrors.front();
        m_lstError.pop_front();
    }
    return error;
}

cppreference has an API reference for std::optional.

As for the complaint about template types, you can always wrap them in another namespace to help prevent pollution:

namespace mynamespace
{
namespace detail
{
    typedef std::tuple<tstring, int, tstring> error_type;
    typedef std::optional<error_type> optional_error;
}

detail::optional_error CCOMErrorHandler::PopError()
{
    //...
}


First I would like to say that I'm not an expert on rfkill; so my comments are more general and may be slightly off for this specific case.

Despite the missing error handling (which you mention) I see only two problems. Not primarily with your code, but with your assumptions:

You are correct to avoid __attribute__((packed)), but the reasons are IMHO not correct. The main reasons in your linked document are unaligned access, data size and performance. None of this is really a showstopper for your code, because you are breaking the data up into its primitive types. More significant is IMHO the simple fact that __attribute__((packed)) is not portable. (Unless you remain on GCC only. On a microsoft compiler you would write #pragma pack(1))
I think you are wrong using the writeRawData() function. Because your code should handle both, big endian and little endian, you would want to use the streaming << operator. I interpret the documentation like this: writeRawData() will always write in the machine byte order - big, or little endian - whatever the machine is. The streaming operators on the other hand will do a conversion, when necessary, to whatever endianness you have selected with setByteOrder().

There is another advantage using the streaming operators, you do not need to do ugly type casting. Instead of this:

out.writeRawData((char*)(&(event.idx)), sizeof(event.idx))

you would simply write:

out << event.idx;

Update: Error handling

I disagree with user1118321. I don't think that the QDataStream throws if it cannot write. I did not find anything about it in the documentation. (but the Qt documentation is known for having white spots) To handle write errors you can use the status() function. Or perhaps the functions from the underlying QIODevice.

out.resetStatus();
out << event.idx;
if(out.status() != QDataStream::Ok)
{
    // error handling
}


Improving the speed of loop in javascript for objects

Continuous repetitive string concatenation is bad for performance because each such operation requires re-hashing of the string due to String interning.
Array enumeration using for-in loop is slower than for-of or a standard for loop.
Things like obj[key][subkey] may be slow in a long loop so cache them in a variable.
Do the proper performance measurements using Devtools Timeline profiler to find bottlenecks.

Here's an arguably more readable and hopefully faster example:

const parts = [];
const group = obj[key];

if (Array.isArray(group)) {
  for (const val of group) {
    if (parts.length) parts.push(', ');
    if (Array.isArray(val)) {
      const tooLong = group.length > 10;
      const len = (tooLong ? group : val).length;
      parts.push(`<font color="green">Array(${len})</font>`);
      if (tooLong) break;
    } else {
      parts.push(objectPreview(val));
    }
  }
} else {
  for (const [key, val] of Object.entries(group)) {
    parts.push(`${parts.length ? ', ' : ''}${key}: ${
      Array.isArray(val) ? '[...]' : objectPreview(val)
    }`);
  }
}
const replacements = parts.join('');

function objectPreview(obj) {
  let str = obj;
  switch (typeof obj) {
    case 'object':
      str = '{...}';
      break;
    case 'string':
      if (/<.*?>/.test(obj)) {
        str = type === 'normal' ?
          `<pre>${process(obj).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>${obj}` :
          '"..."';
      } else {
        str = `<font color="red">"${obj}"</font>`;
      }
      break;
    case 'number':
    case 'boolean':
      str = `<font color="#947cf6">${obj}</font>`;
      break;
  }
  return str;
}


Elegant and secure way to create a dynamic query

If you allow users to pass in arguments that are column names (for example array keys that you turn into column names). Then the keys could be modified to allow SQL Injection.  It's not clear in the question if you plan to do this.  If you just want to have dynamic arguments (with known columns) then preparing the query should suffice as all the user data can be parameterized without issue.

As preparing the values is not an issue, I will assume you want to make the columns and/or tables dynamic.

Problem

Imagine you create a dynamic Select query like this, where the keys from the input args are used for column names and the table name is dynamic as well (fully dynamic):

class foo{
  function Select($table, $args){
    $query = "SELECT * FROM {$table}";
    $where = [];
    $params = [];

    foreach($allowedArgs as $col => $arg){
        $where[] = "{$col} = :{$col}";
        $params[$col] = $arg;
    }

    if(!empty($where)) $query .= ' WHERE '.implode(' AND ', $where);

    print_r($query);
  }
}

Output would be something like this:

 //------- intended behaviour
 $foo->Select('someTable', ['ID' => 32, 'user' => 'someUser']);
 "SELECT * FROM someTable WHERE ID = :ID AND user = :user"
 //after executing with parameters
 "SELECT * FROM someTable WHERE ID = '32' AND user = 'someUser'"

  //------- unintended behaviour
 $foo->Select('someTable', ['ID' => 32, '1 OR 1 --' => null]);
 "SELECT * FROM someTable WHERE ID = :ID AND 1 OR 1 -- = :1 OR 1 --"
 //the DB would execute this:
 "SELECT * FROM someTable WHERE ID = 32 AND 1 OR 1"

To explain the SQLInjection:

The first 1 completes the AND
Then the OR 1 is always true.
Everything after the SQL comment -- is ignored.

So this would return all records in that table regardless of the other arguments.  This is how basic SQLInjection works.

Here $table is also susceptible to SQLInjection, so if you did (this is a bad example but you get the point):

 $foo->Select('admin WHERE 1 --', []);
//"SELECT * FROM admin WHERE 1 --"

Solution

However, you can query the DB schema, by using DESCRIBE {$table} and SHOW TABLES, to build a whitelist of column names and tables. And than, store that data so you can filter out any bad "stuff" like this:

//eg. results of DESCRIBE
Field   Type               Null     Key     Default     Extra
  ID    int(10) unsigned    NO      PRI     NULL    auto_increment

//eg. SHOW TABLES
Tables_in_{database}
   someTable

From this you can build something like:

class foo{
  //get the schema
  public static $fields;
  public static $tables;

  public function ckTable($table){
     if(!self::$tables){
        $smtp = $this->db->query("SHOW TABLES");
        self::$tables = $stmt->fetchAll(PDO::FETCH_COLUMN); //['someTable', "admin", ...]
     }
     if(!in_array($table, self::$tables)) throw new UnknownTable($table);
  }//end ckTable()

  public function getFields($table){
       $this->ckTable($table);

      //only query this once per request
      if(!self::$fields[$table]){

         self::$fields[$table] = [];

         $smtp = $this->db->query("DESCRIBE $table");

         $fields = [];
         while($row = $smtp->fetch(PDO::FETCH_ARRAY)){

           //technically we only need the Keys or the "Field" for this
           //but I felt like showing how you can parse the type too...
           preg_match('/^(?P<type>\w+)(?:\((?P<size>\d+)\))?/', $row['Type'], $match);

           $fields[$table][$row['Field']] = [
             'type' => $match['type'],
             'size' => isset($match['size']) ? (int)$match['size'] : false,
             'key' => $row['Key']
           ];
        }//end while
      }//end if self::$fields

      return self::$fields[$table];
   }//end getFields()
 }//end foo

Regex Sandbox

Which should give you something like this:

  //-note- we're returning only $fields['someTable'] in the example
  $fields = [
      'someTable' => [
           'ID' => ['type' => 'int', 'size' => 10, 'key' => 'PRI']
         ], [...]
      ], [...]
   ];

Then when you make your dynamic query:

 class foo{
     //eg inputs (with sql injection)
     //$table = 'someTable';
     //$args = ['ID' => 1, '1 OR 1 --' => '']
     public function Select($table, array $args){
        $fields = $this->getFields($table); //retuns ['ID' => [...]]

        $allowedArgs = array_intersect_key($args, $fields); //results in ['ID' => 1], removing key '1 OR 1 --'

        //escaping with backtic ` is a good idea, it adds a tiny bit of security too.
        //eg.  "SELECT * FROM `admin WHERE 1 --`"  this is a sql error
        //that said it's mostly for reserved words and spaces in table names etc..
        $query = "SELECT * FROM `{$table}`";

        $where = [];
        $params = [];

        foreach($allowedArgs as $col => $arg){
            //backtic column names too
            $where[] = "`{$col}` = :{$col}";  // 'ID = :ID'
            $params[$col] = $arg;
        }

        if(!empty($where)) $query .= ' WHERE '.implode(' AND ', $where);

        $this->db->prepare($query);
        return $this->db->execute($params);
    } //end Select()
 }//end foo

Output would be something like this:

$foo->Select('someTable', ['ID' => 1, '1 OR 1 --' => '']);
//note the SQLInjection key is removed by array_intersect_key
$query = "SELECT * FROM `someTable` WHERE `ID` = :ID"
//in PDO the ':' for execute arguments are optional
$params = ['ID' => 1];

  array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

So by having the schema dynamically pulled from the DB we can filter out bad Keys that would become column names in the SQL.  Also because it's dynamic (you should store it once per request, so do the describe query once) if we modify the schema we don't have any issues with our code.  It just adapts based on the arguments and the schema.

The only problem with this (the tables being dynamic) is they could potentially access other tables you don't want them too. But only if they are valid tables.  If that is a concern you can always create the table array manually or explicitly remove those tables you don't want end users having access to, with unset etc...

Additional Error checking

You can also throw an exception by comparing the count of $args and $allowedArgs Like this:

class foo{

  //eg inputs (with sql injection) ['ID' => 1, '1 OR 1 --' => '']
  public function Select($table, array $args){
    $fields = $this->getFields($table);
    $allowedArgs = array_intersect_key($args, $fields);

    if(count($args) != count($allowedArgs)){
       $diff = array_diff_key($args, $allowedArgs);
       throw new UnknownColumn(implode(',', array_keys($diff)));
    }
    ....
  }//end Select()
}//end foo

The above would throw a UnknownColumn (assuming that exception exists) that says something like this:

//$foo->Select('someTable', ['ID' => 1, '1 OR 1 --' => '']);
Exception UnknownColumn: "1 OR 1 --" IN somefile.php ON line 123

If you did some table that doesn't exist (as I showed above) you would get an exception from ckTable() which is chained through getFields:

//$foo->Select('1 OR 1', ['ID' => 1, '1 OR 1 --' => '']);
Exception UnknownTable: "1 OR 1" IN somefile.php ON line 123

Obviously you can add more complexity such as if it's and AND or an OR.  Argument groups such as exclusive ORs.  Type checks, size checks etc.  Basically whatever you want as you will have all the schema data at your fingertips.

I actually have a DB class that basically does this to build dynamic Insert and Update queries.  For example in the above I know that ID is the Pkey of the table so if its present in the arguments, I know that is an update of row with {x} ID.  If not then it's an insert etc...  Unfortunately my DB class has some dependencies and I can't share it without removing some of my employers requirements.  It does a lot of other things too, like handling multiple databases, different comparison operators, logical groups etc.  I should refactor it and put it on Git (one of these days).

Anyway, I should re-iterate you can also do this with a simple array (instead of getting the schema) that you manually built. Essentially a whitelist the columns or tables.  But, if you edit the schema you will likely have to modify your code.

Cheers!

PS. I didn't test any of this, I like PDO so I used it for the code.  But it should be pretty close.


Using operator== on doubles isn't usually a good idea, although it may be okay in the TestSpike case as you know you've assigned exactly 1.0 to it previously.

I would write GenerateSpike as follows:

void GenerateSpike(Complex* data, int length) {
  std::fill(data, data+length, 0.0);
  if (length >= 2)
    data[1] = 1.0;
}

By the way, you're not checking that the array is of sufficient length in TestSpike.

stepSize in FFT does not depend on the parameters of the second-outermost loop, so it should be in the outermost loop.  You should also use stepSize instead of bflySize/2 in the call to butterfly.

About testing:  w, butterfly, Reverse, and FFT all seem to be pure functions, so you can test them simply by checking the return value.  You might want to get a framework like GTest or Boost.Test to make them easier to write.


JavaScript telegram bot that sends images based on user search

// Request module
const request = require('request');

// Telebot module
const Telebot = require('telebot');

// Bot
const bot = new Telebot("YOUR TELEGRAM API TOKEN");

// DOMParser
const jsdom = require('jsdom');
const { JSDOM } = jsdom;

First of all is the comment noise. It's pretty clear what the code is already doing. You don't need to put comments on code that's already obvious. If you really need comments, save it for "weird" cases or things that is normally done one way yet you did it in another.

// /start command
bot.on('/start', (msg) => msg.reply.text('Hello! For informations about usage, creator, etc., please use the command /help!'));

// /help command
bot.on('/help', (msg) => msg.reply.text('Usage:\n /imageof <your_word> sends you an random image.\nExample:\n/imageof dog - You\'ll get an random image of a dog.\n\nAbout:\nVersion: 2.0\nCreator: @CodeFox\nGitHub: https://github.com/CodeF0x/image-search-telegram-bot\nAll images are taken from https://unsplash.com.'));

This is fine for now. But should your app grow, consider putting the messages in a dedicated object. This allows you to easily look up and modification of messaging without diving into code.

    var html = new JSDOM(response.body); // Parse the response
    var images = html.window.document.getElementsByClassName('_2zEKz'); // Get all images - in this case by class name, otherwise we would get profile pictures too
    var sources = []; // Array to pick random url from

I find it strange that you use const on the stuff above, but var down here.

    var images = html.window.document.getElementsByClassName('_2zEKz'); // Get all images - in this case by class name, otherwise we would get profile pictures too
    var sources = []; // Array to pick random url from
    for (var i = 0; i < images.length; i++) { // Loop through all images and push only valid url to the array
        if (images[i].src.includes('https')) {
            sources.push(images[i].src);
        }
    }

Given the existence of array methods that let you transform one array to another, I find this pattern of "create array and push items from another array into it" an anti-pattern. Use array.map and array.filter instead. Also, you might want to check if https is actually the start of src.

const sources = Array.prototype.slice.call(images) // Convert NodeList to regular array.
  .filter(img => img.src.indexOf('https') === 0)   // Only https images
  .map(img => img.src)                             // Extract src


Scala implementation of @rolfl's integer-partitioning algorithm

Keep in mind that I likely know less about scala than you and that this is my first review ;)

  Is there a way to write topUp without explicit recursion, yet still avoiding ::: concatenation?

I don't think so, but I may be wrong.

  Is the : Option[Sum] type annotation on Some(List.fill(n)(1)) avoidable?

Yes! You can use the Option type constructor like this:

Iterator.iterate(Option(List.fill(n)(1)))(advance)

  There seems to be a lot of Option / None / Some noise in advance. Is there a better way to handle the termination condition? (Perhaps by using lift?)

I think so, but not with lift. This just uses the standard map and filter (please let me know if this is incorrect logic).

def advance(partition: Option[Sum]): Option[Sum] =
   partition.filter(_.size > 1)
            .map(p => topUp(p.head - 1, p.tail.head + 1 :: p.tail.tail))

  Similarly, Iterator.iterate(…)(…).takeWhile(! _.isEmpty).map(_.get) seems cumbersome. Is there a less verbose way to say "repeatedly apply this function until exhausted" using the standard Scala library?

I really don't know.

One minor point. Here

Iterator.iterate(Some(List.fill(n)(1)): Option[Sum])(advance)
        .takeWhile(! _.isEmpty)
        .map(_.get)

You use ! _.isEmpty, but option has a perfect method for you, isDefined.


Best way to use an array that is returned from a function immediately in PHP

So, .. you want to simply check whether a certain key in an array is set to a certain value.

You can't do this directly on the function call because older PHP versions don't support array dereferencing. You are right when saying you'll need an intermediate variable.

The only question remaining is what to name it. Considering that the variable will probably be situated in a really small scope, don't worry about it too much. There is a saying which says, the bigger the scope, the bigger the name. You could just name it $list.

Old replies:

  Your code does something else as what
  you describe? If you want to see
  whether a given value is present in
  the array, use in_array().

  UPDATE:

  I believe I understand what you are
  trying to accomplish now. You just
  want to see whether the key is set?

  array_key_exists()

  PHP has got a pretty good online API,
  be sure to check it for existing
  implementations when looking for a
  solution.


Tracking 1400+ client codes, multi-threading nightmare

First, I'm pretty sure that it's impossible for
os.chdir(path)

to meaningfully apply different working directories per thread; and even if it were possible it would be a bad idea. subprocess supports a cwd parameter directly that you should use.
If you were opening files yourself, you would want to make a semaphore where the lock only applies to the section of the code where the file is opened. However, you aren't opening the files - it's probably your invocation of git that opens the most files.
I think the only practical way around this is to just limit the number of concurrent threads. You could either estimate this ahead of time, or keep spinning up threads until you hit the first OSError and start no new threads, running one-out-one-in until your work pool is complete.
If you deeply care about performance, subprocess-ing out to git should be replaced with in-process computation; either calling into a library or manually processing entries in .git (I have not researched either).


Well for starters:

int(str(x)[-1]) is a really expensive operation:

Go from integer (x) to a string that represents X
Get the last element as a char [-1]
Transform that char back to an integer

Given what you're trying to do (find if the last digit is a 5), the same operation can be achieved with x%10==5 or x%51=5 (all integer operations, way less expensive).  This could be damaging your performance a lot.

Doing a quick experiment:

$> def test1():
    k = time.clock()
    s = int(str(55)[-1]) is not 4
    t = time.clock()
    print(t-k)

$> def test2():
     k = time.clock()
     s = (55%10 != 4)
     t = time.clock()
     print(t-k)

$> test1()
1.682255089008322e-05
$> test2()
1.7107678900174506e-06

test2() takes one order of magnitude less than test1() just because of the type of operations.

For your problem space, I think trying to find useful properties of prime numbers that you can exploit is the best way to optimize.  For example, a number N doesn't have a prime divisor greater than Sqrt(N).


Zig-zag child element with Flexbox and JavaScript

Tiny adjustment : you can update all your objects in your first loop and get rid of the second.

var reverseBoxes = function() {

    var flexItems = document.querySelectorAll(".child"),
        flexItemsCount = flexItems.length,
        reverseAt = flexItems.length / 2,
        breakPoint = 480;

    if (window.innerWidth > breakPoint) {
        for (var i = reverseAt; i < flexItemsCount; i++) {
            flexItems[i].style.order = flexItemsCount - i;
            // First half of items
            flexItems[flexItemsCount - i - 1].style.width = (100 / flexItemsCount) * 2 - 2 + "%";
            flexItems[flexItemsCount - i - 1].style.height = "auto";
            // Second half of items
            flexItems[i].style.width = (100 / flexItemsCount) * 2 - 2 + "%";
            flexItems[i].style.height = "auto";
        }
    } else {
        for (var i = reverseAt; i < flexItemsCount; i++) {
            flexItems[i].style.order = flexItemsCount - i;
            // First half of items
            flexItems[flexItemsCount - i - 1].style.height = (100 / flexItemsCount) * 2 - 2 + "%";
            flexItems[flexItemsCount - i - 1].style.width = "auto";
            // Second half of items
            flexItems[i].style.height = (100 / flexItemsCount) * 2 - 2 + "%";
            flexItems[i].style.width = "auto";
        }
    }
}

Edit : got the if out of the for loop


Optimization of comparing two collections and get the changes

I would first make ChangeResult<T> truly immutable using sealed and readonly. It's unfortunate that we don't have true immutable syntax for automatic properties, but space is cheap, they say:

/// <summary>
/// Immutable class containing changes
/// </summary>
public sealed class ChangeResult<T> : IChangeResult<T>
{
    private readonly ReadOnlyCollection<T> deleted;

    private readonly ReadOnlyCollection<T> changed;

    private readonly ReadOnlyCollection<T> inserted;

    public ChangeResult(IList<T> deleted, IList<T> changed, IList<T> inserted)
    {
        this.deleted = new ReadOnlyCollection<T>(deleted);
        this.changed = new ReadOnlyCollection<T>(changed);
        this.inserted = new ReadOnlyCollection<T>(inserted);
    }

    public IList<T> Deleted
    {
        get
        {
            return this.deleted;
        }
    }

    public IList<T> Changed
    {
        get
        {
            return this.changed;
        }
    }

    public IList<T> Inserted
    {
        get
        {
            return this.inserted;
        }
    }
}

and because it's good design to program to interfaces, I extracted one:

public interface IChangeResult<T>
{
    IList<T> Deleted
    {
        get;
    }

    IList<T> Changed
    {
        get;
    }

    IList<T> Inserted
    {
        get;
    }
}

Then, in your CompareTo<TSource, TKey>() method, I have it return said interface. Also, I expand the deleted and changed lists to the capacity of the local enumerable (converted to a list locally so an expensive enumerable doesn't get iterated multiple times). This may be overkill in some cases, but in the worst cases, you wind up eliminating potentially expensive list expansion reallocations. A classic speed-vs-space tradeoff. I would then posit that this is actually a great algorithm to go parallel with, as long as you don't care about the order in the three lists:

/// <summary>
/// Gets the changes [Deleted, changed, inserted] comparing this collection to another.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="local">The source collection.</param>
/// <param name="remote">The remote collection to compare against.</param>
/// <param name="keySelector">The primary key selector function</param>
/// <returns></returns>
public static IChangeResult<TSource> CompareTo<TSource, TKey>(
    this IEnumerable<TSource> local,
    IEnumerable<TSource> remote,
    Func<TSource, TKey> keySelector)
{
    if (local == null)
    {
        throw new ArgumentNullException("local");
    }

    if (remote == null)
    {
        throw new ArgumentNullException("remote");
    }

    if (keySelector == null)
    {
        throw new ArgumentNullException("keySelector");
    }

    local = local.ToList();

    var remoteKeyValues = remote.ToDictionary(keySelector);
    var deleted = new List<TSource>(local.Count());
    var changed = new List<TSource>(local.Count());
    var localKeys = new HashSet<TKey>();

    Parallel.ForEach(
        local,
        localItem =>
        {
            var localKey = keySelector(localItem);

            lock (localKeys)
            {
                localKeys.Add(localKey);
            }

            /* Check if primary key exists in both local and remote
             * and if so check if changed, if not it has been deleted
             */
            TSource changeCandidate;

            if (remoteKeyValues.TryGetValue(localKey, out changeCandidate))
            {
                if (changeCandidate.Equals(localItem))
                {
                    return;
                }

                lock (changed)
                {
                    changed.Add(changeCandidate);
                }
            }
            else
            {
                lock (deleted)
                {
                    deleted.Add(localItem);
                }
            }
        });

    var inserted = remoteKeyValues
        .AsParallel()
        .Where(x => !localKeys.Contains(x.Key))
        .Select(x => x.Value)
        .ToList();

    return new ChangeResult<TSource>(deleted, changed, inserted);
}


Review of my CSS for aligning the navigation icons and text in a footer menu

HTML:

Since the the navigation is the only thing inside your <div class="footer">, how about moving the class to the ul?
Instead of using span's there, you can add the &raquo; to a pseudo-element (see the CSS part)

CSS:

For your arrows, you should use pseudo-elements:

.footer a:after {
    content: "\00BB";
    float: right;
    padding: 9px;
    border-radius: 2px;
    background-color: #ca0000; /* hex-based values are shorter */
}

You won't need to hide them on bigger screens either, if you define them inside a media query, because they're not present in your markup
Instead of actually writing the links in capital letters, write them like you would in normal language and make them appear uppercase with text-transform: uppercase;
I don't see a purpose for the min-width: 1px part in your media query. Just unnecessary.
Defining display: block; on list-items is not necessary, because they behave like block-level elements already
Select .footer li instead of .footer ul li and .footer a instead of .footer ul li a. No need for this extra layer of specificity and dependency. There will probably no other links and list-items in this ul other than these you already have


My first Qt application - a multiple-state window with a menu

That's a good first Qt program.  Most of my comments are preferences rather than rules, but I'll try to provide justifications.

In main(), no need to new

I would write

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    MainWindow mw;
    mw.show();
    return app.exec();
}

That way, you don't need to remember to delete the objects app and mw.  (You can argue that there's no need to clean up when you're exiting, but I find it helps to avoid false-positives when I'm checking memory correctness with Valgrind).

In constructors, prefer to use initializers

I can write

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent),
      layout(new QStackedLayout(this))
{

This allows us to declare layout as a const pointer, for increased safety:

QStackedLayout *const layout;

Note that I've passed this to the QStackedLayout constructor: that ensures that it always has an owner that's responsible for deleting it, and it installs it as the layout manager for the MainWindow widget (saving us a line of code).

Use new-style connect() when you can

Unless you don't know the complete type of the objects being connected, you can connect by pointer-to-member-function.  This allows more errors to be caught at compilation time (a Good Thing):

MenuPage::MenuPage(MainWindow *parent)
    : QWidget(parent),
      layout(new QVBoxLayout(this)),
      signalMapper(new QSignalMapper(this))
{
    void(QSignalMapper::*signal)(int) = &QSignalMapper::mapped;
    connect(signalMapper, signal, parent, &MainWindow::setPage);
}

However, I'd move the signal mapper and connect() call up into MainWindow, so that MenuPage doesn't need to know about its parent.

Reduce coupling

Both MainWindow and MenuPage need to know about MainWindow in their constructors.  Although we can simply pass a QObject, and connect by name, there's still coupling because they impose requirements on the slots exposed, so they can't be used more generally.

The way to fix this coupling is for the pages to emit a signal to indicate user actions; the MainWindow (which knows about its contents) can then connect those signals to the relevant actions.

MenuPage then looks like

public:
    explicit MenuPage(QWidget *parent);
signals:
    void buttonPressed(int button_number);

and its constructor is now

MenuPage::MenuPage(QWidget *parent)
    : QWidget(parent),
      layout(new QVBoxLayout(this)),
      signalMapper(new QSignalMapper(this))
{
    void(QSignalMapper::*signal)(int) = &QSignalMapper::mapped;
    connect(signalMapper, signal, this, &MenuPage::buttonPressed);
}

(The temporary variable signal is to avoid the problem of connecting overloaded signals and slots in Qt 5).

In MainWindow, we connect it directly:

connect(menuPage, &MenuPage::buttonPressed, layout, &QStackedLayout::setCurrentIndex);

We can do something similar in SubPage, but this is a little simpler, as we don't have an overloaded signal.  So just create a signal (call it done(), perhaps) and make the page's constructor connect the button's clicked() to the page's done().

A memory leak

Here, we allocate a new QString, which is never released:

QString label = (new QString("Page %1")) -> arg(nButtons);

It's easy to fix this - QString objects are fine to pass by value:

QString label = QString(tr("Page %1")).arg(nButtons);

Allow for translation

If you get into the habit of using tr() on all your user-facing strings, you've made a good start on internationalizing your application

Full worked example

I've inlined the methods just to make this smaller - I don't expect that in a real, multiple-source-file program.

#include <QWidget>
#include <QPushButton>
#include <QStackedLayout>
#include <QVBoxLayout>
#include <QSignalMapper>
#include <QLabel>

class MenuPage : public QWidget
{
    Q_OBJECT

public:
    explicit MenuPage(QWidget *parent)
        : QWidget(parent),
          layout(new QVBoxLayout(this)),
          signalMapper(new QSignalMapper(this))
    {
        void(QSignalMapper::*signal)(int) = &QSignalMapper::mapped;
        connect(signalMapper, signal, this, &MenuPage::buttonPressed);
    }

    void addButton()
    {
        ++nButtons;

        QString label = QString(tr("Page %1")).arg(nButtons);
        QPushButton *button = new QPushButton(label, this);
        layout->addWidget(button);

        signalMapper->setMapping(button, nButtons);
        connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
    }

signals:
    void buttonPressed(int button_number);

private:
    QVBoxLayout *const layout;
    QSignalMapper *const signalMapper;
    int nButtons = 0;
};

class SubPage : public QWidget
{
    Q_OBJECT

public:
    explicit SubPage(const QString& messageText, QWidget *parent)
        : QWidget(parent),
          message(new QLabel(messageText, this)),
          backButton(new QPushButton(tr("Back"), this))
    {
        QVBoxLayout *const layout = new QVBoxLayout(this);
        layout->addWidget(message);
        layout->addWidget(backButton);
        connect(backButton, &QPushButton::clicked, this, &SubPage::done);
    }

signals:
    void done();

private:
    QLabel *const message;
    QPushButton *const backButton;
};

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0)
        : QWidget(parent),
          layout(new QStackedLayout(this))
    {
        setWindowTitle(tr("Application"));
        MenuPage *const menuPage = new MenuPage(this);
        SubPage  *const page1    = new SubPage(tr("This is page one."), this);
        SubPage  *const page2    = new SubPage(tr("This is page two."), this);

        layout->addWidget(menuPage);
        layout->addWidget(page1);
        layout->addWidget(page2);
        layout->setCurrentIndex(0);

        menuPage->addButton();
        menuPage->addButton();
        connect(menuPage, &MenuPage::buttonPressed, layout, &QStackedLayout::setCurrentIndex);
        connect(page1, &SubPage::done, this, &MainWindow::goToMenu);
        connect(page2, &SubPage::done, this, &MainWindow::goToMenu);
    }

private:
    QStackedLayout *const layout;
public slots:
    void setPage(int index)
    {
        layout->setCurrentIndex(index);
    }

    void goToMenu()
    {
        layout->setCurrentIndex(0);
    }
};

#include <QApplication>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    MainWindow mw;
    mw.show();
    return app.exec();
}

#include "165088_moc.cpp"