With Python it can be tempting to want to write one-liners; but, short code does not necessarily make for better code, and I'd like to review your code in a way that I think would make it more maintainable, flexible and professional, rather than shorter. (maybe someone else will address the one-liner request)
Type hints
Since you are using Python 3.x you could take advantage of the new type hints. According to PEP 484:

This PEP aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.
Of these goals, static analysis is the most important. This includes support for off-line type checkers such as mypy, as well as providing a standard notation that can be used by IDEs for code completion and refactoring.

Even if you don't use static code analysis at the moment, type hints still have the advantage of making the code easier to read and understand.
In your case:
def vowels_finder(s: str) -> list:
    # ...

Reusable functions
The first thought I had looking at your function is that some logic could be extracted for more general reuse. For instance, this function could come in handy for other things:
def is_vowel(ch: chr, include_y: bool=False) -> bool:
    if include_y:
        return ch in ('a', 'e', 'i', 'o', 'u', 'y')
    else:
        return ch in ('a', 'e', 'i', 'o', 'u')

You will notice I also added support for optionally including "Y" as a vowel, which can be useful for certain contexts.
Note that I also used a tuple instead of set, since vowels won't change anyways and tuples are generally faster since they are immutable, and we don't need set operations in this case other than in membership, which tuples support as well.
Now we can simply do this in your vowels_finder function:
for el in s:
    if is_vowel(el):
        vowels[el]+=1

Main function improvements
I would expect a function named vowels_finder to do just that: look for a vowel, and return True if it finds one. Furthermore, I would expect a name like this to be an object/class "Thing", rather than a function which is usually named like "do something".
Let's call it count_individual_vowels instead. Also, now that we have a function for vowels with added functionality for "Y", we can very easily add this option to this function. Note that I have changed some of the variable names a bit to make them more clear:
def count_individual_vowels(input_str: str, include_y: bool = False) -> list:
    vowel_counts = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
    if include_y:
        vowel_counts['y'] = 0
    for el in input_str:
        if is_vowel(el, include_y):
            vowel_counts[el] += 1
    return [(key, pair) for key, pair in vowel_counts.items()]

Bug / overlooked problem
After refactoring this I noticed a problem, see for illustration:
string1 = "My phrase has some vowels, pretty cool don't you think?"
print(count_individual_vowels(string1))
print(count_individual_vowels(string1, True))
string2 = string1.upper()
print('UPPER CASE')
print(count_individual_vowels(string2))
print(count_individual_vowels(string2, True))

Results:

[('u', 1), ('o', 6), ('i', 1), ('e', 4), ('a', 2)]
[('e', 4), ('a', 2), ('u', 1), ('y', 3), ('o', 6), ('i', 1)]
UPPER CASE
[('u', 0), ('o', 0), ('i', 0), ('e', 0), ('a', 0)]
[('e', 0), ('a', 0), ('u', 0), ('y', 0), ('o', 0), ('i', 0)]

This could of course cause problems, but thankfully the fix is extremely simple, just use .lower() method on strings in the functions
Here in the new helper function...

return ch.lower() in ('a', 'e', 'i', 'o', 'u')

And also when adding it into the dict, so that uppercase vowels get grouped into the lowercase count:
for el in input_str:
    if is_vowel(el, include_y):
        # here:
        vowel_counts[el.lower()] += 1

OrderedDict to keep vowels in order
As you've noticed, using a regular dict to store the counts results in the output vowels returns the values in arbitrary order. You could make it return always in the same order by using from collections import OrderedDict and just replacing this:
vowel_counts = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
if include_y:
    vowel_counts['y'] = 0

By this a bit more verbose, but much nicer output:
vowel_counts = OrderedDict()
for vow in 'a', 'e','i', 'o', 'u':
    vowel_counts[vow] = 0
if include_y:
    vowel_counts['y'] = 0

See:

[('a', 2), ('e', 4), ('i', 1), ('o', 6), ('u', 1)]
[('a', 2), ('e', 4), ('i', 1), ('o', 6), ('u', 1), ('y', 3)]

Finally, here is a working demo on repl.it with all the above suggestions applied.


At some point, I'd recommend using template here. This will allow you to store any date type, not just ints, in your structure.
It'd be better to define node as a struct inside StackusingList as private. In your current implementation, node's fields are not hidden because they are all made public.

class LinkedList
{
private:
    struct Node
    {
    };

public:

};

Prefer nullptr to NULL if you're using C++11.
StackusingList() should be an initializer list:

StackusingList(int max) : top(NULL), maxnum(max), count(0) {}

count should be of type std::size_t.
In both push() and pop(), you'll need to return if the stack is full or empty respectively. Otherwise, the function will continue to execute, defeating the purpose of the check.
print():

// no data members are being modified,
//   so make this const
void print() const
{
    // could just be initialized
    // the asterisk is commonly
    //   put next to the type in C++
    node* temp = top;

    while (temp)
    {
        cout << temp-> data << ",";
        temp = temp->next;
    }
}

Watch out:

StackusingList *sl = new StackusingList(5);

You do not call delete with this new, thereby causing a memory leak!  Always call delete properly with every new.

At the end of main() before the return:

delete s1;

Beyond that, you really don't need to use new here.  It's only necessary with the nodes, which you're already doing. It's best to just avoid manual allocation/deallocation as much as possible.
stackData isn't used anywhere (and doesn't have a clear meaning), so just remove it.
You're missing a few useful public member functions:

std::size_t size() const { return count; } // put into header

bool empty() const { return count == 0; } // put into header

template <typename T>
T StackusingList<T>::top() const { return top->data; }

There is no destructor! You're allocating new nodes, so you have to define the destructor to properly delete them:

StackusingList::~StackusingList()
{
    node* current = top;

    while (current)
    {
        node* next = current->next;
        delete current;
        current = next;
    }

    top = NULL;
}

With the destructor defined, you'll need to satisfy The Rule of Three.  This is also important because the default copy constructor and assignment operator will perform a shallow copy of top. This means that the pointer itself will be copied instead of just the data at that pointer. This will cause problems if you try to copy list objects or initialize new ones with existing ones.


Your private one-liner functions do very little to help with anything, and they're not really DRY. Might as well do this:

private boolean isDivisibleBy(Integer number, Integer divideBy) {
    return number % divideBy == 0;
}

As you can see this does nothing much more than wrap the modulo operator with a function call... which is questionable. Notice:

"Divisible" - not sure why your functions lost an i in the process.
Spacing. There's no need to cram operators and operands together into as little horizontal spaces as possible - let code breathe. Especially if the reason for having these functions in the first place, is to improve readability!

Your code doesn't comply with the specs: it's not adding "Script" to the end of the string when the number is even. In fact, your logic is redundant:

if(isDivisbleByThreeAndFour(number)) {
    ...
}

if(isDivisbleByThree(number)) {
    ...
}

Notice:

Both blocks check if number can be divided by 3.
Consistent brace position. If you're going to put scope-opening braces at the end of the line, keep 'em that way - don't switch to C#-style next-line bracing in the middle of your code!

Your bracing style not only inconsistent, the braces themselves are inconsistently present!

    if(isEven(number))
    return "CoffeeScript";
    else
    return "Coffee";

Don't do that. Use braces, and indentation. For your own health.

if(isEven(number)) {
    return "CoffeeScript";
} else {
    return "Coffee";
}

Note, when you have if (x) { return foo; } else { return bar; }, it can be rewritten with a ternary operator, like so:

return x ? foo : bar;

But you don't want to do that here.

You don't want that, because you'll need nested ternaries to remove the redundancies, and that would look terrible.

What would the correct logic be then?

Just follow the specs:

Check to see if it divides by 3 - if it does:

If it also divides by 4, we got "Coffee". Else, we got "Java".
If it also divides by 2, append "Script" to whatever we got.

Otherwise, return "mocha_missing!"

The nesting here should give you a clue: you only need to check once if the number can divide by 3.

String value;
if (number % 3 == 0) {
    if (number % 4 == 0) {
        value = "Coffee";
    } else {
        value = "Java";
    }
    if (number % 2 == 0) {
        value += "Script";
    }
} else {
    value = "mocha_missing!";
}

return value;

Strategy Pattern seems very much overkill here. If this is for an interview, I'd say don't overthink it - they're just trying to see if you can read specs.


Algorithm

mergesort allocates a new buffer of scratch memory for each recursive call. This means sorting an array has to use \$O(n \log n)\$ allocations total, with \$2 * n\$ peak memory usage. This is double the amount of memory usually required, and if mallocs runtime complexity is worse than \$O(1)\$, the whole mergesort operation will perform worse than \$O(n \log n)\$.

Also, every call to mergesort unnecessarily copies all of the elements of the previous buffer into the new ones. These copies can be completely skipped with appropriate management of the already existing buffers.

The merge operation isn't stable, though it can trivially be made so by changing l[i] < r[i] to l[i] <= r[i]. Stability is usually a major factor for choosing merge sort!

Implementation

Unnecessary restriction on int - this algorithm could be used for any comparable type with templates.
malloc/free or new/delete should usually be used sparingly. In your case, what would speak against the use of either a std::vector<int> or (preferably) gsl::span<int>, or at the very least a std::unique_ptr<int[]>? Both release their memory just fine in case of exceptions (which the current code doesn't even begin to check: results of malloc are never tested!), and freeing the memory will be done automatically once the objects leave the scope.
Naming: Many variables have short, cryptic names that do not express their intentions clearly. What reads easier, l[i] = a[i]; or left_buffer[index] = original[index];?

Fixes

Trying to keep faithful to the original, but including the improvements suggested:

template<typename Element>
void merge(Element *target, Element *source, size_t left_start, size_t right_start, size_t right_end) {
    auto target_index = left_start, left_end = right_start;
    auto left_index = left_start, right_index = right_start;

    while(left_index < left_end && right_index < right_end) {
        if(source[left_index] <= source[right_index]) {
            target[target_index++] = source[left_index++];
        } else {
            target[target_index++] = source[right_index++];
        }
    }

    while(left_index < left_end) {
        target[target_index++] = source[left_index++];
    }

    while(right_index < right_end) {
        target[target_index++] = source[right_index++];
    }
}

template<typename Element>
void merge_sort(Element *original, Element *buffer, size_t start, size_t end) {
    auto distance = end - start;
    if(distance < 2) return;
    auto mid = start + distance / 2;

    merge_sort(buffer, original, start, mid);
    merge_sort(buffer, original, mid, end);

    merge(original, buffer, start, mid, end);
}

template<typename Element>
void merge_sort(Element *original, size_t size) {
    auto buffer = std::make_unique<Element[]>(size);

    for(auto index = 0u; index < size; ++index) {
        buffer[index] = original[index];
    }

    merge_sort(original, buffer.get(), 0, size);
}

  merge basically just gets a slightly different signature (as I'm passing around indices to indicate different buffers instead of pointers).
  merge_sort got split into two functions: One to do the actual sorting, and one to setup the extra buffer. Note the reuse of the original array as buffer!
  Also note that the elements get copied into the buffer beforehand. This is done so the cascading between buffers works in all cases (\$\lceil\log_2 n\rceil\$ might be odd = the lowest merge would start copying from the wrong buffer, or \$n\$ is not a power of 2 = recursion depth might differ by 1 for different parts of the array). This copy step could conceivably be moved elsewhere (or, under certain circumstances, be skipped entirely), but this way the implementation is much clearer about when the copy is done.

Further improvements

merge_sort could use a different sorting algorithm once the number of elements in a part goes below a threshold in order to improve overall performance.
merge_sort could be extended to support iterators, instead of just plain arrays.


I do not see the reason of for class OggConverter as it is now.

Instead of that you could just add the interface IConverter to class Ogg. And remove all others classes as then only forward the call.

IConverter converter = OggConverter(Ogg(file1,file2));

If we add the interface to Ogg

IConverter converter = Ogg(file1,file2);

I also do not see the reason for class AudioConverter, beside that it can store the ref to IConverter but we can store this reference in other place.

In addition to improve are those CODEC and FORMAT string constant. Instead of string constatns you shuld provide enumerations.

public enum AudioCodec {
  LIBVORBIS;
}

public enum AudioFormat {
 OGG("ogg"),
 MP3("mp3");

private final String ext;

private AudioFormat(String ext) {
  this.ext = ext;
}

public String getExt() {
   return this.ext;
 }
}


Rails controller method to accept one rating per IP address via AJAX

Controller code looks good.. You only need to refactor code little bit so that it will look more clean & robust. otherwise rest things are ok. regarding ajax response, you need to implement success/failure response either inside controller or js file.

just to give idea on implementing ajax response inside controller

def update
  render :update do |page|
    if success
      # here replace_html is prototype helper method
      page.replace_html "DIV_ID", "PARTIAL"
      # if you are using jquery then you can execute js code like
      page << "js code goes here"
    else
      page.replace_html "ERR_DIV", "Error occured"
    end
  end
end


Python has a built-in sorted function, you should use it. What it needs to sort according to some special criteria is a key function:

def max_digit_diff(n):
    n_str = str(n)
    return int(max(n_str)) - int(min(n_str))

This uses the fact that "0" < "1" < ... < "9".

However, the sorted function uses a stable sorting algorithm, so if two elements compare equal, the original order is preserved. But here we want the opposite order (later elements come first), so we just reverse the list first:

def digit_difference_sort(a):
    return sorted(reversed(a), key=max_digit_diff)

This should be vastly easier to read than your convoluted function. Note that the function names also follow Python's official style-guide, PEP8.

Like all (good) sorting functions, this is \$\mathcal{O}(n \log n)\$. Here is a timing comparison to your function with arrays up to length 10k (at which point your function takes more than a minute...).

Here is an implementation of the radix sort suggested by @JollyJoker in their answer:

from itertools import chain

def radix_sort(a):
    sub_a = [[] for _ in range(10)]
    for x in a:
        sub_a[max_digit_diff(x)].append(x)
    return list(chain.from_iterable(reversed(x) for x in sub_a))

This seems to have the same complexity as my approach, probably the implementation of max_digit_diff actually dominates this:


RFC: Lightweight C++ 2D array template with runtime dinemsions

Overall
It's fine as far as it goes.
I don't see anything wrong with the implementation.
Note: Since you use none checked version of operator[] you should have the ability to validate that your inputs are correct. So your array needs the ability to return the dimensions of the array in both the x and y dimensions so the code can validate the inputs when required.
Next Step
Currently this is not a container.
There are a few more requirements to make this a standards compliant container. If you want to go this direction.
see: https://en.cppreference.com/w/cpp/named_req/Container
Some improvements:
User defined Types (and by extension template types) should always have an initial capitol letter. This is for humans so we can easily distiguish types from objects:
template<typename type>

I don't like this as now type looks like an object to me when I read it in the code.
Put the destructor next to the constructors.
When code reviewing I want to make sure that your destructor releases the resources correctly as I read. Not scroll back when I find the destructor at the bottom. Also they logically group together.
Why is none copy?
I don't see the logic in that.
Add a swap method (noexcept) and swap free standing function. That comes in handy when interacting with the standard library functions.
It would be nice to simply loop over an array:
Array2D<int>   data = get2DArray();

for(auto const& val: data) {
    std::cout << val << " ";
}

The ability to extract rows to loop over would also be nice (this is an alternative to the above).
for(auto const& row: data) {
    for(auto const& val: row) {
        std::cout << val << " ";
    }
    std::cout << "\n";
}

You have the none checked operator[] implemented fine. But sometimes it is nice to have checked versions so add the method at() that does the same thing but validates its input first.
This is very C like type const *object The * placed next to the object is a standard C convention but in C++ the convention is the opposite and (by tradition) you put the * next to the type rather than the objet (as it is part of the type information).


I don't know what you mean by declarative in this case. All these functions are pure (except the console.log), but the implementations of the functions are all imperative (which is fine of course)
When adding to a set, you don't need to check if the key exists first. Just add it.
Splitting the string into an array of chars isn't necessary. You can use string utils instead, for example indexOf('+'). You can also do a split('+')[0] to avoid having the iPlus variable.
If you swap the reduce for a map, and wrap that in a Set, you don't need to add to set explicitly. It's probably a bit slower though.
You could add some more newlines to the code to group related concepts, and make it more readable

I came up with the solution below:

const getUniqueEmailKey = email => {
    const [local, domain] = email.split('@')
    return local
        .split('+')[0] // Take everything before +
        .split('.').join('') // Remove dots
        + '@' + domain
}

const numUniqueEmails = emails => new Set(emails.map(getUniqueEmailKey)).size

About leetcode:
Try running the code a few more times. The time you get is a bit random...


Simple DRY Rails - check if a model belongs to a user

I suggest you extract two methods: authorized? to check if the user is authorized, and not_authorized to handle behaviour. You would then end up with this:

def new
  @model = ParentModel.find(params[:id])
  not_authorized unless authorized?
end

private

def authorized?
  if signed_in?
    # If you have your associations setup correctly you don't have
    # to check equality on id. You can just compare the objects
    current_user.admin? || current_user == @model.user
  else
    # See aside number 2 for why I removed session
    # session[:session_id] will return nil if it's not present
    # which is false in ruby, so it's safe to do this
    session[:session_id] == @model.author_session_token
  end
end

def not_authorized
  flash[:error] = t('errors.messages.not_authorized')
  flash.keep
  redirect_to root_path
end

But I suggest you think about using an authorisation library, or extracting authorisation logic into a policy object. This way you gain the benefit of DRY, and an extensible way to add and reuse permissions.

def new
  @model = ParentModel.find(params[:id])
  not_authorized unless authorized?(current_user, @model)
end

In a separate policy object you could:

# Choose a better name for this
class ModelPolicy
  attr_reader :user, :model

  def initialize(user, model)
    @user, @model = user, model
  end

  def authorized?
    user.admin? || user.id == model.user_id
  end
end

This example illustrates my point but it is not complete. You must wire the policy to the controllers, maybe include it in a concern. But it's not that hard.

There's a great gem called Pundit that gives you similar interface.

Asides

Try not to use unless with || and && conditions because it becomes confusing. It's clearer to use negation: !current_user. Some people are boolean impaired, including myself.
I'm not sure under what circumstances the session hash does not exist. So checking for its presence may be redundant.


sorting a numerical list using basic scheme

So to answer your specific question, yes you can greatly simplify your algorithm in a couple places:

(list-tail numList (- (length numList) 1))

So you're taking the last n - 1 elements of a list of length n? That's exactly:

(cdr numList)

As for this part:

(reverse (list-tail (reverse numList) 1))

So the list-tail will return a list of size 1, so you can drop the outer-most reverse entirely.  Secondly, what are you getting here? Just the first element right? Which is to say...

(car numList)

So putting that together, we end up with this (+/- missing parens)

(define ra-sort
  (lambda (numList)
    (cond
      ((null? numList) '())
      ((= (car numList) (apply max numList))
          (cons (car numList) (ra-sort (cdr numList))))
          (else (ra-sort (append (cdr numList) (list (car numList))))
      )))

Ok so now think about this algorithm. At each iteration, we're checking if the head is in the right place, if it is we go to the next element, else we rotate the whole array. Checking if the first element is the max takes O(n) time. We expect to have to do this O(n) times per element, for every element... so we end up with O(n^3).

A simple insertion sort, which is what I think you're trying to implement, should be only O(n^2). So try to redo your algorithm so that instead of just checking if the first elem is the maximum one, you actually find it. So your inner clause would be something like:

(cons maxElem                               # largest element
    (ra-sort (remove-elem numList maxElem)) # + rest of list
)

That'll get you to where you want to be. At least for this sorting algorithm.


Structure

Generally, a method should do one thing. For example addPlay should add a play (although it's an odd method for a play class, as a play generally cannot own another play). But your method doesn't just add something, it actually retrieves user input, prints stuff, writes stuff to a file, and then calls a seemingly unrelated method, which asks for more user input and processes it in some way.

It's also very unclear what your LocalPlay class is actually supposed to do. Looking at the fields, constructor, and getter/setter, it looks as if it holds the data for one play, but then it is also possible to add a play, which doesn't make sense.

You should definitely try to separate the holding of the data from the parsing of user input.

You should also try to better define the tasks and differences of lPlayDetails and addPlay, and you should try to remove the confusing call structure (the functions call each other, which makes it difficult to follow the control flow of your program).

Misc

there is no reason to make the fields (or the methods) static.
your naming is a bit confusing. There doesn't seem to be a difference between a play and a show, you seem to be using both interchangeably. In that case, use just one of the terms for clarity.
if a method is not implemented, it shouldn't do anything. Instead of doing something totally different, throw something like an UnsupportedOperationException.
lPlayDetails: It's very unclear what this method does. The name is vague and it is missing a JavaDoc comment. It is also very unclear what the exact difference to addPlay is.
it is very unclear to me why you create a new LocalPlay in addPlay. There doesn't seem to be a reason for it, and it seems to be unused.


squareStyle variable should be initialized in constructor instead of render. Reason being, render is called on each state update and so, if your render is called multiple times, the variable inside render will be computed again which will cause the existing colours of the digits to change on each and will be unpleasant to look.
Usage of var is replaced by let and consts

Modified Code

class Square extends React.Component {
  constructor(props) {
    super(props)
    this.squareStyle = {
      width: 25,
      height: 25,
      backgroundColor: props.colour || getRandomColor(),
      display: "inline-block"
    };
  }
  render() {
    return (
      <div style={this.squareStyle}>
      </div>
    );
  }
}


Python implementation of Kahn's Algorithm

Be explicit about the data structure you're using, and the assumptions. For example, a comment like this would be helpful for any future readers(including yourself): "We represent a graph as adjacency list stored in a Python dictionary. The adjacency list can contain nodes that are not present in the keys of the dictionary, and they should be treated as nodes that contain no outward edges."
I suspect that it's a bad idea to allow nodes that are not present in the keys. Conventionally, an adjacency list should have one entry for each node, whether they have outward edges or not. Moreover, it causes a lot of headache in implementations(To access a dictionary, we had to use get() method instead of the more straightforward square bracket notation).
The first five lines of your function essentially counts each nodes' occurrence. If you require that all nodes should be present in the keys of the dictionary, it can be implemented in a single line:

in_degree = {u: sum(u in v for v in graph.values()) for u in graph}

topological_sort sounds like a verb. Try use a noun for variable names, such as sorted_nodes.


Summing 3 consecutive integers in a list to see if the sum matches a specified value

About performance:

One call of a.AddToList plus one call of a.SumExists cannot work conceptually faster than your variant. But several calls of a.AddToList plus several calls of a.SumExists can run much faster.

You can index all the sums after first call to a.SumExists with as HashSet, so all other calls of SumExists will be run in \$O(1)\$.
A second (and others) call to a.AddToList needs no recalc the whole index - you need only add new elements.

class Aggro
{
    List<int> _numbers = new List<int>();
    HashSet<int> _index = new HashSet<int>();
    int _lastIndexed = -1;

    public void AddToList(int[] list)
    {
        for (int i = 0; i < list.Length; i++ )
        {
            _numbers.Add(list[i]);
        }
    }

    public bool SumExists(int sum)
    {
       if (_lastIndexed > -1 && _index.Contains(sum)) return true;
       for (int i = _lastIndexed + 1, c = numbers.Length - 2; i < c; i++)
       {
            int tmp = numbers[i] + numbers[i + 1] + numbers[i + 2];
            _index.Add(tmp);
            _lastIndexed = i;
            if (tmp == sum)  return true;
        }
        return false;
    }

    public static void Main(string[] args)
    {
        Aggro a = new Aggro();
        a.AddToList(new int[] { 12, 21, 16, 4, 67, 1 });
        Console.WriteLine(a.SumExists(41)); // True
        Console.WriteLine(s.SumExists(69)); // False
        a.AddToList(new int[] { 1 });
        Console.WriteLine(a.ContainsSum3(69)); //True
    }
}


Reverse digits and add until a palindrome appears

reverse()

Your reverse() function only works for numbers below 1010.  Although that upper bound may be good enough to solve this particular challenge, it's not correct in general.  (Keep in mind that the standard says that an unsigned long is at least 32 bits — possibly larger.)

Here is a simpler implementation that works in general:

unsigned long reverse(unsigned long original) {
    unsigned long reversed = 0;
    for (; original; original /= 10) {
        reversed = (10 * reversed) + (original % 10);
    }
    return reversed;
}

is_palindrome()

For every iteration, you end up calling reverse() twice: once to test whether a palindrome has appeared, and again to obtain the next number to add.  You would be better off eliminating this function, and rolling the palindrome check into the reverse_add() loop itself.

reverse_add()

For clarity, I would rename the function to reverse_add_until_paindrome().

Conventionally, C functions are designed so that a status code is returned, and the data being manipulated are passed by reference.  I recommend redesigning the interface so that it returns the number of iterations, as that is closer in spirit to a status code.  The number itself can be passed by reference.  Notice what happens then: it becomes an in-out parameter!  The rationale for the convention makes itself apparent.

int reverse_add_until_palindrome(unsigned long *n) {
    int i;
    unsigned long rev;
    for (i = 0; (rev = reverse(*n)) != *n; i++) {
        *n += rev;
    }
    return i;
}

The problem statement guarantees that you will never be given a P that will require more than 1000 iterations.  That's just for your information; I don't think you need to verify that fact.  (If you do want to bail out, you should add code in main() to detect that the computation was aborted.)

main()

The way you try to use one scanf() to read both N and the Pi is awkward.  Not only does that make the code less clear, it also imposes a penalty of an extra conditional on every subsequent loop.  In addition, it's wrong: the format string for an int is "%d", whereas the format string for an unsigned long is "%lu".

You read n, but never make use of it.  That works, I suppose.  I prefer to use it to see whether all of the expected input was received.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    unsigned long p;

    if (1 != scanf("%d", &n)) {
        return EXIT_FAILURE;
    }
    while (n-- && scanf("%lu", &p)) {
        int iterations = reverse_add_until_palindrome(&p);
        printf("%d %lu\n", iterations, p);
    }
    return (n == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}


Datepickers for departure and return dates

Excess controllers?
This code appears to be similar to several examples of UI Bootstrap datepickers - e.g. this plunker. Initially the layout looked fine but then I realize that there are three total instances of DatePickerController - one for each <date-picker> plus the wrapping <div ng-controller="DatePickerController as dp">. My presumption is that you should be able to implement this without that wrapping DatePickerController but maybe there is something I am missing.
Descriptive function/class names
I noticed that the functions for the controller and the directive are named Controller and directive, respectively. Most widely-accepted style guides call for class names in UpperCamelCase while method/function names should be in lowerCamelCase (e.g. the Google Style Guide). As your application grows it would be advisable to make the function names more descriptive - e.g. datePickerController and datePickerDirective.
Functions only called once
Do the methods toggleDepartDate() and toggleReturnDate() in FormDatepickerController get called anywhere other than the controller initializer (i.e. immediately after they are declared)? If not, then the functionality within them could be moved outside the functions.
IIFEs could be combined
There are two IIFEs in datepicker-controller.js. Those could be combined into a single IIFE because there isn't any reason to have them separated (at least code-wise).


Data formatting, splitting objects & deleting key's/values

You can use Object.entries() and .filter() with RegExp /date|delivery|residential|secondary|shoe/ and .test() to filter data from data, create a function expecting property name and optional separator character to concatenate to property name to replace in returned object spread as values passed to second parameter of Object.assign()

const data = {
  agency: "",
  agent: "",
  agent_email: "",
  agent_phone: "",
  date_of_birth: "2007-05-30",
  delivery_address: "address - 1",
  delivery_city: "city - 1",
  delivery_country: "PE",
  delivery_state: "state - 1",
  delivery_zipcode: "zip_code - 1",
  facebook: "",
  instagram: "",
  name: "Dustin Peter",
  primary_email: "wagnerpeter@bailey-schroeder.example.com",
  primary_phone_number: "+31622064234",
  residential_address: "address - 0",
  residential_city: "city - 0",
  residential_country: "LC",
  residential_state: "state - 0",
  residential_zipcode: "zip_code - 0",
  secondary_email: "garzajustin@vasquez.example.com",
  secondary_phone_number: "+39349330249",
  shoe_size: "38",
  snapchat: "",
  twitter: "",
  url: "",
  youtube: ""
}

let [filters, filtered] = [
  ['date', 'delivery', 'residential', 'secondary', 'shoe']
, (data, props) => Object.entries(data)
  .filter(([key, value]) =>
    new RegExp(props.join`|`)
    .test(key))
];

const handleProps = (prop, r = '', props = filtered(data, filters)) =>
  ([...p] = props.filter(([key, value]) =>
    new RegExp(prop).test(key)).map(([key, value]) =>
    (r ? {[key.replace(new RegExp(prop + r), '')]: value} : value))
    , r ? p : p.pop());

const dataSet2 = {
 date_of_birth:handleProps('date_of_birth')
, delivery_address: Object.assign({}, ...handleProps('delivery', '_'))
, residential_address: Object.assign({}, ...handleProps('residential', '_'))
, secondary_email: handleProps('secondary_email')
, secondary_phone_number: handleProps('secondary_phone_number')
, shoe_size: handleProps('shoe_size')
};

console.log(dataSet2);


Optimizing code to find maximum XOR in Java

You are correct that your code has \$\mathcal{O}(n^2)\$ performance.

Here is a solution in \$\mathcal{O}(log(n))\$:

static int maxXor(int l, int r) {
    int c = 0;
    int exp = 0;
    while (l != 0 || r != 0) {
        c++;
        if ((l & 1) != (r & 1)) {
            exp = c;
        }
        l >>= 1;
        r >>= 1;
    }
    return (1 << exp) - 1;
}

Explanation

The task of finding the maximum XOR value \$m\$ is equivalent to finding the most significant bit \$b\$ that differs between L and R. The maximum XOR value will be \$m=2^{b+1}-1\$.

Proof sketch

Let's use the number 42 (101010) and 59 (111011) as a running example. The most significant bit that differs is bit 4, therefore we expect \$m=31\$.

vvvvvv all these bits are equal
00000101010
00000111011
      ^ bit b=4 differs

Note that bits above \$b\$ never change when counting from L to R, and since XOR only cares about different bits we have \$m<2^{b+1}\$ as an upper bound.

But since bit \$b\$ is set in R and not set in L, there have to be two numbers in the range [L, R] where:

In the first number x, all bits below \$b\$ are set.
In the second number x+1, \$b\$ is set, but all bits below it are not.

So x XOR x+1 will be equal to the sum of all bits up to and including \$b\$ which is \$2^{b+1}-1\$, i.e. \$m \geq 2^{b+1}-1\$.

Thus we have \$2^{b+1}-1 \leq m < 2^{b+1}\$

=> \$m = 2^{b+1}-1\$

In the example:

47 101111
48 110000
47 XOR 48 = 31


In the context of function parameter passing, char* and char[] are equivalent (because char[] decays to char*).

Anyway, I would rather use title_case(char* s) because it more clearly expresses the truth: what you really get within the function is a pointer to the first character of the array.
Accepting char* as string parameter implicitly suggests that the passed string will be '\0'-terminated. As you probably know, there are many known security issues with this.
If that's not the case, that means if you cannot guarantee the '\0'-ending always, consider passing the string length also, for ex.:
title_case(char* s, size_t len)
The cast from char to int (int)s[0] should not be needed, because conversion from smaller to the bigger integral type is always done implicitly and should trigger no warning on any compiler I know.

4.The strlen() in this loop for(i = 1; i < strlen(str); ++i) is called on every iteration, so the overall complexity will be quadratic. The common practice to avoid this is to store length into a variable and then use it, like:

size_t len = strlen(str);
for (i = 1; i < len; ++i) ...

The more concise way with linear complexity would be something like this

>

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void title_case(char *s)
{
    if (s == NULL) return;

    for (char *p = s; *p != '\0'; ++p)
        *p = (p == s || *(p-1) == ' ') ? toupper(*p) : tolower(*p);
}

int main()
{
    char s[] = "this is some     title";
    title_case(s);
    printf("%s\n", s);
}

Note: In the boolean expression p == s || *(p-1) == ' ' short-circuit evaluation capability of C/C++ is used: if p==s is true, then *(p-1) is not evaluated. Otherwise we would dereference invalid pointer -> which would lead to undefined behaviour.

Edited: Emphasize quadratic complexity issue, as proposed in comments by @sudo


Your idea

Your idea is nice, but it will cause problems when extending the game. For example, we will add spock and lizard:

var spock = ["spock", "paper", "lizard", "scissors", "rock"];

Now, index 1 and 2 mean p1Loss, and index 3 and 4 mean p1Win. This can easily cause bugs in the future.

Maybe a better idea

You could instead maintain arrays that say what items beat. For example:

var spockBeats = ["scissor", "rock"];

Then, check at the beginning if the input of the users is equal, return "tie" if it is. If it is not, find the appropriate array for user1 (I would use a switch instead of many if-else) and see if it contains the choice of user2.

In this case, extending the game is easier. New item? Add a new array and a new switch option, and add the item to some of the other arrays.

In case you really want to extend the game (I mean like adding a couple dozen or more options), this approach too would become somewhat annoying. In that case you might want to read up on graph theory, as this is basically just a directed graph. I think that an adjacency matrix might work well then.

For rock, paper, scissor, the matrix would look like this (it contains duplicate information, but I don't think that memory is a concern and removing it would make it harder to use):

   R  P  S
R  0 -1  1
P  1  0 -1
S -1  1  0

And you use it like this:
Player1 plays paper, Player2 plays rock.
Look in the paper row for the value under rock. it is 1 and player1 wins. -1 would mean they lose, and 0 means tie.
For just rock, paper, scissors this is overkill, but for a lot more options this might work well.

Comments on current code

I would save the strings (rock, paper, scissors) in fields at the top of the file. It's an easy source of bugs because of typos
I would return which player won, not with what choice they won. Or both, but the current way seems just odd to me


You could have a collection of ValueConverters which would validate your TextInputs' strings. For example one could be a PhoneNumberValidator or PhoneToBoolConverter (example names there). This way HasError would bind to HasError="{Binding PhoneNumber, Converter={StaticResource PhoneNumberValidator}}". Converters are handy and you can reuse them in multiple places around your code if they are declared in your App.xaml.cs for example.


Asking for a name and showing the initials

White Space

As was mentioned in the comments by @Aluan Haddad, your initial code was missing white space between things like operators and operands.  As it stands, your code is still missing standard white space, such as a blank line between methods, a blank line between the end of your #include section and the start of the code.  It makes your code feel a bit cramped.

Const

If you're not going to be modifying the contents of variables passed into functions you should be declaring the parameters as const.  This helps the client to know that it is safe for example to pass a string literal into your getInitials function.

Users are unreliable

Even well users with good intentions make mistakes.  You're not capturing all of those mistakes with your current code.  What happens if the user puts two spaces between parts of their name?

Cleanup

In getName, you malloc up a buffer which you never clean up.  It may be that you've intentionally done this because you know that it will be cleaned up anyway when the program exits.  Alternately it may be that you've forgotten to do it.  Generally I'd suggest always cleaning up after your malloc's because that way whoever is reading the code knows you've thought about it.

Naming

Some of your names are good and appropriate (name, initials), others are less descriptive (holder, j).  Good naming makes your code a lot easier to follow.

Live up to your promises

getInitials says that it returns a char.  It doesn't.

Be consistent

getName prompts the user, outputs what they tell the program, then returns the value.  getInitials on the other hand parses a string, outputs the initials and then doesn't return anything.  The prefix get really suggests that the methods should be doing a similar level of task.

Separate out user interactions

getInitials could be written in such a way that it took in a name and returned a string containing the initials, then it could be called from future programs that had different user interfaces.  At the moment, it has a printf in it which makes this more challenging.  Try to isolate your user interactions (inputs/outputs) from your main logic (string processing in this case).

Allocate how much?

getInitials allocates sufficient memory to store every character from the persons name.  Is this really required?  Since you've declared a buffer for the persons name as 100, should this really be a constant that can be reused so that getInitials doesn't need to malloc, it can just have a local buffer?

Multiple declarations on a single line

I don't really like them.  I find that they make it hard to locate variables so I would avoid this:

int length,i,j = 0;

Unnecessary casting

You should avoid unnecessary casting.  Since malloc returns a void*, you don't need to cast it when assigning it to a char*.  You can simply do:

initials = malloc(length);


Node.js error handling using merely if else without try catch

My main problems with your approach are:

You have to remember to do this error handling. If you forget, you'll get a silent failure.
You have to make every middleware aware of your error handling.

The first one can't really be solved by Express. Due to the way that Express works, you'll always have to do some variant of:

if (error) {
  return doSomething(error)
}

I prefer Koa as a result because Koa uses async/await, which translates to Promises under the hood; errors that occur in a Promise will propagate correctly, regardless of if you remember to handle them or not.

As for the second result, this kinda invalidates the purpose of middleware. Middleware should only know what it does; you can easily leave error handling til later on in the chain by modifying your middleware to pass the error argument to the next middleware in the chain..

router.get('/tasks', (request, response, next) => {
  Tasks.getTasks((error, result) => {
    if (error) {
      return next(error)
    }

    ....
  })
})

And then adding the following as the final middleware in Express:

app.use(function errorHandler(error, request, response, next) {
  return handleError(error, request, response)
})

As long as all other middlewares pass the error to the next in the chain, this will work 'automagically' and you can swap out your implementation of error handling without any middleware having to change.

As a side note, I'd highly recommend making your application use Promises and async/await (Node 8 is now LTS which supports this so there's no reason not to). You can still use express if you want to, and it would look something like this instead:

router.get('/tasks', async (req, res, next) => {
  try {
    res.json({
      success: true,
      msg: {
        tasks: await getTasks()
    })
  } catch (error) {
    next(error)
  }
})

If you used Koa you wouldn't need the try/catch.

I'd also recommend not having the success flag: Use HTTP status codes to indicate success or failure.


Reduce array of objects into object of arrays

We've got a readability issue here. This is the horror we all have to face when we overuse the new "concise" ES6 syntax. I had to read the code at least 3 times to understand what it was doing (and forgot ... is spread).

If you're worried about code size, let the minifier do its job. Code is for programmers to understand. The verbose version of it isn't that bad. It's not like it's not going to run in older browsers.

var result = rows.reduce(function(result, item){
  result[item.k] = (result[item.k] || []).concat(item);
  return result;
}, {});


Returning an iterator is fairly easy with impl. Here's how you can do it. Note that you need to use move with the closure so that it takes ownership of i. Since u32 can be copied, this just copies it instead of taking a reference, which lets you avoid dealing with lifetimes on the return type.

fn get_multiples(i: u32, max: u32) -> impl Iterator<Item = u32> {
    let max_multiplier = max / i;
    (2..=max_multiplier).map(move |n| i * n)
}

As another note, I have a recommendation for improving performance on your sieve. Currently, every time you call remove_item, you have to search all the way through the vector, remove the item, then shift all items after it forward by one. This is awful for performance. Instead, you could have a Vec<bool> and simply flip the value based on index rather than remove it. Then when you're done sieving, you can go through this vector along with indices and create a Vec<u32> to return.


Formatting HTML for use in a locally hosted iframe

SOLID

It crawls HTML code from sites and then it manipulates the returned code, not adhering to the Single Responsibility Principle.

Bad Naming

Don't name your class HTMLFixerClass, obviously it is a class. Also with OOP, in PHP, the convention is camelCase for variables and PascalCase for class names. E.g. yours would become HtmlFixerClass.

What does correct_directories() do? Programmers should be reading this method signature and immediately get an idea of what it is that this method is doing. Currently I have no clue, and it requires me to dig inside the body of the method to figure it out. Especially when it's doing a bunch of regex string manipulations which looks like gibberish at first sight (WTF moment).

Encapsulation

Make your class as private as possible.

If you have no means of having certain components extended or directly called from the public, you can make those private.

A Constructor Constructs

Your constructor is doing way too much.

A constructor is exactly as the name implies it to be, it constructs the object. You are creating a new instance of an object, crawling from a URL, doing a whole bunch of stuff that shouldn't be in there.

Dependency Injection

Your class is tightly coupled to GoutteClient.

What if you wanted to use another instance of GoutteClient? You'd now have to modify your class, which is a bad thing. You can utilize Dependency Injection to make it loosely coupled.

Comments

I do appreciate the comments, but they don't really help all that much. Maybe you should include an example in it, to give the programmer a quicker idea of what's being done.

Also //foreach match in the entire doc, pretty redundant. It doesn't add any additional information. So I would just remove it.

I would also start commenting your entire class. See PHPDoc for examples.

Coding Standards

Try to adhere to the coding standards defined by the PHP Framework Interop Group. It gives better readability to your code, especially for other programmers who do it as well. Of course, you do not have to be perfect with it.

Conclusion

Trying to fathom the use case of this class from a higher level, I came to realize that a class like this is pretty much unnecessary.

Basically it contains just one relevant utility method that does something helpful, correct_directories(), although I can't be bothered putting some more effort into actually understanding what it does.

I would probably just make this a standalone function, or contain it in a static utility class HtmlFixer which would contain every method that fixes anything HTML code related.

As far as crawling the HTML from URLs, this should be done somewhere in the application level, where different objects and functions work together to achieve  something.


replace all .click() functions with:

$('img.thumbs_img').click(function(){
        $('img.big_img').hide(); // Hides all big images
        var id = $(this).attr('id');
        id = id.replace("thumbs_img_", "big_img_");
        $('img#'+id).fadeIn('slow'); //Slowly fades in selected image
    });


I take great pleasure in the fact that your "concise" version is longer than your "verbose" version!

If you believe one version to be more readable and the other to be more obscure, I would argue going with readability over obscurity. One obscure detail is that you're relying on people understanding

(a = CallMethodA()) == null

Some people might think that to be an error, not realizing the expression on the left actually has a value.

If you want to use less lines of code, you could go with something like this

var a = CallMethodA();
var b = (a == null) ? null : CallMethodB(a);
return (b == null) ? null : b.SomeProperty;

Which isn't altogether different than your original if/else chain, but is a bit more compressed and has just the one return statement.


A different way to execute a hangman game

I find this function signature quite confusing:

std::string replace_if_match(std::string& write,
                             const std::string& read, const std::string& match)

The names write, read, and match aren't very descriptive and everything is being passed in by reference, so what is it going to be returning?

Changing the parameter names to something like guessed_word, word_to_guess and guess might be more descriptive.  The return still feels wrong though, why not just have it return true/false to indicate if replaces have been made?

The implementation you've made doesn't really conform to the standard rules of Hangman.  One of the advantages of keeping track of characters guessed is that it ensures you only guess one character at a time.  With your current approach, it's possible to guess partial words (so you can guess 'hang' and it would find the start of 'hangman').  Character matching also encourages you to think about casing, 'H' != 'h' with your current approach.  These choices may be intentional, but it feels unexpected.


Cross browser JavaScript implementation of xhr

Unfortunately, there is a new API for AJAX called fetch. It even has a polyfill. It even has a polyfill for older browsers which looks to me like its already doing what you aim to do.

But anyways, onto your code.

I see you have a long list of ternaries to set values or a default to the options. Instead of that, create an object hosting your defaults, and use Object.assign to merge it and the user config into an object. This throws away the need for doing a ternary/if-else on your code by providing sensible defaults.

var defaults = {
  method: 'GET',
  url: window.location.href,
  username: undefined,
  password: undefined,
  withCredentials: undefined
};

var mergedOptions = Object.assign({}, defaults, options);

var _xhr = new window.XMLHttpRequest();

_xhr.open(mergedOptions.method, mergedOptions.url, true, mergedOptions.username, mergedOptions.password);

_xhr.withCredentials = mergedOptions.withCredentials

For calling the callbacks, consider using call with a context of null. This way, the callback has no assumptions on what the context is and code doesn't accidentally bind something to the global scope.

Alternatively, consider returning a Promise from your function. This way, it acts more like jQuery and the standard fetch.

function xhr(options){
  return new Promise(function(resolve, reject){
    // setup XHR

    if (this.status >= 200 && this.status < 400) resolve(this.responseText, this.status, responseHeaders, this);
    else reject(this, this.status, responseHeaders);

    // send XHR
  });
}

xhr({...}).then(onSuccess, onError);


Project Euler Problem 11: Largest product in a grid

Your functions returning a unsigned long long are missing a return which leads to undefined behavior (more details on this question). You could throw an exception to handle this or you could just return 0.

Not a real issue and mostly a matter of personal preference but the way you check that you are not going out of the bounds of the array could be written in a more natural way.

To check that index b + 3 is in the array, I'd rather read b + 3 < a.size() than b < a.size() - 3.

Even more unusual is the pre-increment in the case of BackDiag() : you add 3 to b and then you consider b - 3.

Once your code re-written to take into account these comments, it looks like :

unsigned long long Horizontal(int a, int b, std::vector<std::vector<int>> grid){
    return (b + 3 < grid[a].size()) ?
        (grid[a][b] * grid[a][b+1] * grid[a][b+2] * grid[a][b+3]) :
        0;
}
//comparing all int's that are vertically next to each other
unsigned long long Vertical(int a, int  b, std::vector<std::vector<int>> grid){
    return (a + 3 < grid.size()) ?
        (grid[a][b] * grid[a+1][b] * grid[a+2][b] * grid[a+3][b]) :
        0;
}
unsigned long long ForDiag(int a, int b, std::vector<std::vector<int>>grid){
    return (a + 3 < grid.size() && b + 3 < grid[a].size()) ?
        (grid[a][b] * grid[a+1][b+1] * grid[a+2][b+2] * grid[a+3][b+3]) :
        0;
}
unsigned long long BackDiag(int a, int b, std::vector<std::vector<int>>grid){
    return (a + 3 < grid.size() && b + 3 < grid[a].size()) ?
        (grid[a][b+3] * grid[a+1][b+2] * grid[a+2][b+1] * grid[a+3][b]) :
        0;
}

Now, one thing to notice is that this good is basically always the same. You should try to write a generic function that you can reuse.

The signature would be something like :

unsigned long long computeProduct(int a, int b, int incrA, int incrB, std::vector<std::vector<int>>grid)


Is this really what has to be done to clear the selection of an ASP.NET TreeView?

There's no in-built method to do this. Your extension method looks great.

Even if TreeView did have an obscurely-named method to clear its selected node, I can only imagine it doing exactly the same as what you've written anyway.


Generic observer pattern implementation in C++

Briefly, I find the following:

The current static behaviour is not intuitive (what does int ev really mean? why numbers and not names?), not efficient (why search in an unordered map rather that direct access?) and not thread-safe (instance is shared among all threads).
A list might be more appropriate to store observers of one event, enabling easier management like removing an observer.
Catching all exceptions in such a generic tool is a limitation. If needed, it could be at least parametrized.
Parameter pack Args... does not take into account return types.
Your Notify takes its arguments by value. Forwarding is not appropriate when calling multiple functions, but at least arguments should be passed by reference.

At a very basic level, I would prefer an object, called e.g. signal, templated on full function signature e.g. R(A...), with non-static members:

(private) observers: std::list or some associative container of std::function<R(A...)>
add()/remove() or connect()/disconnect() to manage the content of observers. remove() would need some form of identification of existing observers, hence the need for an associative container.
operator()(A&&... a) so that signal behaves like a function object. Arguments a... are passed without forwarding to underlying functions, so that they are copied if needed, and not invalidated between subsequent calls.
additional management like clear()/empty().

Your example usage would be rather like

signal<void(int, int)> s;
s.connect([=](int a, int b){whatever});
s(4, 5);

Isn't that better? Since everything is non-static, the user controls how many instances there are, and names them properly. In fact, a single object may have e.g. ten methods, each with its own observers. Each such method is then a signal and behaves like a function object.

Additionally

std::function expects the 1st argument of a call to be the object if bound on a member function. It would be much more convenient to have functionality such that the object is stored separately and the signal's signature matches exactly that of the member function. In many applications everything is about objects + member functions rather than free functions.
Though non-trivial, possibly provide a mechanism to collect return values of called (observer) functions plus policies to choose, compute and return a single return value from operator().

Have a look at boost::signals and boost::signals2 for more ideas.

I have implemented my own model in the past, using delegates instead of std::function. There is an amazing amount of additional work if such "signals" are to fully mimic functions or member functions, including:

default arguments (arbitrary values encoded into types in the signature itself)
overloading (with different signatures)
inheritance (overriding member functions in base/derived classes)
virtual functions
...

I have used it as a full C++-compliant replacement for Qt signals/slots and wrapped most of the Qt Gui module so that a project can be built without moc and without qmake. One day I will hopefully clean and rewrite in C++11.


First of all, there are only three specific keys that you are interested in, so there is no need to loop over the map. Just grab the keys that are interesting and see if they are null or not.

Secondly, it's possible to extract a method for increasing the actual card counts in each map.

Object creatureType = card.getProperties().get("creatureType");
Object manaCost = card.getProperties().get("MANA_COST");
Object scrapCost = card.getProperties().get("SCRAP_COST");
if (creatureType != null) {
    increase(creatureTypes, (String) creatureType, cardCount);
}
if (manaCost != null) {
    increase(manaCostValues, Integer.parseInt(String.valueOf(manaCost)), cardCount);
}
if (scrapCost != null) {
    increase(scrapCostValues, Integer.parseInt(String.valueOf(scrapCost)), cardCount);
}

Where the increase method is:

private <T> void increase(Map<T, Integer> map, T key, int cardCount) {
    if (map.get(key) == null) {
        map.put(key, cardCount);
    } else {
        int oldValue = map.get(key);
        int newValue = oldValue + cardCount;
        map.put(key, newValue);
    }
}

Now, the folks over at Oracle noticed that this was a very common pattern in code, so in Java 8 they introduced the Map.merge method:

private <T> void increase(Map<T, Integer> map, T key, int cardCount) {
    map.merge(key, cardCount, (a, b) -> a + b);
}

But what about this pattern?

Object creatureType = card.getProperties().get("creatureType");
if (creatureType != null) {
    increase(creatureTypes, (String) creatureType, cardCount);
}

Well, the new Java 8 Optional class to the rescue!

Optional.ofNullable(card.getProperties().get("creatureType"))
    .ifPresent(obj -> increase(creatureTypes, (String) obj, cardCount));

So your entire code can be changed to:

private void buildDeckInfoBox() {
    this.deckInfoLabelBox.getChildren().clear();

    Map<Integer, Integer> manaCostValues = new HashMap<>();
    Map<Integer, Integer> scrapCostValues = new HashMap<>();
    Map<String, Integer> creatureTypes = new HashMap<>();

    for (int cardId : this.activeDeckConfig.getChosen().keySet()) {

        CardInfoMessage card = this.cardList.get(cardId);
        int cardCount = this.activeDeckConfig.getChosen().get(cardId);

        Optional.ofNullable(card.getProperties().get("creatureType"))
            .ifPresent(obj -> increase(creatureTypes, (String) obj, cardCount));
        Optional.ofNullable(card.getProperties().get("MANA_COST"))
            .ifPresent(obj -> increase(manaCostValues, (Integer) obj, cardCount));
        Optional.ofNullable(card.getProperties().get("SCRAP_COST"))
            .ifPresent(obj -> increase(scrapCostValues, (Integer) obj, cardCount));
    }

    for (int manaCost : manaCostValues.keySet()) {
        Label manaCostLabel = new Label();
        manaCostLabel.setText(String.format("Mana Cost = %d, Count = %d", manaCost, manaCostValues.get(manaCost)));
        this.deckInfoLabelBox.getChildren().add(manaCostLabel);
    }
    for (int scrapCost : scrapCostValues.keySet()) {
        Label scrapCostLabel = new Label();
        scrapCostLabel.setText(String.format("Scrap Cost = %d, Count = %d", scrapCost, scrapCostValues.get(scrapCost)));
        this.deckInfoLabelBox.getChildren().add(scrapCostLabel);
    }
    for (String creatureType : creatureTypes.keySet()) {
        Label creatureTypeLabel = new Label();
        creatureTypeLabel.setText(String.format("Creature Type %s, Count = %d", creatureType, creatureTypes.get(creatureType)));
        this.deckInfoLabelBox.getChildren().add(creatureTypeLabel);
    }
}

private <T> void increase(Map<T, Integer> map, T key, int cardCount) {
    map.merge(key, cardCount, (a, b) -> a + b);
}

It is possible to refactor those last three for loops as well, but I am not sure if it is entirely worth it. Perhaps I'll show how to do that some other time.


More effective solution:

str_replace('_', '', ucwords($key, '_'));

From Gears library


Swapping pairs of characters in a String

Using a StringBuffer for building the new string is good,
but the variable name str1 is non-descriptive.

The computation of the required array length can be shortened
with the conditional operator:

int n = len % 2 == 0 ? len : len - 1;

Instead of swapping the array elements you can append them to the
string buffer in opposite order:

for (int i = 0; i <= n - 2; i = i + 2) {
    str1 = str1.append(arr[i+1]).append(arr[i]);
}

(and the re-assignment to str1 is not necessary).

And now one sees that the intermediate array is not needed at all:
You can append the swapped characters directly from the original string:

static String swapPairs(String str) {
    int len = str.length();
    StringBuffer swapped = new StringBuffer(len);
    for (int i = 0; i < len - 1 ; i += 2) {
        swapped.append(str.charAt(i + 1));
        swapped.append(str.charAt(i));
    }
    if (len % 2 != 0) {
        swapped.append(str.charAt(len - 1));
    }
    return swapped.toString();
}


#!/usr/bin/env python3

import os

import dotenv
import requests

dotenv.load_dotenv()
token = os.environ['DO_API_TOKEN']
domain = os.environ['DO_DOMAIN']
subdomain = os.environ['DO_SUBDOMAIN']

records_url = f'https://api.digitalocean.com/v2/domains/{domain}/records/'
session = requests.Session()
session.headers = {
    'Authorization': 'Bearer ' + token
}

def get_current_ip():
    return requests.get('https://api.ipify.org').text.rstrip()

def get_sub_info():
    records = session.get(records_url).json()
    for record in records['domain_records']:
        if record['name'] == subdomain:
            return record

def update_dns():
    current_ip_address = get_current_ip()
    sub_info = get_sub_info()
    subdomain_ip_address = sub_info['data']
    subdomain_record_id = sub_info['id']
    if current_ip_address == subdomain_ip_address:
        print('Subdomain DNS record does not need updating.')
    else:
        response = session.put(records_url + subdomain_record_id, json={'data': current_ip_address})
        if response.ok:
            print('Subdomain IP address updated to ' + current_ip_address)
        else:
            print('IP address update failed with message: ' + response.text)

if __name__ == '__main__':
    update_dns()

The script will not work if any variables are missing, so use [...] instead of .get(...) to throw an error ASAP if needed.
The DO URLs always start with /{domain}/records/ so I included that in the top level constant.
A requests.Session makes multiple requests to the same domain faster as it keeps the connection open, and it lets you specify info like headers once.
A few times you create a variable and immediately return it. You can just return the expression directly.
I felt that the check_ip_url constant didn't add anything, so I inlined it. This is mostly a preference.
Most of the comments do not help readers in any way, so I removed them. But if you want to describe what a function does, use a docstring.
Calling .json() on a response parses the text as JSON for you.
Moving the values of one dict to another dict before finally extracting them just adds another layer, so I just returned record directly.
You called get_sub_info() twice which meant two identical requests. To speed things up, I extracted a variable.
Again, requests makes JSON easy to use, now with the json= argument. This both converts the dictionary to a JSON string and sets the content type. But even without this, you really should have been using json.dumps rather than string concatenation.
response.ok is typically how you check if a request succeeded, or by checking the value of response.status_code. I've never seen anyone using the in operator on a response.
There's no reason to return when a function is ending anyway.


Testing a list of proxies for validity concurrently

You are starting two Task in ValidateProxiesAsync - one in the method and another in the extension method.  Really seems it should be one Task.

Also judges is an IEnumerable that you are constantly doing ElementAt.  Should either do First and store that value for each call or pass in an IList or Array is that's what it really is if you need to access it by element

As for Parallel.ForEach vs TPL DataFlow I think that depends on if you are building a data flow mesh (TPL DataFlow) or just want to process items in Parallel only (Parallel.ForEach)


Cartesian product of two tuples - python

If you can use the built-in itertools module, then itertools.product is probably the easiest, but it probably not allowed.  itertools.product creates an iterable of the cartesion product of two sequences.  Since you want it with both the tup1 element first and the tup2 element first, you need to do it twice:

def cartesian_product_itertools(tup1, tup2):
    return tuple(product(tup1, tup2))+tuple(product(tup2, tup1))

The second approach would be to roll your own generator-based solution, using the yield statement.  This can then be converted to a tuple in the same way.  You need an inner function to handle the generator, and an outer function to convert it to a tuple:

def cartesian_product_iter(tup1, tup2):
    def cartesian_product_iter_inner(tup1, tup2):
        for t1 in tup1:
            for t2 in tup2:
                yield t1, t2
                yield t2, t1
    return tuple(cartesian_product_iter(tup1, tup2))

You can also do a similar looping version:

def cartesian_product_loop(tup1, tup2):
    res = ()
    for t1 in tup1:
        for t2 in tup2:
            res += ((t1, t2), (t2, t1))
    return res

For a recursive version, you can greatly simplify by using slices instead of indexes:

def cartesian_product_recursive(tup_1, tup_2):
    res = ((tup_1[0], tup_2[0]), (tup_2[0], tup_1[0]))
    if len(tup_2) == 1:
        return res
    res += cartesian_product_recursive(tup_1[:1], tup_2[1:])
    if len(tup_1) == 1:
        return res
    res += cartesian_product_recursive(tup_1[1:], tup_2)
    return res

I prefer short-circuiting, hence the returns.  If you prefer if...else, here is an equivalent implementation:

def cartesian_product_recursive_2(tup_1, tup_2):
    res = ((tup_1[0], tup_2[0]), (tup_2[0], tup_1[0]))
    if len(tup_2) > 1:
        res += cartesian_product_recursive_2(tup_1[:1], tup_2[1:])
    if len(tup_1) > 1:
        res += cartesian_product_recursive_2(tup_1[1:], tup_2)
    return res


Project Euler problem 79: deducing a passcode

The thing wrong isn't so much the code as the algorithm. Your approach to finding the next first digit is inefficient. What is the right way to approach this problem?

This is actually one of the few Euler problems that I've been able to do on paper. Let's start with just establishing the constraints. We know what digits have to go before other digits and thankfully there aren't any repeats. We can turn the input text into a graph, where a directed edge indicates that a digit has to precede another digit. Behold, the power of pictures:

Just looking at the graph makes the answer obvious: 73162890. Why is it obvious and what work did we do in our head to determine this answer? We sorted the graph. Specifically, we performed a topological sort by following the edges. The algorithm is very straightforward assuming no cycles:

L <- Empty list that will contain the sorted nodes
while there are unmarked nodes do
    select an unmarked node n
    visit(n)

function visit(node n)
    if n is not marked then
        for each node m with an edge from n to m do
            visit(m)
        mark n
        add n to the head of L

Since we're dealing with digits, we can keep our edges as just an array of sets:

class DigitGraph(object):
    def __init__(self):
        self.digits = set()
        self.edges = [set() for _ in xrange(10)]

    def add_edge(self, i, j):
        self.digits.add(i)
        self.digits.add(j)
        self.edges[i].add(j)

And then topo-sort can be written by directly translating the algorithm. I'll leave the rest as an exercise. I time it at about 2x faster.


Add-to-cart method has too many conditions

public void addToCart(OrderlineType orderline) throws Exception
{

        if (orderline == null)
        {
            throw new OutOfStockException("Null object pass addToCart");
        }

You almost certainly don't want to treat a null orderline the same as an OutOfStockException. You probably don't need to check this at all. If a null orderline is illegal, just let the function throw the NullPtrException that results.

        if(orderline.getProduct().isRecallStatus())
        {
             throw new ProductRecallException("Product Id: " + orderline.getProduct().getProductId()
                     + " is being Recalled");
        }

This isn't really the best place for rules about whether you can sell a product. Instead, I'd suggest:

        orderline.getProduct().verifyAllowedToSell();

Which will throw the exception if you aren't allowed to sell the product because its recalled, or any other reason.

        int tempOrderlineQuantity = orderline.getQuantity();
        int tempOrderlineProductId = orderline.getProduct().getProductId();

Avoid storing variables in temporary locals unless you really need to.

        if( Inventory.getInstance().getQuantity(tempOrderlineProductId)
                        == tempOrderlineQuantity  )
          {
                   shoppingCart.add(orderline);
                   log.warn("Product " + orderline.getProduct().getProductName()
                           +" ID: "+ tempOrderlineProductId
                           + "after purchase will have no more in stock");

          }
        else if(Inventory.getInstance().getQuantity(tempOrderlineProductId)
                        > tempOrderlineQuantity)
          {
                    shoppingCart.add(orderline);

Pull this out of the if blocks.

          }
        else if(Inventory.getInstance().getQuantity(tempOrderlineProductId)
                            == -1)

          {
                        throw new OutOfStockException("PrductId: " + tempOrderlineProductId
                                + " is not listed in the Inventory: "
                                + Inventory.getInstance().getQuantity(tempOrderlineProductId));

           }
         else
          {
                        throw new OutOfStockException("PrductId: " + tempOrderlineProductId
                                                    + " does not have enough to complete this order, the in Stock amount is: "
                                                    + Inventory.getInstance().getQuantity(tempOrderlineProductId));
          }

Move this entire if block structure into

   Inventory.getInstance().takeQuantity(orderline.getProduct(), orderline.getQuantity());

}

Basically, I'd end up with

public void addToCar(OrderlineType orderline) throws Exception
{
     orderline.getProduct().verifyIsAllowedToSell();
     Inventory.getInstance().takeQuantity(orderline.getProduct(), orderline.getQuantity());
     shoppingCart.add(orderline);
}


Template function for splitting strings in C++

Well, the formatting is peculiar — I can’t see where the function begins.

ContainerT &cont
const CharT *delimiter

The style in C++ is to put the * or & with the type, not the identifier.  This is called out specifically near the beginning of Stroustrup’s first book, and is an intentional difference from C style.

std::size_t start = 0, end;
  ⋮
while ((end = str.find(delimiters, start)) !=
       std::basic_string_view<CharT>::npos)

⧺ES.10: Declare one name (only) per declaration.

Meanwhile, you can declare end just where it is needed, not ahead of time.

while (size_t end=str.find(delimiters, start); end != str.npos)

You can also make the clauses of the condition more readable by making the names short:  For example, see that I used the same instance str to get npos rather than its class name.

  The function can split std::basic_string, not only std::string.
  How string_view in C++17 can help in this example. My version seems not take full advantages of it.

std::basic_string_view<CharT> str,

Your input argument str will be able to take basic_string of any character type, but only using the default Traits.  You might do that on purpose, if Traits are never used other than the defaults?

A string_view will take a string_view, string, or C-style lexical string.

  The delimiter can be a CharT, or const CharT* p or std::basic_string<CharT>

So this first form will take the latter two types, as well as string_view.  You do not need to overload to take CharT delimiter separately.

You do not need to overload to take basic_string for both parameters, because the string_view will take those!

So, two of the overloads should just be removed.  The last one, that takes a CharT delimiter, needs to take the string_view for str so it will handle different types for that — you have it taking a basic_string only, which will be inefficient (copied!) if passed a const CharT* or string_view.

template <typename CharT, typename ContainerT>
void split ( ⋯, ContainerT& conts)

Don’t use “out” parameters.  Return values (⧺F.20).

I can see the appeal here of getting template argument deduction on the return value, but that does not make up for the lack of composibility.  You can add a default type to the ContainerT template parameter, which is handy for the case where the user doesn’t care.

template <typename CharT, typename ContainerT = vector<basic_string<CharT>>
ContainerT split ( ⋯ )

You are assuming that the container holds elements which have the form of constructor you are expecting.

Anyway, now your first example in main becomes:

auto strs = split (str, ",");

template <typename Iter>
void print(Iter begin, Iter end) {
    for (auto it = begin; it != end; ++it) {
        std::cout << *it << "/";
    }
    std::cout << std::endl;
}

    print(strs.begin(), strs.end());

You should just take the container, not separate begin/end.  That not only makes passing easier, but makes the function easier too!

template <typename R>
void print(const R& rng) {
    for (const auto& item : rng) {
        std::cout << item << "/";
    }
    std::cout << '\n';
}

    print(strs);

Oh, and don’t use std::endl.

I also should point out that it’s good practice how you have unit tests for your function!


Is checking for null redundant while using Contract Annotator from JetBrains?

You said it yourself in your question :

  it can't prevent him/her of doing so though.

That settle it for me. You still have the responsibility to prevent that null value are pass to your classes. The annotation seems to be about preventing NullPointerException. So you should be checking for null values even if you use @NotNull.

    Preconditions.checkNotNull(login, "login is null or empty");
    Preconditions.checkNotNull(password, "password is null or empty");

Your message or the method you use is lying. The method is called checkNotNull but you warn about empty String, this is two very different things. Either you should modify you message to inform that you're only checking null values or you could change/rename the method checkNotNull to better represent the empty check.


Gulp task to increment a major, minor, or patch level of the version number of the last build

The first thing that I see is that:

    major = parseInt(versionArray[0]) + 1;

Is a bit redundant. You already say:

major = parseInt(versionArray[0]);

Just do:

major += 1;

(This is similar for all the major, minor and patch statements)

You can also use a switch-case instead of if statements so instead of:

if (ver === 'major') {
    major = parseInt(versionArray[0]) + 1;
}
else if (ver === 'minor') {
    minor = parseInt(versionArray[1]) + 1;
}
else if (ver === 'patch') {
    patch = parseInt(versionArray[2]) + 1;
}

You have:

switch (ver) {
    case 'major':
        major += 1;
        break;
    case 'minor':
        minor += 1;
        break;
    case 'patch':
        patch += 1;
        break;
}


Build process for compiling client JS modules into one script

Your approach is sound. The optimizer of RequireJS called r.js also scans the code for calls to methods with a special name (define and require) to detect dependencies.

You can see how this detection works in the file transform.js. As you can see, this optimizer uses a JavaScript parser, which is more reliable than using regular expressions: for example, your regular expression may match a call in a comment, which would be skipped using a parser.

There is another way to declare dependencies for RequireJS though, which is described in the Asynchronous Module Definition specification: wrap each module in a call to a function and list the dependencies explicitly in an array.

You may also be interested in the use of a simpler pattern for the declaration of modules, independently of the loader used.

With regards to circular dependencies ("when two files require each other"), there are two ways to handle them:

detect them and fail, forcing the developer to avoid them in their code
load one of the two modules with only parts of their dependencies, which requires extra care from developers: they can no longer be sure that all dependencies are available when the module runs, and must check before calling methods and accessing properties on required objects

Both approaches have drawbacks.


When you are using a class you can utilize a private/protected class property. As said you know about PDO and since I am not very familiar with the old school sqlsrv_* functions I have used PDO in the examples. An example could be.

class Database {

    /*
     * Having a private/protected property ensures that only
     * the class itself can change/removed the connection. This way calling
     * code cannot mess something up regarding the connection.
     */
    private $pdo;

    public function __construct($dsn, $username, $password, array $options)
    {
        $this->pdo = new PDO($dsn, $username, $password, $options);
    }

    public function __destruct()
    {
        $this->close();
    }

    /**
     * This is an utility method to expose the PDO instance. This
     * enables calling code to use the full toolset of PDO.
     *
     * @return PDO
     */
    public function pdo()
    {
        return $this->pdo;
    }

    public function query($sql)
    {
        /*
         * I do not enclose this inside a try-catch block
         * as only the calling code can decide if the application
         * can recover from the exception state.
         */
        return $this->pdo->query($sql);
    }

    public function close()
    {
        /*
         * Since PDO is an object closing a connection
         * is done by assigning the value NULL.
         */
        $this->pdo = null;
    }

}

If you look at the Database::close() method you can see that no parameters are required. We already have the property storing the current connection available. I am also using a __destruct() method to ensure the connection is closed as soon as the object loses all references. This frees up server resources earlier than if the connection was closed when the script ended.

You can also store the connection details/credentials inside the class an lazy load the connection only when it is actually required. There are plenty of tutorials around the web about this.

Hope this can help, happy coding!


How to format embedded if statements in JavaScript

How to format code is not really how CodeReview works ;)

You are indenting with 2 and with 4 spaces, pick one, I advocate 2
It is more common to compare _srwc to undefined itself
_srwc is an unfortunate name, it conveys no meaning
window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]); could use a comment block
Do not use console.log in production code
Also, read about apply, it allows you to call a function and pass an array of arguments so you don't have to be limited to 3 arguments.

if (_srwc !== undefined) {
  for (var i=0; i < _srwc.length; i++){
    var currentArg = _srwc[i];
    if (typeof window[currentArg[0]] == 'function') {
      window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
    } else {
      console.log('The Setter method: "' + currentArg[0] + '" is undefined');
    }
  }
}


Seems Range.RemoveDuplicates could turn it all into a much more efficient one-liner.

Stylistically though, the code could use some help anyway.

The rather procedure begins with a good dozen variable declarations. Code is easier to follow when you don't need to constantly scroll up and down and back to know what's what: by declaring variables closer to their usage, you reduce the cognitive load and avoid that scrolling.

Dim xlApp As Application
Set xlApp = Excel.Application

Now, there's no need for this variable; Application is free, globally-scoped, and you're not owning that instance - just copying a reference to an existing object. Don't do that, use the globals that are right there waiting to be referenced instead. This includes any worksheet that exist at compile-time in ThisWorkbook:

Dim wsSource As Worksheet
Set wsSource = xlApp.ThisWorkbook.Worksheets("source")

Every worksheet has a CodeName property, that you can change in the properties toolwindow (F4). Locate that "source" worksheet in the Project Explorer, then look at its (Name) property - change it from what defaults to e.g. Sheet1, to a meaningful identifier, e.g. SourceSheet. And now you have a free, global-scope worksheet object referring to that specific sheet, readily usable everywhere in that VBA project - which makes this wsSource variable redundant as well.

Dim rBefore As Range
Set rBefore = wsSource.Range(wsSource.Cells(2, 1), wsSource.Cells(wsSource.UsedRange.Rows.Count, 1))

It's not clear whether that r stands for Range (in which case it's useless Hungarian Notation), and Before what this range is. So we try to look at other usages to infer its meaning... and we don't find any: the variable is assigned, but the assigned reference isn't used anywhere - the variable is redundant and can be removed entirely.

Dim ws As Worksheet
Set ws = xlApp.ThisWorkbook.Worksheets("testSheet")

Again, the CodeName could be TestSheet, and ws wouldn't be needed, provided that the worksheet exists at compile-time. Otherwise, kudos for fetching it from the Worksheets collection.

Dim r As Range
Set r = ws.Range(ws.Cells(2, 1), ws.Cells(ws.UsedRange.Rows.Count, 1))

UsedRange isn't a reliable way to get the last row of a column.

r isn't a meaningful name. testRange would tell us it's from the TestSheet, but wouldn't convey what it means - any single-letter variable name can never tell us anything whatsoever about something's purpose. Unless it's i for a For...Next loop counter, which any programmer knows about; here i isn't used like that, it's more like some processedRows.

DoEvents inside the loop, combined with updating the status bar at every single iteration, is contributing to slowing things down.

You're disabling ScreenUpdating, automatic Calculation, etc.; but you leave EnableEvents enabled, so a worksheet event is fired whenever you delete a row. You could use Union to combine all the rows you want to delete, and then delete them all in one single operation - instead of deleting them one at a time. But then again, Range.RemoveDuplicates makes that moot.

There are a number of issues (it's a constant work-in-progress), but Rubberduck could have picked up a number of the observations I made above. Kudos for Option Explicit, the meaningful name, and the explicit Public modifier on your macro!


Preventing SQL injection without using prepared statements

never return from constructor
avoid having new statements in the constructor
on error, throw an exception instead of echo + exit
% is used in MySQL's LIKE syntax
you should refactor your DatabaseConnection::query() method - it's too high cyclomatic complexity
constants are global immutable state (it's not as bad as mutable globals, but still a bad idea)
you should be using spl_autoload_register instead of the archaic __autoload
you are mixing HTML with logic .. bad idea, try this approach instead
don't use ".class.php" in filenames, because then you will be screwed, when you start adding interfaces (which one would want to autoload too)


Creating a directory structure from JSON

It seems fine, but I suggest to improve some minor improvements:

filename is not a simple file name but has directory element too, so I'd call it path
Instead of calling os.path.dirname twice, I'd call it once and cache the result in a local variable

Like this:

package_name = response['Package'][0]['fields']['name']
for doc in response['Document']:
    path = os.path.join(package_name, doc[0]['fields']['name'])
    basedir = os.path.dirname(filename)
    if not os.path.exists(basedir):
        os.makedirs(basedir)

    content = doc[0]['fields']['content']
    with open(filename, "w") as f:
        f.write(content)

Btw, the JSON structure looks a bit odd,
with several arrays with a single element.
Makes me wonder why these arrays are there at all,
instead of their contained objects directly.

I'd also be concerned about format changes in the JSON:
your code is tightly coupled to an unintuitive structure,
and if anything changes later,
it might be difficult to migrate the implementation.


SQL to find table containing all specified columns

In this case, I would consider using a CTE to contain the columns you are interested in. This saves having to declare the variables, and also saves the inserts, etc. The basic concept is the same as your second query though...

with FindColumns as (

    select 'DataAreaId' as Seek
  UNION
    select 'CountryRegionId' as Seek

), MyTables as (

    select object_id as Tab,
           count(*) as ColCount
    from sys.columns inner join FindColumns on name = Seek
    group by object_id

)

select *
from sys.tables
inner join MyTables on object_id = Tab
where ColCount = (select count(*) from FindColumns)

Note how this is really just a re-expression of your second query using Common Table Expressions

I put that query together on the Stack Exchange data explorer as an example using a couple of different column names.... you can see it working there.


Determining if variables (integers) are greater or less than 0

The following will simplify your boolean logic, remove repetition in your input processing, and better express what you're really doing:

puts "please assign an integer to x:"
x = gets.chomp.to_i

puts "now please assign an integer to y:"
y = gets.chomp.to_i

num_positive = (x > 0 ? 1 : 0) + (y > 0 ? 1 : 0)

case num_positive
when 2
  puts "two variables are > 0"
when 1
  puts "at least one variable is > 0"
else
  puts "no variables are > 0"
end


def is_string(data):
    return isinstance(data, str)

def is_bytes(data):
    return isinstance(data, bytes)

I personally think that there isn't much gained by adding these two functions, but others may disagree (your post suggests you might). In otherwords, I would just write isinstance(data, str) wherever I see is_string. However, I think encodeable is sufficiently complicated to be a good stand-alone utility function.

I would also move:

s = str('spam')
r = r'eaggs'
b = b'slurm'
print('Before encoding')
print(s, r, b)
print(type(s), type(r), type(b), '\n')

print('After encoding')
s, r, b = encode(s), encode(r), encode(b)
print(encode(s), encode(r), encode(b))
print(type(s), type(r), type(b))

To a doctest.


Implementation of perceptron, inspired by Rashka

Style

Python comes with an official Style Guide often just called PEP8, and especially as a beginnger it's a good starting point to get going. Of course coding style is often a matter of choice, however, there are aspects you should definitely follow.

Whitespace
As you know, Python's code structure is build upon indentation, so some parts are already language-defined. The style guide also has recommendations on how to use whitespace within statements and expressions. For example, , should always be followed be a single space character, while = is preceded and followed by a single space when used in assignments (there should be no whitespace around = if used as keyword arguments to functions such as foo(batz='bar')). So you would go from

gradL_W,gradL_b=self.backward(y_i,y_hat,x_i)
self.w_,self.b_=self.update(gradL_W,gradL_b)

to

gradL_W, gradL_b = self.backward(y_i, y_hat, x_i)
self.w_, self.b_ = self.update(gradL_W, gradL_b)

which does look way cleaner IMHO.

Variable names
It's always good practice to use descriptive variable names. Simply writing self.weights instead of self.w_ wont hurt that much. Apart from that, the Style Guide also recommends to use a single leading underscore for non-public variable names. Note, this is only a convention, since Python has no "real" private member variables as you may know from other languages.

Documentation
There is a single function in your perceptron class that has a) documentation and b) also follows the docstring-style from the Style Guide. You should apply that to the other functions and maybe even to the class as well. Your current project might be simple, but if projects become more complex, good documentation will save you a lot of headache. Following the official docstring style also has the nice benefit that Python's help(...) function as well as most IDEs will easily find it.

The code

Apart from the stylistic issues mentioned above, there are some more direct code-focused aspects you should work on.

Code duplication
There is some duplicated code in your implementation of the perceptron model. E.g., you implement the scalar product at the input of the perceptron twice! The first time at net_input, which is likely where it's supposed to go, and the second time in predict. predict also reimplements pretty much the whole point of activation. It's pretty straightforward to implement predict using net_input and activation:

def predict(self, X):
    s = self.net_input(X)
    y_hat = list(map(self.activation, s))
    return y_hat

If you use Python for a while you will also learn to use list comprehensions more often than the list(map(...)) construct, simply because it's more flexible and readable. Rewriting the calculation of y_hat as list comprehension would look like y_hat = [self.activation(i) for i in s]. After you have arrived at

def predict(self, X):
    s = self.net_input(X)
    y_hat = [self.activation(i) for i in s]
    return y_hat

you may also find the similarity between predict and forward quite striking. forward can now be boiled down to simply

def forward(self, x):
    return self.predict(x)[0]

Getting the "first" result of the return value using [0] is mainly to ensure that the new version just returns a single number as it was before. Otherwise it would be a list with a single element.

Explicit is better than implicit

(Taken from the Zen of Python)

Using code like

heaviside = lambda x: (1, -1)[x < 0]
return heaviside(z)

might be clever, but clever does not equal good or readable most of the time. The same thing can also be expressed as return -1 if z < 0 else 1, which is almost a verbatim translation of the mathematical definition of the step function as presented by Rashka. If you don't like the inline-if, you may also write it as "normal" if condition:

if z < 0:
    return -1
else:
    return 1

gradL_b = error * 1 is another instance of cleverness. This time, I am not even sure what you are actually trying to accomplish here. Depending on the type of your labels y, error will either be of type int or maybe also float, and multiplying it with 1 will not change that.

errors += (y_hat != y_i) * 1 is more obvious, but could also be expressed explicitly as errors += int(y_hat != y_i). Python should even be able to do errors += y_hat != y_i without changing the end result.

Return values
I'm not 100% sure what you are trying to accomplish with some of your function return values. For example, I cannot see the point in fit returning self. updateis another instance of that topic. I can see you're using it as self.w_, self.b_ = self.update(gradL_W, gradL_b), but there is not a real reason to do this, since update already modifies the weights internally.

You will likely have to think about that topic as you further progress in your journey into the depths of neural networks (pun intended). Often, the multilayer perceptron is  one of the next logical steps in this process. At this stage, you will need the gradients of previous layers to be able to propagate errors through the network. But time will tell1.

Until then: Happy coding!

1You will also probably soon find out that modelling single neurons is not sufficient (and computationally efficient) for what there is to come. Depending on your learning materials, matrix operations will pop up more and more often. This is the time where the NumPy library will help you shine.


Automate The Boring Stuff - Character Picture Grid

It's wasteful to use range() and then only use the result for indexing.
Instead, just iterate directly over the values:
for col in range(len(grid[0])):
    for row in grid:
        print(row[col],end='')
    print()

We can simplify, though - use the zip function to transpose the array:
transposed = zip(*grid)

for row in transposed:
    for col in row:
        print(col,end='')
    print()

The next simplification is instead of printing one character at a time, we can use join to form strings for printing:
for row in zip(*grid):
    print(''.join(row))

And we can join all the rows using '\n'.join(), giving this final version:
print('\n'.join(''.join(x) for x in zip(*grid)))

Equivalently, using map:
print('\n'.join(map(''.join, zip(*grid))))


When it comes to system backups, I think it's more important to know what you include than to know what you exclude.
So instead of specifying what you exclude,
I think it's better to think about what you need to include.
It might be a shorter list,
and less noisy without all the --exclude flags.

Your current method is wasteful: the backup takes twice the size it needs,
once for the .tar.gz, and once for the split version. You could pipe the output of the tar command to split to save some space, for example:

sudo tar -cvpz --one-file-system /usr /etc /home ... | split -b 100MB - "/HDD/systemBackup/$date-"

Most importantly, as @tarleb also said, make sure to test restoring from backup. An all too common mistake is to not test restoring, and one day when you really need it, your backups turn out to be useless.

  Will this method also work on both a Raspberry Pi and an Ubuntu system?

The list of directories you want to backup might be a little bit different.
If you have to inspect both systems and see.
Other than that, the same technique should work, yes.

  Is this a good method of backing up my Linux system to the web?

This is one way to do it.
It's a full backup.
Its advantage is that it's simple.
Its drawback is that it wastes a lot of space,
because much of the data in each backup for different $date values will be duplicated.
And transferring over the network will be relatively slow.

An alternative would be using incremental backup,
which would save disk space and network bandwidth,
at the expense of considerably more complex backup and restore procedure.

One more way would be to rsync the interesting directories,
and take create a timestamped archive at the other side.
That would save disk space locally, save network bandwidth,
and still be relatively simple.


Two click functions doing the same thing with difference the selector

Here are 3 - there are more, no doubt

Give both checkboxes a class and use that as the selector

$(".someClass").click( ... )

Declare the event handler elsewhere, and use it anywhere:

function checkboxClick(event) {...};

$subparentCheckbox.click(checkboxClick);
$childCheckbox.click(checkboxClick);

Use .add to combine the two checkboxes into one collection before calling .click like so

$subparentCheckbox.add($childCheckbox).click(...)`