Did not pass the interview about an RPN Calculator

I don't know how your assignment looked exactly, so some of the below may be misguided criticisms. I've just tried to poke as many holes in the code as possible; fair or otherwise. Something will probably overlap with your interviewer's thoughts. But of course, I don't know what that might be, so there's no real order to these points - I just wrote them as I thought of them.

Separate the logic from the REPL user interface. It'd be nicer if you could push input to the calculator from anywhere. And it'd be much easier to test the code.
Speaking of: Tests would be nice to see. If the place you interviewed is really big on TDD/BDD, maybe that's what they wanted to see more than anything. Interview assignments (when done well) are as much about the candidate's process as it is the result.
#start is a rather long method and it pretty much does, well, everything. If you call it, it starts a loop you won't be able to exit from code. That's kinda scary. The method just does too much.
Again, a different structure will help. Also, Ruby's case statements are pretty powerful. Might come in handy instead of if...elsif...else.
The regex used to match numbers is very loose. It'll accept anything as long as there's a digit somewhere in it. So "u wot m8" is technically a number in the eyes of your code.
The (res.to_i == res) ? (puts res.to_i) : (puts "%0.1f" % res) line is several kinds of nasty. It'd be much cleaner if you put the puts first, and used the ternary for its arguments instead. Right now it's "if A then puts, otherwise if B then... well, then also puts". Also you don't want to use a ternary's branches for anything except the simplest things. You'll want to use them to decide between values, not actions. So calling to_i on stuff or doing simple arithmetic is fine, but don't go too far. If you want to do more, use a proper if..else.
Something like this would make more sense:

puts res.to_i == res ? res : "%0.1f" % res

Or you could use %g instead, which'll ignore decimals for integers:

puts "%g" % res.round(1)

However, it'll truncate large numbers so it's not a clear winner.
Your code accepts a list of operators, but it assumes:

that any string you pass is actually valid (otherwise the reduce call will break)
that all the operators have an arity of 2.

So the code is halfway configurable, and halfway not. Suppose you want to support a ! operator for factorial: For one, ! is not a method on Float, so reduce(n.to_sym) will fail. For another, the factorial operator only has one operand, not two.
Frankly, I wouldn't bother making this configurable unless I was asked to. Or I'd ask if I was unsure, rather than make assumptions.
Speaking of operator arity: The script crashes if the stack's empty and you enter an operator. You assumed that all operators would always have two operands, but you also assumed that there always are two operands.
Not sure what the last example input (* 24) is supposed to do. Push 24 to the stack and multiply? Complain about the input? (Edit: As pointed out in the comments, it's probably just missing linebreak. That would make sense. Even though I should've figured it out myself, I'll just turn that around and say you should proof-read your code comments and documentation :)
Regardless of its intended meaning, it's interesting as test input: It prints * 24 back to you, because you print the raw input, rather than the parsed value. So you don't know what the script actually made of your input. What it did, though, was push 0.0 to the stack, because the code thinks it's a number, but "* 24".to_f just returns zero.
Speaking of what you print, echoing the user's input right back is sort of pointless. I mean, the user just wrote it. Printing the stack (or at least the input after interpretation) would likely be more useful.
Naming. The variable n is too short to mean much. I suppose it means "number", but that only makes sense if the input is indeed a number. I'd just call it input. Also, res is unnecessarily shortened. It's not that bad to write result instead. There's really no reason to abbreviate.
Otherwise, naming is fine - I like that operators and operands are both full words. Still, as mentioned, #start is not a great name for a method that does everything including reading, evaluating, printing and (ironically) stopping. But that's less a question of changing the name; the method itself should be refactored.
If you want to be fancy, you could make a Stack class instead, and implement #*, #+, etc. as methods on that class.
Small fry, but ["+","-","*","/"] could be written more simply as %w(+ - * /). But again, I'd skip making it configurable.

Now, as mentioned I don't know what your exact exercise was. You built a REPL calculator, but perhaps they wanted something that could parse a full expression like "3 4 * 2 /" => 6? Or a calculator "engine" that's callable from code? If that's the case, you kinda went the wrong way to begin with :)

Edit: I should add that I don't intend for this to be harsh. As 200_success points out, it's not at all bad for < 30 mins of coding while under pressure.


A conceptual question, those are always tricky.

Organizing by namespace is not a bad idea, though I would lowercase your namespace ( Header -> header etc. )

Furthermore, I would suggest to look into Movel View Controller and let each namespace have a model, view and controller.

The binding of events is in the realm of the controller. So when you initialize the controller, that is where can you do all the binding.

So in document.ready you can call centralBody.init() which could call centralBody.controller.init().


.pop(0) would remove the first element from a list - this is a \$O(n)\$ operation since everything after must "shift" (Time Complexity reference).

I would not pop from left and right subarrays and instead keep track of indexes in both the left and right lists:

def merge(left, right):
    merge_result = []

    left_index = right_index = 0
    while left_index < len(left) and right_index < len(right):
        if left[left_index] > right[right_index]:
            merge_result.append(right[right_index])
            right_index += 1
        else:
            merge_result.append(left[left_index])
            left_index += 1

    merge_result += left[left_index:]
    merge_result += right[right_index:]

    return merge_result

And, if you are preparing for an interview, make sure to write this function from memory couple times - it'll persist in your memory pretty soon - focus on the pattern (using left and right indexes for merging), don't try to remember the code line-by-line.


Quickest way of finding the largest integer n such that n! has length of m bits

import math
n = int(input())
while n != 0:
    n = (n - 1960) / 10 + 2

What does n represent now? n as a name for the value which is called y in the task description is already unnecessarily obscure, but aliasing it really confuses things.

In addition, note that in Python / does floating point division. If the output for 1969 should be the same as the output for 1960 (and I'm pretty sure the spec requires that) then there's a bug here.

    m = pow(2,n)

What does m represent? If you want people to review your code, use descriptive names!

    while m > 0:
        m -= math.log(i,2)
        i += 1

How many times does this loop execute for the largest possible input? How can you avoid a linear loop? (Hint: a certain Stirling analysed \$\log n!\$ ...)

(Or, arguably cheating, there are only 21 decades in view, so you could hard-code a lookup.)


Before I start: Thank you so much for making this code easily readable! Thank you from the bottom of my heart!

Second thing that I have noticed was the name. It's wrong! If it is a sptrinf-like function, give it the right name. sprintf! Done! No overly complicated boring names.

You have an argument called string. Please, don't do that. In fact, remove it's name! You know it is the first element.

You can do this:

var text = arguments[0];
for (var i = 1; i < arguments.length; i++) {

Done! But it won't be needed and you will see why.

You still didn't learn: Store the length in a local variable. Always! Like this:

for (var i = 1, length = args.length; i < length; i++) {

Accessing a property in an object (in this case, an array) is slower than accessing a loval variable. By setting the local variable with that slow property, we increase performance.

It is really a great idea to have literal regular expressions, but the whole code is quite... shady... Specially the useless validations!

You expect a string to be a real string so you can do something... But why? What about a number? What about an array? What around something else? Why can't I convert anything into a string? Every single object has the .toString() method.

And why that NaN there? What is it for? Is that to say it is NaN?

The %o is doing something somewhat somewhere that I don't get. By the C++ documentation and the PHP documentation specify that this is the octal representation.

And now, the questions:

Why do you check if an argument is a string before converting it to string?
Why do you check if an argument is og any type before converting?
why don't you do any kind of validation?
Why are you using exec?

I would never do it on this way. It's so frail and picky. It's so hard to change anything without breaking it. You have to deal with things you should, like breaking a string in 3 parts and replacing the middle part with something. That's a bad way to do a .replace().

I would do like this:

function sprintf(){
    var toBase = function(value, base){
        //converts to the required bases
        return (parseInt(value, 10) || 0).toString(base);
    };
    var map = {
        s: function(value){
            return value.toString();
        },
        d: function(value){
            return toBase(value, 10);
        },
        i: function(value){
            return this.d(value);
        },
        b: function(value){
            //binary conversion
            return toBase(value, 2);
        },
        o: function(value){
            //octal conversion
            return toBase(value, 8);
        },
        x: function(value){
            //hexadecimal conversion
            return toBase(value, 16);
        },
        X: function(value){
            //HEXADECIMAL CONVERSION IN CAPITALS
            return toBase(value, 16).toUpperCase();
        },
        e: function(value){
            //scientific notation
            return (parseFloat(value, 10) || 0).toExponential();
        },
        E: function(value){
            return this.e(value, 10).toUpperCase();
        },
        f: function(value){
            //floating point
            return (parseFloat(value, 10) || '0.0').toString();
        }
    };

    //crude way to extract the keys
    var keys = '';
    for(var k in map)
    {
        keys += k;
    }
    var args = Array.prototype.slice.call(arguments).slice();

    return args.shift().toString().replace(new RegExp('%([' + keys + '])','g'),function(_, type){
        if(!args.length)
        {
            throw new Error('Too few elements');//appropriate type here?
        }

        return map[type](args.shift());

    });
}

Come on! It's so easy to understand! You can change it's functionality easily!

If you want, you can remove that loop to fetch the keys and use this literal regular expression: /%([diobsxXeEf])/g. Same thing, but faster and less flexible.

And this is a "good enough" clone of the sprintf function. It doesn't support padding, float-number size specifitation and others. But, it works for the bare minimum.

Outside the scope of this review, thanks to you, I finally have a function to write my polyglot questions! Also, you may want to look at http://phpjs.org/functions/sprintf/ if you want a perfect clone of the sprintf function.

To reflect closely the desired implementation, one can change the map variable. I went a bit further and changed all unnecessary things. To be consistent with the MDN documentation and the Chrome console API documentation, you can do this:

function sprintf(){
    var map = {
        s: function(value){
            return value.toString();
        },
        d: function(value){
            return (parseInt(value, 10) || 0).toString();
        },
        i: function(value){
            return this.d(value);
        }
        f: function(value){
            return (parseFloat(value, 10) || '0.0').toString();
        }
    };

    var args = Array.prototype.slice.call(arguments).slice();

    return args.shift().toString().replace(/%([difs])/g,function(_, type){
        if(!args.length)
        {
            throw new Error('Too few elements');
        }

        return map[type](args.shift());

    });
}

The %o, %O and %c specifiers are implemented internally and isn't possible to implement using this method. %c and %Cwork on elements, by creating a list in the console or a link to the element to show in the Element Inspector. The %c uses CSS styles to style the output in the console itself.


Use a cache to save fibonacci numbers, will improve speed of the program. That way you won't have to compute the numbers again at each loop.

'''
Cached_fib
'''
def memoize(f):
    cache = {}
    return lambda *args: cache[args] if args in cache else cache.update({args: f(*args)}) or cache[args]

@memoize
def fib(n):
    return n if n < 2 else fib(n-2) + fib(n-1)

def find_closest_fib(l):
    for num in l:
        i = 1
        while 2*num>fib(i)+fib(i+1):
            i += 1
        print ('Nearest fib number = {} \n for num {}\n'.format(fib(i), num))

if __name__ == '__main__':
    l = (60, 234234231, 35342454, 27000000000000)
    start_time = timeit.default_timer()
    find_closest_fib(l)
    print('Elapsed time: ', timeit.default_timer() - start_time)

    start_time = timeit.default_timer()
    find_fib_op(l)
    print('Elapsed time: ', timeit.default_timer() - start_time)

Output new version

Nearest fib number = 55 for num 60
Nearest fib number = 267914296 for num 234234231
Nearest fib number = 39088169 for num 35342454
Nearest fib number = 27777890035288 for num 27000000000000

Timing of implementation

Cached fibonacci

  Elapsed time: 0.06364319414684597

OP fibonacci

  Elapsed time: 0.23451719927193976


Sorting large 1GB file with 100 millions numbers using merge sort

Don't do this

using namespace std;

This is a bad habit that will get you into a lot of trouble. Please break the habit before it becomes ingrained.

see: Why is “using namespace std” considered bad practice?

Note: The reason the "standard" library uses the namespace std:: is so that it is not a large burden to use as a prefix.

Prefer '\n' over std::endl

Others have mentioned it.
The problem is that std::endl performs a flush of the stream (in addition to adding '\n') as a result this makes using the stream very inefficient as you need to wait to write every value to disk before continuing.

Let the system flush its own internal buffer at the optimum time. It will do this automatically without any of your help.

Reading Value

I see that you are not using the standard stream to integer conversion.

long value;
stream >> value;

but rather using the line reader than using atol() to convert the string into a number.

I assume you have done the appropriate speed tests and found this to be faster on the scale that you are using and you don't need all the facilities that the stream operator>> provides.

If this is true then I would wrap up that call so that you can use atol() and operator>> to make your code more readable.

struct Number
{
    long value;
    static std::string  reusableBuffer;
    operator long() const {return value;}
    friend std::istream& operator>>(std::istream& str, Number& data) {
        std::getline(str, data.reusableBuffer);
        data.value = std::atol(data.reusableBuffer);
        return str;
    }
};

Now you can read numbers using operator>> but still have the speed you have verified with atol().

Never test for eof in a loop

while (!sorted_1.eof() ||!sorted_2.eof());}

The problem becomes that if there is an error on the stream then you end up going into an infinite loop (if there is an error reading from the stream it goes into a bad state until you  reset it. While in a bad state it will refuse to read any more values and thus never reach the end of the file.

Rather than testing for eof() you should check to make sure the stream is good() (if it reaches eof() or error() then it will no longer be good() so your loop will still exit correctly).

The easy way to test for good() is to simply use the stream in a boolean context (an expression that is expected to be bool) and the compiler will convert the stream to bool which results in a call to good().

while(sorted_1 || sorted_2);

Merge I think can be simplified.

I think we can simplify that merge algorithm a lot.

Number number;
if (sorted1 >> number) {
    sorted1Value = number;
}
if (sorted2 >> number) {
    sorted2Value = number;
}
while (sorted1 && sorted2) {
    // Don't need to explicitly test if they are equal.
    // If they are equal always use the sorted1 file.
    // that way you get a stable sort (an important property for
    // sorted values in some situations).
    //
    // It also makes the code simpler.
    if (sorted1Value <= sorted2Value) {
        result << sorted1Value << "\n";
        sorted1 >> number;
        sorted1Value = number;
    }
    else {
        result << sorted2Value << "\n";
        sorted2 >> number;
        sorted2Value = number;
    }
}
// At this point one of the streams is empty.

Copy one file to another.

When you have merged all the values out of one file. Then the remaining numbers from the other file are simply copied to the destination. But there is no need to spend extra time converting those numbers from text to an integer then back into text. Simply copy the raw data from one file to the other.

// At this point one of the streams is empty.
if (stream1) {
    result << sorted1Value;
    result << stream1.rdbuf()
}
if (stream2) {
    result << sorted2Value;
    result << stream2.rdbuf()
}

Intermediate format

So the intermediate files don't need to be in human readable form. You spend a lot of time converting integers to and from text. Rather than doing this you could write the binary representation of the number to an intermediate file and then read it directly back into the number when merging.

// writing
result.write(reinterpret_cast<char*>(&sorted1Value), sizeof(sorted1Value));

// reading
stream1.read(reinterpret_cast<char*>(&sorted1Value), sizeof(sorted1Value));

Merging more than one file.

Currently you perform the merge operation 3 times. Once to merge parts 1 and 2 into a temp file. Then you merge 3 and 4 into a second temp file and finally you merge the temp files into the output.

Merging from different streams is not that memory intensive. So you should read from all the temporary files at the same time (within reason as long as you have less than a thousand part file).

So you should open all 4 temp files and read the values from them. Each iteration find the largest value from each of the 4 files write that to the output and read the next value.

Global State.

Global state

std::vector <long> vec;

int i=0,numberOfpieces=0;
string line,filename;

Is always considered a bad thing. Never use it. You can still get the same efficiencies by using local values in the appropriate places.

One thing you way want to do to increase the efficiency of std::vector is to reserve its size. That way it never needs to do any reallocation (which is expensive).

vec.reserve(25000000);

Note your use of <= in the for loop is very unusual.

for(i=1;i<=25000000;i++)

Normally this is written as:

for(i = 0; i < 25000000; ++i)

This is because indexes into arrays (vectors) always start at zero.


Review Solution 1
Sacrificing usability for the common consumer of your API in order to gain some usability for specific consumers that happen to subscribe on a multitude of events, should never be considered best practice.

Action<Game1, EventArgs> InitializeEvent;
public virtual void Initialize(object o, EventArgs e)
{
    // the average consumer does not want to cast here
    // if he only wants to be subscribed to this event ->
    InitializeEventArgs initializeEventArgs = (InitializeEventArgs)e;
}

Review Solution 2
Grouping events together is a better approach, since the common consumer is not impacted. It is an augmentation, rather than a substitution, of the event pattern. Though your implementation using a struct is viable, I would opt to use a more common approach - the Callback Interface.

public struct Events
{
    public Action<Game1, MoveEventArgs> MoveEvent { get; set; }
    public Action<Game1, InitializeEventArgs> InitializeEvent { get; set; }
    public Action<Game1, DrawEventArgs> DrawEvent { get; set; }
    public Action<Game1, LoadContentEventArgs> LoadContentEvent { get; set; }
}

Proposed Solution
You should determine whether to use either events, a callback interface or a mixture of both.
Let's assume you would like consumers to be able to subscribe to single events, and allow specific consumers to subscribe to all of them. The mixture of events and a callback interface could be implemented as follows.
Create event arguments
public class MoveEventArgs : EventArgs { /* .. impl */ }
public class InitializeEventArgs : EventArgs { /* .. impl */ }
public class DrawEventArgs : EventArgs { /* .. impl */ }
public class LoadContentEventArgs : EventArgs { /* .. impl */ }

Create a callback interface that bundles handlers for all the relevant events.
 public interface IGameListener
 {
      void OnMove(Game1 game, MoveEventArgs e);
      void OnInitialize(Game1 game, InitializeEventArgs e);
      void OnDraw(Game1 game, DrawEventArgs e);
      void OnLoadContent(Game1 game, LoadContentEventArgs e);
 }

As discussed, you may want to create an adapter. This allows derived classes to decide which event handlers to override.
public abstract class GameAdapter : IGameListener
{
      public virtual void OnMove(Game1 game, MoveEventArgs e) {}
      public virtual void OnInitialize(Game1 game, InitializeEventArgs e) {}
      public virtual void OnDraw(Game1 game, DrawEventArgs e) {}
      public virtual void OnLoadContent(Game1 game, LoadContentEventArgs e) {}
}

Game1 uses events and allows for registration of specific listeners. If you don't like to 'pollute' the game with these actions, you could let a mediator perform the registration of the callback interface. Argument checks are omitted for brevity.
 public class Game1
 {
        public event Action<Game1, MoveEventArgs> MoveEvent;
        public event Action<Game1, InitializeEventArgs> InitializeEvent;
        public event Action<Game1, DrawEventArgs> DrawEvent;
        public event Action<Game1, LoadContentEventArgs> LoadContentEvent;

        public void Register(IGameListener listener)
        {
            MoveEvent += listener.OnMove;
            InitializeEvent += listener.OnInitialize;
            DrawEvent += listener.OnDraw;
            LoadContentEvent += listener.OnLoadContent;
        }

        public void Unregister(IGameListener listener)
        {
            MoveEvent -= listener.OnMove;
            InitializeEvent -= listener.OnInitialize;
            DrawEvent -= listener.OnDraw;
            LoadContentEvent -= listener.OnLoadContent;
        }

        // other instance code ..
 }


Bug: The result of check_prefix depends on the order of values. Basically, it compares each pair of values once, but truncates only one of the two for comparison. On my Python 3.5 your test fails occasionally.
Duplicate values are also prefixes of one another. It is not necessary for is_consistent to check for both.
It is not necessary to handle the empty phonebook as a special case in is_consistent as the check functions return True swiftly anyway in that case. Thus the function can be simplified to

def is_consistent(self):
    return self.check_prefix()

A more efficient solution for check_prefix would be to sort the values and compare adjacent ones. Making use of pairwise from Itertool recipes, and the fact that the prefix will sort first:

def check_prefix(self):
    return not any(b.startswith(a)
                   for a, b in pairwise(sorted(self.get_values())))


I have a possible solution for your case, this is what I am thinking.
1) You can implement scrollViewDidEndDragging delegate and load your image for the visible cells.
for ex.

  - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    {
            [self loadImagesForOnScreenRows];
    }

loadIamgesForOnScreenRows  will look like:

- (void)loadImagesForOnScreenRows
{

    NSArray *visiblePaths = [self.tracksListing indexPathsForVisibleRows];

    for (NSIndexPath *indexPath in visiblePaths){
            [[self.tableView cellForRowAtIndexPath:indexPath] bindItemObject:record];
        }
    }
}

In my case bindItemObject is for downloading the image implemented in tableViewCell class, and record contains the url for the image.

The only problem which you will encounter in this case is, when the tableView appears for the first time.
In that case I suggest you to programmatically call the

[self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionTop
                                  animated:YES];

and give indexpath as indexpath for row:0 and section:0

I think this can solve your problem.


The std::vector<> is a dynamically sized container.  The allocation strategy is implementation dependent, but for sake of the argument, assume the .capacity() of a std::vector<> starts off at 1 and doubles each time the vector's size exceeds the current capacity.  This capacity increase requires a reallocation of storage, and possibly a copying of the entire array contents to a new location.  If you are generating 1 trillion primes, you'll need 40 reallocations and will have done 1 trillion number copies over the course of the 40 reallocations.  This is wasting time.  If the operating system gets involved with virtual memory paging, you are going to suck up a lot more time.

This overhead can be eliminated by simply .reserve(size_type n)-ing the expected size of the vector ahead of time.  With sufficient memory allocated to the vector upfront, no reallocations will occur, and no copies will occur.

    for (unsigned long long i = 7;; i += 2)
    {
        for (int j = 0; i % primes[j] != 0; ++j)
        {
            if (sqrt(i) <= primes[j])
            {

When i is a prime number or semi-prime number in the order of, say, one million, you are looping over all the prime numbers upto the square root of a million, to see if any of them can divide your current number.

How many different values will sqrt(i) evaluate to over those thousand iterations?  Or phrased another way, how many times are you computing the same square root?  You may want to move that sqrt(i) calculation out of the inner loop.

    for (unsigned long long i = 7;; i += 2)

If you let this loop run over night, or even over a fort-night, will this loop ever end?  No!  i will overflow the long long and become negative, and slowly increment back towards positive numbers and repeat.  Forever is not long enough.  Use, at the very least, i > 0 as the loop test condition.

A long long has at least 64 bits. A double has only a 52 bit mantissa.  This means when you pass a large long long to sqrt( ), you will end up losing a few bits of precision, which can make your sqrt() return slightly the wrong value.  When you test sqrt(i) <= primes[j], if i is greater than 2^52, and is a perfect square, you might return a value slightly less than the correct value and fail to test the last prime value, and erroneously declare the perfect square a prime number.

You are stuffing long long values into a std:vector<int> container.  After a while, they ain't gonna fit.

You are using long long for your prime number candidates, which means you expect to find some prime numbers above 2^31.

The Prime Number Theorem tells us the density of prime numbers in that range to be around 1/21.  Or, after testing numbers up to 21 billion, you should have found around 1 billion prime numbers.

Your prime number index j is declared as an int.  An int is only guaranteed to have 16 bits.  You would need at least a long to guarantee 32 bits.  But if you hope to find prime numbers up to 2^52, you have to expect to find 2^45 primes, which even exceeds a long.  Your j index should be a long long as well.

Finally, as mentioned in the comments, look at the Sieve of Eratosthenes.


Decorator to add key parameter support to an existing sort function

Python is open-source, and all the source code in the GitHub repository python/cpython. For a great deal of the built-ins, they can be found in cpython/Python/bltinmodule.c
. In the current revision, the beginning of the sorted function definitions is found at line 2175, and the actual function itself is found at line 2201.

However, I'm not sure that knowing the implementation of sorted can help you too much with optimizing heapsort, because sorted uses Timsort.

I can make a suggestion: decorators will always add overhead, and particularly in a case like this, it's probably better to just make a new version of the function that integrates the key parameter with the original function, though this answer might miss the entire point of your question.


What are k and a?  It looks like a is a loop counter variable, in which case it can be renamed to i and moved to the front of the first for loop.  As for k, rename it such that it conveys its purpose.  With the exception of loop counter variables such as i, variables shouldn't be a single character.
Many of the lines in the for loops are difficult to read, especially with all the bit-shifting.  Depending on the type of shift, the optimizing compiler may be able to replace some arithmetic operation with an appropriate bitshift.  But for others, it would help to leave comments to explain what's being done for each complex operation.
This is quite crammed together:

for (; globalPasses>>=1; ++a){
    barrier(CLK_GLOBAL_MEM_FENCE);
    while (*completeBlocks != 0);
    if (lid == 0) atomic_inc(completeBlocks);
    while (*completeBlocks < get_num_groups(0));
    if (lid == 0 && gid == 0) atomic_xchg(completeBlocks,0);
    k = (gid >> a << (a+1)) + (1<<a);
    output[k + (lid&((1<<a)-1))] = output[k - 1] + output[k + (gid&((1<<a)-1))];
};

You should isolate the while loops so that it's easy to see that they're busy-waits.  You could also consider using curly braces for the if statements.  Finally, consider adding whitespace between the operators for more readability.

for (; globalPasses >>= 1; ++a) {
    barrier(CLK_GLOBAL_MEM_FENCE);

    while (*completeBlocks != 0);

    if (lid == 0) {
        atomic_inc(completeBlocks);
    }

    while (*completeBlocks < get_num_groups(0));

    if (lid == 0 && gid == 0) {
        atomic_xchg(completeBlocks, 0);
    }

    k = (gid >> a << (a + 1)) + (1 << a);

    output[k + (lid&((1 << a) - 1))] =
        output[k - 1] + output[k + (gid&((1 < <a) - 1))];
};


You shouldn't use bare excepts, this is as it can prevent things like KeyboardInterrupt.
That's just bad.
password is a better variable name than pw, at first I was quite confused about what it was.
You can return early if you know the password is not valid.
This can save you a lot of checks in your program.
Your program goes through each character and checks if it's one of the four valid groups.
Instead you can check if it shares any items with that set.
If it doesn't it's not valid.
You're creating warnings un-neededly, currently, excluding the cast, the functionality is the same if it's a list.
Instead of a warning you should either raise an error, or return.

This is as if I pass ['P', 'a', '$', '2', 1, 2] it probably shouldn't return True, which it might on a different implementation.
Instead you can either hard limit your input to strings, or check if the contents of the input are strings. Or both.

In short, just change password to a set, and use & with the groups it needs to be a part of.
This can remove the need to make the function check_number, and makes the code much more readable:

import string

def check_validity(password):
    ''' Return True if input pw is valid, and return False if invalid.'''
    if isinstance(password, str) \
            or not all(isinstance(c, str) for c in password):
        return False

    if len(password) < 6:
        return False

    password = set(password)
    checks = [
        set(string.ascii_lowercase),
        set(string.ascii_uppercase),
        set(string.digits),
        {'$', '#', '@'},
    ]

    for check in checks:
        if not check & password:
            return False
    return True

print check_validity('P@ss1234')


QPlainTextEdit subclass function to indent lines in selection

Some of these comments can be removed:

Too obvious:

// Do nothing if we don't have a selection.

Noisy:

// Done!

These initialized variables:

int spos = curs.anchor(), epos = curs.position();

should be on separate lines for better maintenance:

int spos = curs.anchor();
int epos = curs.position();

No need to do a manual swap:

if(spos > epos)
{
    int hold = spos;
    spos = epos;
    epos = hold;
}

Just use std::swap to keep it idiomatic:

if (spos > epos)
{
    std::swap(spos, epos);
}

No need calculate the difference each time:

for(int i = 0; i <= (eblock - sblock); ++i)

Define a constant before the loop and use it instead:

const int blockDifference = eblock - sblock;

for (int i = 0; i <= blockDifference; ++i)


Your algorithm doesn't have simple uniform distribution over !n. Your alternative do has it, is actually a known algorithm named Fisher–Yates shuffle.


Warning
This is a code-review (CR) site. Though my answer/review may seem harsh at points, it is my firm belief that CR can, and should, be tough. I've explained my reasoning at length here.
It is not my intention to hurt yours or anyone else's feelings, be advised that some criticisms may be phrased badly, or bluntly. It is important, then, to keep in mind that my only goal is to help.

Due to the fact that much of CR is criticizing other peoples code, you may get the impression that I see myself as the light of the world, and only source of
"good code". Not so. Some critiques are subjective (such as which extension I recommend: PDO and not mysqli_*). TMTOWTDI and to each his own.

The first thing that is "bad" (as in: not good practice), is that you're not using the right MySQL extension. What is in fact outright wrong is that you're not consistently using a single extension throughout. Most of the time, you're using the mysql_* extension (which is really, really bad, mkay). But then out of the blue you have this, shall we say, moment of clarity, and you use the MySQL Improved extension (or mysqli_*):

//all your code using mysql_*
$result = mysqli_query($localhost,"select * from users where username =     '".$username."'");
while ($row = mysqli_fetch_array($result)) {
    echo $row['id'];
}
//reverting back to deprecated extension

The help section of this site specifically request you post actual, working code to review. If you need this code fixed/debugged: set about trying yourself and, if you can't seem to get it to work, post a question on SO.
Please clarify (by editing your posted code) which extension you're actually using. Also mention any notices, errors or warnings you get, if any.
Regardless of what extension you choose: make sure it's not deprecated, use it as was intended and be consistent.

The second thing is the use of magic quotes. Like the mysql_* extension, these have been deprecated for quite some time and have been removed since PHP 5.4.0. Do not use them. Ever. No, seriously. Stop. I'm not joking. Honest.

Third item on the agenda: at no point are you bothering to check if there is any POST data to be processed, You just blindly assume $_POST['username'] will be there. That can issue notices (undefined index E_NOTICE).
Adding an if (!isset($_POST['username']) || !isset($_POST['password'])) exit(); isn't a lot of work, and prevents all this.
I would assume you're include-ing this file as part of a bigger script, and in case that script does check for isset params, then you should be good, but if that's the case: be careful with that header business. If the headers are already sent, you'll get an error.

Which brings us neatly on to point four: header('Content-type: application/javascript');? Why? What? How? Why are you setting a header that makes no sense? As far as I can tell, you're only echoing text, a more suitable header, then, would be:

header('Content-Type: text/plain');

If you are going to add markup to the output, change that header to:

header('Content-Type: text/html');

Fifth: mysql_connect(...) or trigger_error(mysql_error(),E_USER_ERROR); vs $query_exec = mysql_query($query_search) or die(mysql_error());. Why are you using that horrible or? and why use trigger_error the first time 'round, only to then switch to that equally horrible die?
If the db connection failed, then the app failed. throw new RuntimeException('Could not connect to db'); from a function that returns a db connection is what you could do, or simply exit(1);
Whatever you do: be consistent.

Lastly, and most importantly: as a result of the things mentioned above, and the fact you're simply concatenating barely validated POST data into a query: You are vulnerable to injection attacks. This site explains what they are.
An easy, reliable and safe way to prevent this sort of attack is to use prepared statements. An example of how this is done with PDO would be:

$dsn = 'mysql:host=127.0.0.1;dbname=default_db';
$user = 'root';
$pass = 'DoNotUseRootUserIfYouDoNotNeedRootAccess';
$pdo = new PDO(
    $dsn,
    $user
    $pass,
    array(//more options here
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
    )
);
//no quotes, no data, just the query as-is
$stmt = $pdo->prepare(
    'SELECT *
     FROM users
     WHERE username = :uname
       AND password = :pass'
);
$stmt->execute(
    array(
        ':uname' => $_POST['username'],
        ':pass'  => sha1($salt1.$_POST['password'].$salt2)
    )
);
if (!($row = $stmt->fetch()))
{
    echo 'User not found';
}
else
{
    do
    {
        echo $row->id, PHP_EOL;
    }while($row = $stmt->fetch());
}

Just browse through the documentation for the PDO class, or work out how to use prepared statements using the mysqli_* extension. It's not very hard, and I'd be happy to review your attempts at it, but I don't really like mysqli all too much, so I'm not posting an example here.
To help you choose between the two extensions, there's a special choose-an-api page can be found here

The reason why I prefer PDO, in case you are wondering is simply because its API is clean, and consistent: it's OO-only, whereas mysqli_* offers both a procedural and OO API. That, to my eye, makes for messy code.
mysqli_* uses a bit too much pass-by-reference in its methods:

$foo = 123;
$mysqliStmt->bindParam('i', $foo);//REFERENCE to $foo
$foo = 678;
$mysqliStmt->execute();//will use CURRENT value of $foo -> 678

It, once again, has to do with being consistent.

Last thoughts:
Given that you're still new to PHP, I'll leave it at this. Spend some time on the doc pages, and if it all gets a bit much, perhaps look at the unofficial coding standards: at PHP-FIG. All major players (Zend, Symfony, Doctrine, Drupal, Joomla... the list is on the site) subscribe to these standards. Since I've repeated it many times before here, if you want to be consistent, too: try and adopt these coding standards.


Targeting specific elements with CSS only

Markup

If you have a td that you're giving a class that indicates that it is some sort of heading, you should be using a th instead.  The th element is allowed to appear in a tbody, it isn't restricted to thead.

When validated, this table will generate warnings regarding different numbers of cells in each row.  The correct structure should look like this:

            Landscape
            Lorum Ipsum

            Lorum Ipsum

            Lorum Ipsum

            Lorum Ipsum

Be consistent with your indentation.

CSS

Now that the markup is simplified, it's child's play to simplify the CSS

.greyBG td {
    width: 100%;
    text-align: center;
}

Demo:  http://codepen.io/cimmanon/pen/GqKcx


I can't make a thorough review right now, but here's a quick fix that should help you structure things up.

What you have is probably working, but you're mixing-up presentation with data concerns. I don't think these methods should be returning void. Picture this:

protected IEnumerable<SalesInfo> LoadSales()
{
    using (var db = new StoreDataClassesDataContext())
    {
        var result = db.Sales.Select(s => new SalesInfo {
                                                SaleId = s.SaleID,
                                                SaleDate = s.SaleDate,
                                                Total = s.Total })
                             .ToList();
        return result;
    }
}

What you get is a bunch of SalesInfo objects that contain your query results. Bind that to your UI instead.

It's probably normal you're re-creating the context everytime, you want these things to be as short-lived as possible.


Handling click events to open and close menus depending on the click target

The switch statement isn't needed.

Just set a click function for each class.

$(document).ready(function ready () {
    $('.expandDropDown').click( handleBreadCrumbDropDownClick );
    $('.headlineTitle').click( handleAccordionItemClick );
});

function handleBreadCrumbDropDownClick() {
    var target = $(this);
    var dropDownList = $('#' + target.attr('data-itemprop'));
    var offset = target.offset();
    if ( dropDownList.hasClass('BC-DropDown-Open') ) {
        dropDownList
          .hide()
          .toggleClass('BC-DropDown-Open');
    }  else {
        if ( $('.BC-DropDown-Open').length ) {
            toggleDropDown('.BC-DropDown-Open');
        }
        toggleDropDown(dropDownList, offset);
    }
}


You could do this with just one query. There are variations how to construct the query but I would probably do something like this:

picture_ids = user.pictures.select(:id) # Will be used as a subquery if you use select
Variant.where(picture_id: picture_ids).sum(:price)

This will only generate one query, and sum all the prices using sql, so you don't lose performance.

EDIT: As pointed out in the comment below, if you are using MySQL (or have a SQL server which does not handle subqueries that good) you can use pluck instead of select. That will make as separate query to fetch all the picture_ids and everything else will still work the same way.


Enum usage to restrict class attribute values

You get no benefit for raising an error in is_in_enum. It's actually a hindrance.
I'd expect to use that function as followed:

if foo.is_in_enum(key):
    # do something
else:
    # do something

However, to correctly use your function I'd have to use:

try:
    foo.is_in_enum(key)
except ValueError:
    # do something
else:
    # do something

Instead just change it to return your if statement.
You can use **kwargs with keyword arguments. Use that instead.

And so I'd use:

from enum import Enum

class ArticleMetadata(object):
    ArticleTypes = Enum('ArticleTypes', 'original modified', module=__name__)

    def in_enum(self, value, Enum):
        """Verify that a value is contained within a defined Enum object."""
        return value in Enum.__members__

    def __init__(self, article_type=None, **kwargs):
        """Set class attributes."""
        if article_type is None or not self.in_enum(article_type, self.ArticleTypes):
            raise ValueError("Value {} not in Enum list.".format(article_type))
        self.article_type = article_type


Regex to remove inline javascript from string

Parsing markup with regex is like building your house using lego... it's not the right tool for the job. HTML is not a regular language, therefore regular expressions don't cut the mustard. More than that: You're actively working to bring the world as we know it to an end, which drives people insane
What you need is a DOM parser, and as luck would have it, PHP has the DOMDocument object, which is just that:

$dom = new DOMDocument;
$dom->loadHTML('<img onload="alert(\'hello world\');" onclick="alert(\'hello world\');" />');
$nodes = $dom->getElementsByTagName('*');//just get all nodes,
//$dom->getElementsByTagName('img'); would work, too
foreach($nodes as $node)
{
    if ($node->hasAttribute('onload'))
    {
        $node->removeAttribute('onload');
    }
    if ($node->hasAttribute('onclick'))
    {
        $node->removeAttribute('onclick');
    }
}
echo $dom->saveHTML();//will include html, head, body tags and doctype

Tadaa... both onload and onclick have been removed from the markup, without the pain of writing a reliable and stable regex, that can deal with in-line JS... As an added bonus, this code will be far more maintainable (and expandable) in the future. I'd much prefer maintaining this code, than having to rework a regular expression somebody wrote a couple of months ago...

If you want, you can echo only the tags you've changed, like so:

$changed = array();
$attributesOfDeath = array('onload', 'onclick');
foreach($nodes as $node)
{
    $current = null;
    foreach($attributesOfDeath as $attr)
    {
        if ($node->hasAttribute($attr))
        {
            $node->removeAttribute($attr);
            $current = $node;
        }
    }
    if ($current)
    {
        $changed[] = $current;//add to changed array
    }
}
$changed = array_map(array($dom, 'saveXML'), $changed);
echo implode(PHP_EOL, $changed);

As Jan said, for maintainability it's best to use an array of "forbidden attributes". That's what the $attributesOfDeath array is for. If you want to, later on, check for a third or fourth attribute, you can simply add that to the array, and nothing else in your code need change. It'll just keep on working as before.


How would you rate this python code? (Django AJAX)

In my opinion it's little bit hard to read. You have to split it up into POST/GET methods.
Then you have to clean up code in POST/GET methods.
Something like this, for example.

@login_required
def bookmark_save(request):
    form = BookmarkSaveForm()
    if request.method == 'POST':
        form = bookmark_POST(request):
        if isinstance(form, HttpResponse):
            return form
    elif 'url' in request.GET:
        form = bookmark_GET(request)

    variables = RequestContext(request, {'form': form})

    if 'ajax' in request.GET:
        template_name = 'bookmark_save_form.html'
    else:
        temaplte_name = 'bookmark_save.html'
    return render_to_response(temaplte_name, variables)

And functions for POST/GET actions

def bookmark_POST(request):
    form = BookmarkSaveForm(request.POST)
    if form.is_valid():
        bookmark = _bookmark_save(request, form)
        if 'ajax' in request.GET:
            variables = RequestContext(request, {
                'bookmarks': [bookmark],
                'show_edit': True,
                'show_tags': True
            })
            return render_to_response(
                'bookmark_list.html', variables
            )
        else:
            return HttpResponseRedirect(
                '/user/%s/' % request.user.username
            )
    else:
        if 'ajax' in request.GET:
            return HttpResponse(u'failure')
    return form

def bookmark_GET(request):
    url = request.GET['url']
    try:
        link = Link.objects.get(url=url)
        bookmark = Bookmark.objects.get(
            link=link,
            user=request.user
        )
        title = bookmark.title
        tags = ' '.join(
            bookmark.tag_set.all().\
            values_list('name', flat=True)
        )
    except (Link.DoesNotExist, Bookmark.DoesNotExist):
        title = ''
        tags = ''
    form = BookmarkSaveForm({
        'url': url,
        'title': title,
        'tags': tags
    })
    return form


Recursively moving every lowercase 'x' in a string to the end

Your solution takes \$O(\frac{(n*n)}{2} + \frac{n}{2})\$ space and \$O(\frac{(n*n)}{2} + \frac{n}{2})\$ time, where \$n\$ is the amount of characters.

The flaw is trifold:

You make use of recursion. If the compiler doesn't optimize the recursion away, you keep the entire string in memory for each stackframe. This explains why there's a * in the O for space.

Strings are immutable, so when you perform operations on them, you get back a new copy.

When a new copy of a string is made, it has to copy every character in that string to another location in memory. This means you have to copy the entire res variable every time you add to it.

What this all means is that each time you call end with res+str.charAt(index) or res+String.valueOf(track.remove(0)), you have two strings in memory:

First call to end, with the empty res
Second call to end with a res of length 1

So if the input string is "xxhixx":

The first time you add an x to track
The second time you add an x to track
The third time you add an h to res, putting a new string of length 1 in memory
The fourth time you add an i to res, putting a new string of length 2 in memory
The fifth time you add an x to track
The sixth time you add an x to track, then the input string is done
The seventh time you remove an x from track and add it to res, putting a new string of length 3 in memory
The eighth time you remove an x from track and add it to res, putting a new string of length 4 in memory
The ninth time you remove an x from track and add it to res, putting a new string of length 5 in memory
The tenth time you remove an x from track and add it to res, putting a new string of length 6 in memory
The eleventh time you enter end, both track and str have been processed, and you return res

If we look at the memory usage when you enter end for the eleventh time, you'll see that there are 6 copies of res:

"h"
"hi"
"hix"
"hixx"
"hixxx"
"hixxxx"

That makes the total memory usage \$6+5+4+3+2+1 = 21 \space \text{characters}\$, consistent with \$\frac{(n*n)}{2} + \frac{n}{2}\$. \$6*6 = 36\$, \$\frac{36}{2} = 18\$, \$\frac{6}{2} = 3\$, \$18+3 = 21\$.

If the compiler notices that it can optimize your recursion away, you will not have this issue - the space complexity will be \$O(n)\$. However, internally, it won't be recursion anymore.

Since you're forced to use recursion, what you have is close to the best you can do.

You could convert track to a String - that way, you can just append it to res in one go when you're done.

But we don't like arbitrary requirements, so let's fix the algorithm.

It's pretty simple:

public String endX(String inputString) {
    int xCounter = 0;
    int writeIndex = 0;
    final int size = inputString.length();
    char[] resultArray = new char[size];
    for (int readIndex = 0; readIndex < size; readIndex++) {
        char c = inputString.charAt(readIndex);
        if(c == 'x'){
            xxCounter++;
            resultArray[size - xCounter] = c;
        } else {
            resultArray[writeIndex++] = c;
        }
    }
    return new String(resultArray);
}

It's \$O(2n)\$ in terms of space (1x for resultArray, 1x for the new String). It's \$O(2n)\$ in terms of time (1x for going through the string, another 1x for the new String because it's a constructor).

I'll explain in detail:

We create a character array to store the new string. We then check each character of the input string. If the character is a normal character, write it into the character array and move on to the next. If it's an X, write it at the end of the array (size - 1). The next time you encounter an X, write it at the location 1 before the end of the array (size - 2). And so on.

Lastly, convert to String via the character array constructor.


Performance of WordPress Plugin is currently very bad and needs to be improved

If you don't need to worry about WordPress filters on getting post meta, you probably can just do this with a single SQL statement and iterate through the results, rather than relying on WordPress to get the values from the database, since that's 20,000 sql statements, plus the memory of caching all that data (which WordPress does behind the scenes when you get post meta for a post).


The code is quite clean and understandable - even though I'd work on the following:

Improve variable naming - for instance, Scrape() should become scrape() - in Python there is a lower_case_with_underscores notation for variable, function and method names.
You can cut down on the nested loops. For example:

for item in tree.xpath("//a[@class='sidebar-item-label']"):
    itm_lnks = item.xpath(".//@href")
    for page in itm_lnks:
        self.profile_links(page)     # Sending links to create new hrefs for getting to each profile of first page
        self.pagination_links(page)  # Sending links to process hrefs to the next page

will become:

for link in tree.xpath("//a[@class='sidebar-item-label']//@href"):
    self.profile_links(link)     # Sending links to create new hrefs for getting to each profile of first page
    self.pagination_links(link)  # Sending links to process hrefs to the next page

I would use the EAFP approach when reading the name and web values - you would at least avoid repeating your XPath expressions this way.
Convert your method comments into proper documentation strings.

Modified code:

import requests
from lxml import html

class HouzzParser:
    main_url = "https://www.houzz.com/professionals/"

    def __init__(self):
        self.keeper = []
        self.session = requests.Session()

    def scrape(self):
        self.receiver(self.main_url)

    def receiver(self, link):
        """Collecting side-bar links."""
        response = self.session.get(link)
        tree = html.fromstring(response.text)

        for link in tree.xpath("//a[@class='sidebar-item-label']//@href"):
            self.profile_links(link)     # Sending links to create new hrefs for getting to each profile of first page
            self.pagination_links(link)  # Sending links to process hrefs to the next page

    def pagination_links(self, link):
        """Creating links for the next page."""
        response = self.session.get(link)
        tree = html.fromstring(response.text)

        for pagination_link in tree.xpath("//ul[@class='pagination']//a[@class='pageNumber']/@href"):
            self.profile_links(pagination_link)

    def profile_links(self, links):
        """Creating links for the profile page."""
        response = self.session.get(links)
        tree = html.fromstring(response.text)

        for profile_link in tree.xpath("//div[@class='name-info']//a[@class='pro-title']/@href"):
            self.target_page(profile_link)

    def target_page(self, urls):
        """Extracting necessary docs from here."""
        response = self.session.get(urls)
        tree = html.fromstring(response.text)

        profile_info = tree.xpath("//div[@class='profile-cover']")[0]

        name = profile_info.findtext(".//a[@class='profile-full-name']")
        try:
            phone = profile_info.xpath(".//a[contains(concat(' ', @class, ' '), ' click-to-call-link ')]/@phone")[0]
        except IndexError:
            phone = ""

        try:
            web = profile_info.xpath(".//a[@class='proWebsiteLink']/@href")[0]
        except IndexError:
            web = ""

        print(name, phone, web)
        data = name, phone, web
        if data not in self.keeper:
            self.keeper.append(data)

    def __str__(self):
        return self.keeper

if __name__ == '__main__':
    scraper = HouzzParser()
    scraper.scrape()
    for item in scraper.keeper:
        print(item)


Determining the maximum value that can be obtained from a loot

The algorithm
Your algorithm needs O(n) space (for storing all items), and O(n * k) time (for selecting the best ones) (n = items to choose from, k = items chosen, bounded by n).
By choosing as you go, you can get that down to O(k') space and O(n * k') time (k' = maximum items chosen at any time, at least k, bounded by n).
Take a look at std::push_heap, std::tuple and lambdas for implementing the new algorithm.
Avoid casting
Casting is error-prone, as it circumvents the protections of the type-system. Thus, use the most restricted cast you can, and don't cast at all if reasonably possible. In your case, why not multiply with 1.0 instead?
Floating-point is hard
You are calculating the specific value (value per weight) of your items for comparison purposes. Luckily, a double has enough precision that you are extremely unlikely to suffer from rounding-errors when dividing two 32 bit numbers. Still, instead of comparing 1.0 * a_value / a_weight < 1.0 * b_value / b_weight you could compare 1LL * a_value * b_weight < 1LL * b_value * a_weight, avoiding division and floating-point.
All those useless copies
While copying small trivial types is generally the right approach, a std::vector is neither small nor trivial; Copying it is rather expensive. If you only need to read it, use a constant reference or preferably a C++2a std::span for increased flexibility.
Gracefully handle all kinds of invalid input
No need to assume malice, you are assured your load of garbage anyway.
Just the code

I don't see where you use anything from <cstdio>, so don't include it.

Never import a namespace wholesale which isn't designed for it. Especially std is huge and ever-changing, which can silently change the meaning of your code even between minor revisions of your toolchain, let alone using a different one.
It cannot be guaranteed to break noisily.

return 0; is implicit for main(). Make of that what you will.


Simple array implementation without bounds-checking

In the constructor that just takes a size. I would initialize all members to their default value even if POD.

template <class T>
Array<T>::Array(const int& init_size)
{
  arr = new T[init_size]();
                  //    ^^^^^  Add braces. on types it makes no difference.
                  //           On POD it will force zero initialization.
  size = init_size;
}

Use the initializer lists in your constructors.

template <class T>
Array<T>::Array(const int& init_size)
    : arr(new T[init_size]())
    , size(init_size)
{}

Use copy and swap idiom for assignment operator (it automatically provides the strong exception guarantee).

template <class T>
Array<T>& Array<T>::operator= (const Array& copy)
{
    if (arr == copy.arr)  // This is the wrong test.
        return *this;     // Though it works as a side effect you will confuse the maintainer.

    size = copy.size;
    delete [] arr;       // breaks the strong exception gurantee.
                         // What it the next line fails? Then you are left with an object
                         // in an inconsistent state. (arr points at de-allocated memory)
    arr = new T[size];

    for (int i = 0; i < size; ++i)
    {
        arr[i] = copy.arr[i];
    }
    return *this;
}

If you want to do this the hard way then it should look like this:

template <class T>
Array<T>& Array<T>::operator= (const Array& copy)
{
    if (this == &copy)    // Return quickly on assignment to self.
    {   return *this;
    }

    // Do all operations that can generate an expception first.
    // BUT DO NOT MODIFY THE OBJECT at this stage.
    T* tmp = new T[size];
    for (int i = 0; i < size; ++i)
    {
        tmp[i] = copy.arr[i];
    }

    // Now that you have finished all the dangerous work.
    // Do the operations that  change the object.
    std::swap(tmp, arr);
    size = copy.size;

    // Finally tidy up
    delete tmp;    // Notice the swap above.

    // Now you can return
    return *this;
}

Alternatively use the copy and swap idiom

template <class T>
Array<T>& Array<T>::operator=(Array const& rhs)
{
    // 1 Copy
    Array    copy(rhs);     // Use the copy constructor to make a safe copy.

    // 2 Swap
    swap(arr,   copy.arr);
    swap(size,  copy.size);

} // 3 as the local copy goes out of scope it destroys the old array.

Note this can be optimized too:

Array<T>& Array<T>::operator=(Array rhs) // 1 implicit copy as parameter is passed by value
{
    // 2 Swap
    swap(arr,   copy.arr);
    swap(size,  copy.size);

} // 3 as the local copy goes out of scope it destroys the old array.

You don't need a get/set methods. Infact get/set is an obvious indication of bad design.

template <class T>
T Array<T>::getVal(const int& index) const {
  return arr[index];
}

template <class T>
void Array<T>::setVal(const int& index, const T& value) {
  arr[index] = value;
}

Just remove both these methods. What you want to do is return a reference to the internal object in your overload of operator[] (which you do) bit the index is an integer usually.

template <class T>
T& Array<T>::operator[] (size_t index)
{                //      ^^^^^^^    Changed type here.
  return arr[index];
}

You also need to provide a verision to use when your array is const.

template <class T>
T const& Array<T>::operator[] const (size_t index)
//^^^^^   Here                ^^^^^  and here.
{
  return arr[index];
}

If you provide an output operator you should generally by symmetric and provide an input operator.


How to optimize Method Visibility and code structures for better performance?

Everything looks good enough.

Code style is OK.

You are using curl, so it will be quite fast and there is nothing you can do in the code to speed it up.

You may or may not need to check this:

    if($id){   // (1)
        $url = 'website/api/v1/pro/'.$id; // (2)
    }

depends from where this $id comes, you probably need to sanitize it somehow. see (1)

In same place you overwrite the $url. see (2) You probably want this:

    if($id){
        $url = $url . 'website/api/v1/pro/'.$id;
    }

I also do not see where you do curl_close($ch) in case an error happen.


How can this functional implementation of Kadane's algorithm be improved?

A recursive function often works well in place of fold.

let kadanes xs =
  let rec loop (partSum, partIdx, maxSum, startIdx, endIdx) i =
    if i < Array.length xs then
      let x = xs.[i]
      let newPartSum, newPartIdx =
        if partSum + x > x then (partSum + x, partIdx) else (x, i)
      let maxSum, startIdx, endIdx =
        if newPartSum > maxSum then (newPartSum, newPartIdx, i)
        else (maxSum, startIdx, endIdx)
      loop (newPartSum, newPartIdx, maxSum, startIdx, endIdx) (i + 1)
    else (maxSum, startIdx, endIdx)
  loop (0,0,xs.[0],0,0) 0


Thanks to Ferada for the hint. Here is what I was able to replace that monster with. Execution time went from more than 590 seconds to less than 2 seconds.

Note: all of the string replacements were another performance pain point, using a single string is much quicker here.

def recurse_search_tables(self, root):
    # Get individual tables and their children nodes.
    for table in root.iter(r'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tbl'):
        for t in table.iter(r'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t'):
            self.decide_to_print(t.text.encode('UTF-8'))


jQuery Plugin Review - wrapper for jQuery UI's tabs

These are probably more comments, but I'll post them as an "answer", because it's easier.

Could you point out a source or an example for the bug with ids/classes containing . and :, because in a quick test they seem to work fine: http://jsfiddle.net/NSXLc/
I don't think you should use the document ready event. It should be the plugins user's choice when he wants to apply the tabs.
The way you are getting the id for the cookie looks dangerously wrong. You assume the selector is always a simple id or class selector and extending on that you assume, that the selector only matches one element and thus only one one set of tabs are initialized at a time.

It's probably better to do something like this:

$wrap.each(function() { // In case the selector matches multiple elements
  var showEvent = null;
  if (this.id) { // only use cookie if ID is set. TODO: use className as alternative
    var id = 'dnnTabs-' + this.id;
    if (opts.selected === -1) {
      // ...
    }

    showEvent = (function(cookieId) { // closure for cookie id
      return function (event, ui) {
        dnn.dom.setCookie(cookieId, ui.index, 1, '/', '', false);
      }
    })(id);
  }
  $(this).tabs({
    show: showEvent,
    // ...
  });
});


Using generic methods for basic crud operations

What about having generic abstract dao class which will contain these methods? You will most likely have to create some concrete dao classes anyway to have specific methods.
We are using this approach in our projects (behind JPA facade)

public abstract class AbstractJpaDao<T extends AbstractEntity> implements GenericDao<T> {

    @PersistenceContext
    protected EntityManager entityManager;

    protected final Class<T> entityClass;

    public AbstractJpaDao(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    @Override
    public T get(Serializable id) {
        Assert.notNull(id, "Entity ID cannot be null");
        return entityManager.find(entityClass, id);
    }

    @Override
    public List<T> findAll() {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> query = builder.createQuery(entityClass);
        Root<T> root = query.from(entityClass);
        query.select(root);
        return entityManager.createQuery(query).getResultList();
    }

EDIT
Also do not put @Transactional on your DAO classes but on Services. Service method describes unit of work which should be done whole or rollbacked.
Consider this simple code

public void save() {
 dao1.delete(entity1);
 dao2.delete(entity2);
}

When second dao fails to delete and you have transactional daos not service, the first entity is lost.

And you save method should not return boolean, but let bubble the exception up into the service layer and let service handle the exception.


Brute-force-like solution to Project Euler Problem 5

The main problem with your code is that it's very hard to understand.

First of all, I'd expect GetSmallestMultiple(10) to return 10. After all, the smallest multiple of 10 is 10, right? That's how your code reads, when it's not really what you want to do. Maybe your signature should look something more like this :

public long GetSmallestCommonMultiple(IEnumerable<int> multiples)

This way, your code reads :

SmallestMultiple.GetSmallestCommonMultiple(Enumerable.Range(1,10));

Now I'd expect 2520 as an answer.

The thing with algorithms is that they can indeed be hard to read, even if it's just a brute force. To counter this, you need strong variable names and a logical flow in your algorithm. (Meaning that just by reading the code I can understand clearly every step of the algorithm)

For example, the code below, if I got it correctly, will find one common multiple (probably not the smallest one) of the multiples. Meaning that, for multiple = 10, we'd have : 10*9*8*7*6

for (int i = maxNumber; i >= 1; i--)
{
    long modulo = num % i;
    if (modulo > 0)
    {
        num *= i;
    }
}

Using the signature I explained at the beginning, we'd get something like that

long commonMultiple = 1;
foreach(var multiple in multiples)
    if(commonMultiple % multiple > 0)
        commonMultiple *= multiple;

Is it much clearer? Nope. What could we do to make it better? Nothing much, right? In such situations, add comments is a good thing to do.

Basically, I think you need to think of better variable names and try to make the algorithm more apparent in your code, now it's kind of hidden behind your code. I know this sounds weird, but usually you should be able to read code once or twice and get what the algorithm does. Now, I can't. I know what you're doing because I know what method you employed, but if I was to read this without barely no mathematic background I'd struggle to understand what's happening.


As personal opinion, I wouldn't use config as name for .value, it sounds too generic and can be confused with .config method of the module API.
Putting comments like //default is false looks confusing - why are these not default? Also it is easy to change the defaults and forget to adjust comments. Uncle Bob recommends to minimize comments and use expressive code with descriptive names instead.
function debounce(a,b,c) is great for minimizers but cryptic for code readers
In my view, using .provider is possibly an overkill as there is not much configuration logic here.
The last two comments here also apply. Instead the config JSON can be kept inside .value and decoupled from the provider.


If you want just to test connection, checking boto.connect_s3() is good enough. According to the docs it raises an exception if something goes wrong.

In case if you want to do more advanced scenario, you can try to make another test with bucket creation and few keys inside.

I will structure the tests the following way:

import unittest
from time import time, sleep

import boto

class BasicConnectionTest(unittest.TestCase):
    def test_connection_works(self):
        # Please add some credentials if necessary
        connection = boto.connect_s3()
        # when using unittest, I'm trying to stick to helper methods
        # because they are more verbose
        self.assertIsNotNone(connection)

class AdvancedConnectionTest(unittest.TestCase):
    def setUp(self):
        self.connection = boto.connect_s3()

    def test_bucket_can_be_created(self):
        bucket = self.create_bucket()
        self.assertIsNotNone(bucket)
        self.assertEqual(len(bucket.get_all_keys()), 0)

    def test_keys_can_be_created(self):
        bucket = self.create_bucket()
        key = self.create_key(bucket, "mykey")
        key.set_contents_from_string("Hello World!")
        sleep(2)
        contents = key.get_contents_as_string()
        self.assertEqual(contents, "Hello World!")

    def create_bucket(self):
        bucket = self.connection.create_bucket('boto-demo-%s' % int(time()))
        self.addCleanup(bucket.delete)
        return bucket

    def create_key(self, bucket, name):
        key = bucket.new_key('mykey')
        self.addCleanup(key.delete)
        return key

In this case you will be safe that if something will go wrong in your tests, addCleanup will take care of removing bucket and key.

It is also possible to test some configs, e.g. http://boto.readthedocs.org/en/latest/ref/s3.html#boto.s3.bucket.Bucket.get_lifecycle_config

Just experiment :)


I am concerned that you have added a layer of false generalization around a very specific, usually one-time use, request object.  I would think the class would be better named Request or similar to better clarify what this wrapper represents as currently stands.

If your intent is to truly define a class that provides generalized request functionality ( get, post, put, etc.) then you should think more closely about how (and if) the class holds state for individual request objects. You probably would not store a common request object for every request on ‘this’, but rather would create a new request object for every method call.   If you find yourself no longer holding request state in your class, then you then would probably consider whether and instantiable class is really what you want.

On a different front, your current code really does nothing to handle errors in the request. If you are spending the time to build a common request abstraction like this, you should add appropriate error handling.

Finally, if you are in the business of building a new request abstraction, then I would strongly consider building of the much more modern and now widely supported Fetch API.


Inspectors & Deconstruction on Unions in a list

Fundamentally, for working with DUs, there is no other way. A DU represents values that can be "either this or that". This means that, when you're looking at one of these values, your code has to handle all possible options of what that value can be, otherwise your program will simply not know what to do for certain cases at runtime. There is no way around it.

That said, you can express this basic idea in different ways.

First, you can use the function keyword to shorten the pattern match a bit. let f = function is just a shorthand for let f x = match x with:

let IsTrue = function Valid _ -> true | _ -> false

Second, you can express IsFalse as a negation of IsTrue:

let IsFalse = not << IsTrue

Alternatively, you could extract the pattern matching part into a function (commonly referred to as "catamorphism"):

let inline validCata ifValue ifError = function Value x -> ifValue x | Error x -> ifError x

and then express the other functions in terms of it:

let inline IsTrue x = validCata (ct true) (ct false) x
let inline IsFalse x = validCata (ct false) (ct true) x
let inline Value x = validCata id (fun _ -> failwith "") x
let inline Error x = validCata (fun _ -> failwith "") id x

(where ct is a trivial constant function, which is sadly missing in F# standard library)

As for the CreateThing function, let me see if I understood the intent correctly: you're trying to validate the sequence of numbers and bail on the first error, returning it; or return the list of numbers if all of them are valid.

If this is the correct intent, you don't need to wrap each number in a Valid at all. Just run the validation function on them until it returns an error, and if it doesn't, return the original list. To run a function on a sequence and stop when it hits the first time, there is a handy library function Seq.tryPick:

let errorFor i =
    if i = 3 then Some "no threes yo" else None

let createThing inputs =
    let firstError = Seq.tryPick errorFor inputs
    match firstError with
    | Some err -> Invalid err
    | None -> Valid { Thing.Values = List.ofSeq inputs }

If you hit this sort of problem often, and really want to use Valid as a general-purpose mechanism for dealing with errors, you can extract the "run sequence until error" part as a reusable thing:

let validSeq (s: Valid<'a> seq) : Valid<'a list> =
    let getError = function Valid _ -> None | Error err -> Some err
    let getValue = function Valid x -> x | Error _ -> Unchecked.defaultOf<'a>
    let lst = List.ofSeq s
    match List.tryPick getError lst with
    | Some err -> Error err
    | None -> lst |> List.map getValue |> Valid

let validMap f = function
    | Value v -> Valid (f v)
    | Error err -> Error err

let createThing inputs =
    inputs
    |> Seq.map ValidateNumber
    |> validSeq
    |> validMap (fun vs -> { Thing.Values = vs })

(note that here I have also extracted validMap as a reusable thing)

Final note: unless you have actually hit (and measured) performance issues, don't work with sequences, work with lists instead. Since F# is not pure, running sequences multiple times can be expensive and unpredictable.


Comma Code - Ch. 4 Automate the Boring Stuff

Your code is well-built and covers everything stated in the task, but could be made much shorter by using the .format() function.

  str.format() is one of the string formatting methods in Python 3, which
  allows multiple substitutions and value formatting. This method lets
  us concatenate elements within a string through positional formatting.

Your code can, therefore, be made shorter and more concise this way. Here is what your code might look like -

def list_concatenator(your_list):

     if not your_list:
         return "Your list is empty!"

     elif len(your_list) == 1:
         return str(your_list[0])

     elif len(your_list) == 2:
         return '{0} and {1}'.format(your_list[0], your_list[1])

     else:
         body = ", ".join(map(str, your_list[:-1]))
         return '{0}, and {1}'.format(body, your_list[-1])

I have used {0} and {1} so that positional arguments can be placed in the order you want them to be in, though it is not necessary to do so.

OR

Another way to format in Python 3 is to use f-strings.

  The idea behind f-strings is to make string interpolation simpler. To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). f-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.

Here's how your code would look like with f-strings (much shorter) -

def list_concetenator(your_list):

    if not your_list:
        return "Your list is empty!"

    elif len(your_list) == 1:
        return str(your_list[0])

    elif len(your_list) == 2:
        return f'{your_list[0]} and {your_list[1]}'

    else:
        body = ", ".join(map(str, a_list[:-1]))
        return f'{body}, and {your_list[-1]}'

Here are some example outputs -

your_list = ['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9]

print(list_concatenator(['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9]))
>>> item1, item2, 3, item4, item5, item6, 7, item8, and 9

print(list_concatenator(['item1', 'item2', 3]))
>>> item1, item2, and 3

print(list_concatenator(['item1', 3]))
>>> item1 and 3

print(list_concatenator(['item1']))
>>> item1

print(list_concatenator([]))
>>> Your list is empty!

The program also takes care of the Oxford comma, where lists with two items do not have commas (e.g. apples and bananas) but lists with more than two items are separated with commas (apples, bananas, and cakes). Here are some useful links that help us understand what Oxford commas really are and when they should be used -

https://www.grammarly.com/blog/comma-before-and/
https://en.wikipedia.org/wiki/Serial_comma

Overall, I believe formatting was the main problem in your code.

EDIT -

In the comments section above, @Ilmari Karonen correctly mentions that the usage of " ' " in the book is the book's way of writing string literals. Therefore, I have edited my answer to make this change (i.e. remove unnecessary quotes). But if you require these quotes, then you could always wrap the string in double quotes, like this - f"'{your_list[0]} and {your_list[1]}'" or this - "'{0} and {1}'".format(your_list[0], your_list[1]).

Another let-down in your code is the use of inconsistent parentheses here,

(', '.join((map(str,your_list[:-1]))))

which could just be written as -

', '.join(map(str,your_list[:-1])).

To remain concise and immaculate in writing programs, I suggest you have a look at PEP 8, which is Python's official style guide.

Hope this helps!


Extracting an arbitrary element from each row of a np.array

The best way to do this is how @GarethRees suggested in the comments:

>>> arr[np.arange(4), keys]
array([1, 3, 7, 11])

There is another (not as good) solution that is a better alternative to using arr[i, keys[i]] for i in range(len(keys)).  Whenever you want both the index and the item from some iterable, you should generally use the enumerate function:

>>> np.array([arr[i, item] for i, item in enumerate(keys)])
array([1, 3, 7, 11])


You can't optimize a promise chain that doesn't exist. The only method that's returning a promise here is User.findOne(). In order for the route to be promise based, you'll need to rewrite the other methods you are calling inside the route.

I'll do my best, with the small amount of information you provided, to help you figure out how to change it.

foundUser.setPassword() seems to be asynchronous but it's using the callback pattern: foundUser.setPassword( newPassword, functionToCallWhenDone ). You need to rewrite it so instead of accepting a function to call back once done, it should return a promise as soon as it finishes or errors out. That way it can be chained with the other promises in the route.

The same can be said about foundUser.save( functionToCallWhenDone ).

Also emailService.sendForgotPassword( foundUser, passwordString ) seems to be crucial to the request's success. I recommend you to rewrite it so it returns a promise too, and catch the error outside the main chain to handle it.

After applying these changes your code could look like this:

// Instead of using comments to indicate your intention, abstract the logic into a method
function generateRandomPassword() {
  return Math.random().toString( 36 ).slice( - 10 );
}

router.post(
  '/forgot-password',
  ( req, res ) => {
    let newPassword;
    let user;

    // I like to start with Promise.resolve() as that makes all the other method calls be at the same indentation level
    // Note: This is not required and purely just about style
    // Also, wrapping anything you'll do around a promise's then method protects you from unforeseen errors
    Promise.resolve()
      // TODO: What happens if the email wasn't sent with the request?
      .then( () => User.findOne( { 'username': req.body.email } ) )
      .then( _user => {
        user = _user;

        newPassword = generateRandomPassword();
        return user.setPassword( newPassword );
      } )
      .then( () => user.save() )
      .then( () => emailService.sendForgotPassword( user, newPassword )
        .catch( error => {
          // What happens if the emailService fails?
          // Here you might want to revert changing the user's password
          revertPasswordChange();

          // Don't forget to return a rejected promise (or throw again the error) because if not, the next then will wrap
          // whatever you return here (or an empty value if you didn't return something) and the success message will be
          // wrongly displayed.
          return Promise.reject( error );
        } )
      )
      .then( () => {
        req.flash( 'success', 'Please check your email.' );
        res.redirect( '/login' );
      } )
      .catch( error => {
        if( error && error.message ) req.flash( 'error', error.message );
        res.redirect( 'back' );
      } )
    ;
  }
);

Note that this code relies on mutable contextual state, which has some drawbacks and (depending on the context) may be considered an anti-pattern. Here's a very good read about how to share state between promises.


Write a clean convertToNumber function, if value is a number

One problem with Number(value); is that it casts falsy values as 0 and truthy values as 1.
That means that an empty string becomes 0, which may not be what you expect.
You could make a regular expression test on the input to determine if it fits your expectations for a number.

let input = document.getElementById('input');
let result = document.getElementById('result');

function IsANumber() {
  let isItANumber = input.value.match(/^-?\d*\.?\d+$/);
  result.innerHTML = isItANumber ? 'true' : 'false';
}
<input id="input" onchange="IsANumber()" onkeyup="IsANumber()" />
 Is a number:

The example above will not fail in truthy/falsy cases, but it will determine strings like "Infinity" to not be numbers too.
Therefore it may need to be modified if you have to parse these to numeric values.


Data Structures for Counting Duplicates and using std::vector::erase

Basic Algorithm
At least if I understand the intent correctly, you simply want a count of the unique input characters that occurred at least twice.
In that case, I think I'd do something like this:
int count_dupes(std::vector<int> const &inputs) {
    std::map<int, int> counts;

    for (auto i : inputs)
        ++counts[i];

    return std::count_if(counts.begin(), counts.end(),
                         [](auto const &p) { return p.second >= 2; });
}

I'd also consider using an array instead of a map, as outlined in an answer to an earlier question: https://codereview.stackexchange.com/a/208502/489 --but this can depend on the range of values you're dealing with. With a 16-bit int, it's no problem at all on most machines. With a 32-bit int (and no other constraints on values) it's still possible on many machines, but probably impractical. For arbitrary 64-bit int, an array won't be practical.
Parameter Passing
Right now, you're passing the input by value. This means when you call the function with some vector, a copy of the original vector will normally be made and passed to the function. As a general rule, something like a vector that's potentially large and slow to copy should be passed by reference to const, as shown in the code above.
Logical Comparisons
Comparing a Boolean value to true or false is generally a poor idea. if (x==true) is equivalent to if (x) and if (x == false) is equivalent to if (!x). Normally, if it's Boolean in nature, a variable should be given a name that reflects that nature, and should be used directly rather than being compared to true or false. For example, s.insert(n).second == false wold be better written as: if (!s.insert(n).second).
Some people (understandably, I guess) prefer to use the written form: if if (not s.insert(n).second). I've written C and C++ long enough that I have no difficulty with reading ! as meaning "not", but especially if it may be read by people less accustomed to programming, it may make more sense to use the words instead of symbols.
Formatting/Indentation
At least to me, this indentation looks a bit odd:
  if (s.insert(n).second == false && m.find(n) == m.end()) {
      dups++;
      m.insert(pair<int, int>(n,0));
      // better to remove from vector than increase space with the map?
      // numbers.erase(remove(numbers.begin(), numbers.end(), n), numbers.end());
    } else {
      s.insert(n);
    }

If you use indentation like that consistently, I guess it's not necessarily terrible, but I think more people are accustomed to something more like this:
  if (s.insert(n).second == false && m.find(n) == m.end()) {
      dups++;
      m.insert(pair<int, int>(n,0));
      // better to remove from vector than increase space with the map?
      // numbers.erase(remove(numbers.begin(), numbers.end(), n), numbers.end());
  } else {
      s.insert(n);
  }

...where each closing brace is vertically aligned with the beginning of the block it closes. As a side-note, there are almost endless debates about the efficacy of various bracing styles. I'm not going to advocate for or against any of the well known styles, but I think there's a fair amount to be gained from using a style that's well known, and then using it consistently. I don't see much to gain from style that's different from what almost anybody else uses.


Your code has some bad side-effects. There's no real difference between filter and filter! since they both modify the input values directly.

It seems that your input is something like:

[{foo: 2}, {foo: 80}, {foo: 6}, {foo: 3}]

in other words, an array of hashes.

When you call filter, you duplicate the array - but the hash objects are still the same objects. So when you calculate the median, and set item[key] = ..., you're modifying the same hash objects. Duplicating the array has no real effect; you're not modifying the array itself, only the objects inside the array. And those objects are the same even if you duplicate the array.

An example:

filter = MedianFilter.new(3, [:foo])
original = [{foo: 2}, {foo: 80}, {foo: 6}, {foo: 3}]

modified = filter.filter(values)

modified # => [{:foo=>2}, {:foo=>6}, {:foo=>6}, {:foo=>3}]
original # => [{:foo=>2}, {:foo=>6}, {:foo=>6}, {:foo=>3}]

In the example, modified is a different array object than original, but the contents of both arrays have been changed. In order words: Your filter method has side-effects.

And I doubt that's what you want.

Anyway, about the code:

Another bug: Your exception says that step "must be odd and higher than 3", but that's not what you actually check. You code checks whether step is below 3 and even. So I can pass in 4 and not get an error, even though it's an even number. Or I can pass in -3 and not get an error, even though is less than 3.
Your error message is also a little misleading. It says "higher than 3" when it fact it can be 3.
You check of keys only checks for a non-empty array - it doesn't check that the array only contains symbols. I could pass in ["foo", 42, Date.new] without the initializer raising an error.
There are a few built-in methods that would make the checks more idiomatic and readable. For instance, step % 2 != 1 can be written as step.even?, and keys.count > 0 can be written as !keys.empty?
I'd probably rename step to window_size, since I think that's a better name. Or you might simply redefine it as the number of neighbors to include - i.e. what you currently call half_step.
I'd simply skip the keys argument, and instead provide the input data in a different way. It would keep this class simple and generic.
I'm not sure this actually needs to be a class, since it doesn't really need to maintain state. It could just be a method.
As for the process method, you can use each_cons to get the "windows" you want to find the median for. You just need to pad the array a little. Here's a simplified example:

# example input
values = [2, 80, 6, 3]
window_size = 3
neighbors = (window_size / 2).floor

# create an array with extra elements at the start and end
temp = ([values.first] * neighbors) + values + ([values.last] * neighbors)

# calculate medians
medians = temp.each_cons(window_size).map { |window| window.sort[neighbors] }

medians # => [2, 6, 6, 3]


Bug: can't delete head node

Your delete_node() function doesn't work if the node you want to delete is the head of the list.  In fact, the function signature can't work:

void deleteNode(node_t *node, node_t *head);

Since the head pointer can change if you delete it, your signature has to be one of these two instead;

void deleteNode(node_t *node, node_t **head);
node_t *deleteNode(node_t *node, node_t *head);

Insert should be renamed

Since your "insert" function adds to the end of the list, I think it should be called append() instead.


Better way to write this branch with an exceptional retry in an embedded C environment?

If you can do without the received variable...just make the radioReceive(...) the condition of a while loop.  You get rid of received, and your loop condition now has a purpose.  :)

while (radioReceive(radiogram, MatchTree, CycleClock, duration)) {
    if (radiogramIsValidForSync(radiogram)) return true;
}
return false;

The only real drawback is that it gets a bit awkward if you need to do anything at both exit points, other than return.


Comparing data in 2 tables on different servers with CHECKSUM

We use mk-table-checksum.

It works really great in Master-Slave context where it also allows to sync differences in both directions depending on your choice.

Saidly from what i've seen most people it for replication and i can't provide any copy/pasteable output but if you don't know it it's definitly worth looking into. If you know it i'd like to hear why it doesn't work for you.

To get an overview over many tables you can use something like mk-table-checksum host1 host2 | mk-checksum-filter


Handling a PUT API call to write to a database using promises

// Nothing fancy, we just wrapped the result in an array
const promise1 = someAsyncOperation()
const promise2 = promise1.then(result => [result])
promise2.then(result => console.log(result)) // [result]

// More concisely
someAsyncOperation()
  .then(result => [result])
  .then(resultInArary => console.log(resultInArray)) // [result]

Whatever you return in then becomes the resolved value of the promise it returns. In this case, when promise1 resolved, we added a then that wrapped the result in an array. The returned value becomes the resolved value of promise2.

Now here's where everyone fails when talking about promises. They miss explaining this one behavior which is vital to the concept of "promise chaining":

const promise1 = asyncOperation1()
const promise2 = promise1.then(result1 => asyncOperation2())
promise2.then(result2 => {
  // This will not be invoked until asyncOperation2()'s promise resolves.
  // Also, result2 is NOT asyncOperation2()'s promise, but its resolved value.

  console.log(result2) // [result]
})

// More concisely
someAsyncOperation()
  .then(result1 => asyncOperation2())
  .then(result2 => {
    // This will not be invoked until asyncOperation2()'s promise resolves.
    // Also, result2 is NOT asyncOperation2()'s promise, but its resolved value.

    console.log(result2) // [result]
  })

When you return a promise in a then, two things happen that's different from returning a "normal value".

It uses the resolved value of asyncOperation2() as the resolved value of promise2, not the promise returned by the function call.
promise2 will not resolve and its callbacks will not be invoked until the promise returned by asyncOperation2() resolves.

By now, you should now see how promise "chaining" is achieved. It's because of this one trick, returning promises in then, that allows subsequent thens to "wait" for (more precisely, not fire callbacks until) the previous promise. You could have code that looks like:

asyncOp1()
  .then(r1 => asyncOp2())
  .then(r2 => asyncOp3())
  .then(r3 => asyncOp4())
  .then(r4 => asyncOp5())
  .then(r5 => console.log('done'))
  .catch(e => console.log('one of the above failed'))

So in your code's case, it would look like this:

class ForbiddenError extends Error {
  constructor(message){
    super(message)
    // Add additional properties
  }
}

app.put('/api/v0/note/:id', (req, res) => {
  const id = req.params.id
  const uid = req.user ? req.user.uid : null

  user_can_edit_note(uid, id)
    .then(yes => {

      // The catch() down below will, uhm... catch this throw.
      if(!yes) throw new ForbiddenError()

      // Return the promise of this operation. The next then() handles it.
      return db.collection('notes').doc(id).update({
        title: req.body.title,
        text: req.body.text,
        author_uid: req.user ? req.user.uid : null,
        updated_on: admin.firestore.Timestamp.now()
      })
    })
    .then(() => {
      // Update completed, respond with ok.

      return res.json({
        ok: "ok"
      });
    })
    .catch((err) => {
      // Any throws not recovered in the sequence will invoke this catch.
      // Use this to evaluate your error. You can extend Error to have it carry
      // custom properties and messages.

      if(err instanceof ForbiddenError){
        return res.status(403).json({
          error: "Permission Denied",
          note_id: id
        })
      } else {
        return res.status(500).json({
          error: "Server error"
        })
      }
    })
})


Collectors.joining

In the two parts of your code, you are using the pattern:

String.join(", " , someStream.map(Object::toString).collect(Collectors.toList()));

to join all the String of a list and separate them with a comma. This has the disadvantage that it requires to construct the whole list in memory only to build the wanted String from it. It would be preferable to use the built-in joining(delimiter) for this task: it will collect the String directly into a String delimited by the given delimiter, without building an intermediate list:

someStream.map(Object::toString).collect(Collectors.joining(", ")));

Stream solution

Your Stream solution has 2 major flaws:

When run in parallel, it is broken. It is simple to test it: add .parallel() just before returning the Stream inside generateFib() and you will not have the correct result; you may even have an ArrayIndexOutOfBoundsException. Why? generate takes here a Supplier<Integer> that will return the next Integer in the Stream, and in parallel, get() will be invoked concurrently. Unfortunately, its code is not thread-safe, leading to unexpected results / exceptions. You might wonder why this is important: the whole Stream API has been built with the idea that running a pipeline in parallel can be done without effort, by just adding .parallel(), so it would simply be inappropriate to write code that doesn't work in parallel.
The supplier is storing itself the whole List<Integer> in memory, when in fact, it would only need the last 2 elements to generate the next one.

Using Stream.generate won't do it: it needs state (last 2 values) so we'll never be able to make a parallel-friendly get(): this method is useful to generate inifnite Stream of uncorrelated values, which isn't our case here.

In this case, we can turn to the Stream.iterate method: this method gives us the last element produced to return the next element. So we could have:

private static LongStream generateFib() {
    return Stream.iterate(new long[]{ 0, 1 }, a -> new long[] { a[1], a[0]+a[1] })
                 .mapToLong(a -> a[0]);
}

This creates a Stream of tuples where each tupes is in fact a 2 element array containing the two previous values. It is initialized to the seed of { 0, 1 } and each next value is computed by retuning { p[1], p[0]+p[1] } from an existing tuple. Finally, this Stream is mapped to a LongStream by only keeping the first element of the tuple. (Note that this uses a primitive Stream of long value. It will quickly overflow: using a BigInteger in place of a long is left as exercise for the reader).

The big advantage is that now, you can run this in parallel, and it won't break (not that it would bring any real advantage, one would have to measure for that; a solution that would probably offer better parallel performance would be implementing a custom Spliterator like done on this Stack Overflow answer).

Then

Main.generateFib().limit(10).mapToObj(Long::toString).collect(Collectors.joining(", "))

gives the same output as the initial code.


Simplify and prettify function looking for max value in a list and modifying some underlying values within that list

If you want to get rid of a for-loop just for code clarity, you could use a Stream and the max() function. (Assuming you're using Java 8+). You could also use Streams for the second for-loop.

Note however, it's not logically possible to avoid iterating through the list twice. You have to check every element to get the largest value, and again to set values on every item in the list.

I don't see you using highestQuantity, it's not really necessary since you have a pointer to recordHighestQuantity already.