How to Make This JavaScript Snippet DRY (Don't Repeat Yourself)?

You can refactor this to follow DRY by using the Strategy Pattern.

function registerEvents(){
    var delegationStrategies = [
        {var1: '.add-control .add-image',
         var2: 'tap',
         func: function (evt) {
             handleAddControlEvent(this);
         }
        },
        {var1: '.delete-image',
         var2: 'tap',
         func: function (evt) {
             evt.stopPropagation();
             handleDeleteControlEvent(this);
         }
        },
        // Add more strategies here.
    ];

    for (var i=0; i< delegationStrategies.length; i++){
        strategy = delegationStrategies[i];
        $(document).delegate(strategy.var1, strategy.var2, strategy.func);
    }
}

You may need to add a special case for the timeout.

The question is whether you foresee the need to add further delegation handlers in the future.  If so, then it is a matter of adding another entry to the strategy.


Removing duplicate audio files with different UTC timestamps in filenames, using PowerShell 5

While -Filter is usually the fastest way as it handled by the provider,
I'm not sure this is true compared to one -Include with an array which only recurses once instead of 8 times.

$Include = '*.clip*','*.ptf','*.wfm','*.repeaks','*.DS_STORE','._.*','Thumbs*.db','*.ini'

Get-ChildItem  -Recurse -Name -Include $Include | Remove-Item

As for the duplicates, your approach will only eliminate dupes in the same folder.
An alternative would be grouping the output with a calculated property which strips off the date in parentheses. And then iterating the groups and sorting by whatever means, keeping only the first/last - removing the others.


Loop termination check for multiple types of host reachability tests

Good names make everything better

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

This signature was clearly generated by a tool. Even though you only need one of the arguments and it is used on the first line of the function doesn't mean the arguments shouldn't have good names.

What happens if I need to use the long argument later? I haven't been in this code for a while, but I just have to add this one simple line. I'm pretty sure arg2 was the long. Oops, arg3 is the long and the int gets implicitly converted and the complier doesn't care. If the arguments had real names, it would be much harder to make this mistake.

That is some what of a contrived example because you could just look at the signature to see that arg3 is the long. But how about this. I haven't had to implement an OnItemClickListener before. I don't know what the arguments are supposed to mean. Why is there a long and an int? Since you didn't take the time to give the arguments real names, I need to look at the documentation to see what each argument means.

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

Seeing that gives me a good idea of the context. Then only if I need more information do I have to look at the documentation.

type also doesn't help me know anything about what this variable is doing. Add the fact that it is an int and there tons of possible values, how do I know what the right value is and I use it properly?

enum HostConnectivity { Lan, Wan, Both }

// ...

final HostConnectivity connectionType = tmp;

Now it is clearer what kind of type we are dealing with and what each value means. This also removes the magic numbers from evalFlag(). It makes it easy to see if the switch does the wrong check for one of the cases.

Using tmp can be acceptable when it is a short lived variable that actually is temporary. (See the middle section to see how it can be removed and solve another problem.)

evalFlag() is a very generic name. It sounds like it is doing some operation on the flag variable. But there is no flag variable. Also, flags are generally throughout of as boolean, either set or not. Your type has multiple states.

What the method is doing is performing a check of the host's connectivity. it happens to be using the type to decide what checks to perform. The while loop isn't concerned with how the type is being used, it cares about what the boolean result. checkHostConnetivity() would be a much better name.

Sub-functions make life easier

Extracting the type selection code into a sub-function.

private HostConnectivity chooseConnectivity() {
    if (!host.isReachableOnLan && !host.isReachableOnWan) {
        return HostConnectivity.Both;
    }
    else if (host.isReachableOnLan) {
        return HostConnectivity.Lan;
    }
    else {
        return HostConnectivity.Wan;
    }
}

Now there is no need for a temporary variable. Also, by separating the choosing from the initialization, you can remove the repeated code that you had a comment about wanting to combine.

final HostConnectivity connectionType = chooseConnectivity();
switch(connectionType) {
  case Both:
    new WakeOnLan(host, host.wolBroadcast).start();
    new WakeOnLan(host, host.wanHostName).start();
    break;
  case Wan:
  case Lan:
    new ExecuteSshCommand(host, host.sshShutdownCommand).start();
    break;
}

Instances never die

There are a number of times when you create a new instance, never store the reference, and just start the operation. You should be careful with this. You need to make sure that these things can not run for ever. The OnItemClickListener might not be able to know if/when the thread should stop running. But it is very likely that you might want to kill the tread before it has completed. It is not clear what WakeOnLan and ExecuteSshCommand are doing and if they might also have a potential to run for a long time. Or maybe they fail and need to be checked later.

It is possible that not storing the references is not a problem in this case. But this type of action should be done with care.


Decimal number to binary number conversion in JavaScript

Comment says, that function will return a string, and then returns a number.

if (decimalNumber === 0) return 0

Best improvement would be using a native method

function getBinaryNumber(num, sep) {
    if (typeof num != "number") num = parseFloat(num)
    return sep ? num.toString(2).split("").join(sep) : num.toString(2)
}

I would remove separator parameter, as it makes no sense to combine this functionality.

function getBinaryNumber(num) {
    return (typeof num == "number" ? num : parseFloat(num)).toString(2)
}


Convert unsigned Integer to ASCII in x86 assembly

It’s been a good many years since I wrote significant code in x86 assembly language, but I’ll wade in here.

Yes, div is a fat pig of an instruction.  It not only takes a ridiculous number of clock cycles, but it uses many of the dispatch ports, clogging the CPU so it can’t do much else while waiting on the result.  See the links in this S.O. answer.

This is because division is difficult.  You could look up how to transform division by a constant (10 in this case) into multiplication and code that.

But, successive division/modulo by 10 is now I learned it.

The biggest speed benefit will be from allowing pipelining to work well and not stalling.  Sometimes you code two or three different copies of the loop and interweave them so that there is more independent calculations to work on at the same time.  To that end, you might start by dividing by 10000 once and then doing high digits and low digits separately in interwoven loops.

But, using the div instruction makes that difficult because it has pre-targeted registers that it uses, and worse, the instruction does not pipeline.

I think the fastest would be to use the div-less algorithm with vector SIMD instructions to compute multiple digits at the same time.

sketch of an idea

Avoid all division/modulo and instead build up the decimal representation using decimal arithmetic!

A 64-bit value can also be treated as 8 bytes; each byte is a digit (not packed as BCD nibbles, but one per byte).  You can add them by adding the 64-bit integers — each byte will add, and there can be no caries outside of the byte because the largest result is 18 and you can hold up to 255.

In particular, doubling such a value means adding it to itself.  The hard part, which I’ll explain later, is following that up with carry propagation.

So, start with a 8-digit unpacked decimal set to all zeros; call that Accumulator.

Loop while In != 0  :

Take your normal integer (called In) and mask off the lowest bit, getting a result that is either 0 or 1.  Add that to the least significant byte of Accumulator.  Note that you have no if here, no branching.  It will simply add zero accomplishing nothing, or add one.  You can do that add using a 32-bit or any other sized int aliased with the Accumulator, not just a byte, because you know the carry will not happen out of the byte.  I mention this because byte arithmetic is slightly slower than 32/64.

Then, shift In right one bit.

Add Accumulator to itself, using the aliasing trick I mentioned before.

Process the carries.

[end of loop]

Convert Accumulator to an ASCII representation by adding 0x30 to each byte.  This can be a constant of 64 bits, so you do this in one add.

So, how do you propagate the carries?  Use SSE instructions.

Load the Accumulator into an SSE register.  Use an instruction which compares each (byte) element against 10 and produces a packed bitmap of the results.  There will be 16 bits, indicating which bytes are too large for decimal.

Use that bitmap as a mask to subtract 10 from each enabled byte.  You can use the same SSE register loaded with all 10's for both steps.

Shift the bitmap left by one bit.  Now use that as a mask to add 1 to every enabled byte.

Now, saving the SSE register back to RAM and loading it again will slow it down.  So do the doubling (adding the register to itself) in SSE, also.  Adding the new In bit can be done with separate instructions, or rolled into the carry step by setting the least bit (or not) after shifting left.  Whichever is the least amount of jumping through hoops or avoiding a branch.


My solution to a competitive programming problem (UVA 10189, Minesweeper)

Even in the case of timed contests, you should not sacrifice good practices for brievity. What you gain typing less is lost when debugging or re-reading code.

Using functions to separate logical units of code is the least you should do here as it help isolate, test and assert correctness of each step of the algorithm more easily.

You should take the habbit of starting to write/configure a template in your IDE:

# imports

def main():
    pass

if __name__ == '__main__':
    main()

Here you start by reading the entire input and then extract out tests cases afterwards. I see two issues with that:

you may run into memory issues if the number of tests cases and/or their length is huge;
you do not take advantage of the highly structured input spec.

I would define the following function:

def read_test_case(lines_amount):
    return [input() for _ in range(lines_amount)]

And call it like:

def main():
    while True:
        lines, columns = map(int, input().split())
        if not lines:
            return
        field = read_test_case(lines)
        # ...

You also perform a lot of for ... in range(len(...)) which is rather inefficient. Consider using direct iteration like you do with for field in fields or enumerate if you also need indices:

MINE = '*'

def build_hints(field, lines_max, columns_max):
    def count_mines(x, y):
        count = 0
        for x_offset, y_offset in itertools.product(range(-1,2), repeat=2):
            x_ = x + x_offset
            y_ = y + y_offset
            if x_offset == y_offset == 0 or not (0 <= x_ < columns_max and 0 <= y_ < lines_max):
                continue
            count += field[y_][x_] == MINE
        return count

    return [
        [
            MINE if square == MINE else str(count_mines(x, y))
            for x, square in enumerate(row)
        ]
        for y, row in enumerate(field)
    ]

All what is left is to put all pieces together and print elements. Which lead to:

import itertools

MINE = '*'

def build_hints(field, lines_max, columns_max):
    def count_mines(x, y):
        count = 0
        for x_offset, y_offset in itertools.product(range(-1,2), repeat=2):
            x_ = x + x_offset
            y_ = y + y_offset
            if x_offset == y_offset == 0 or not (0 <= x_ < columns_max and 0 <= y_ < lines_max):
                continue
            count += field[y_][x_] == MINE
        return count

    return [
        [
            MINE if square == MINE else str(count_mines(x, y))
            for x, square in enumerate(row)
        ]
        for y, row in enumerate(field)
    ]

def print_hints(hints):
    for row in hints:
        print(''.join(row))
    print()

def read_test_case(lines_amount):
    return [input() for _ in range(lines_amount)]

def main():
    for test_case in itertools.count(1):
        lines, columns = map(int, input().split())
        if not lines:
            return
        field = read_test_case(lines)
        hints = build_hints(field, lines, columns)
        print('Field #{}:'.format(test_case))
        print_hints(hints)

if __name__ == '__main__':
    main()


Should my Json storage handle exceptions?

This is how I see things...

Throwing ArgumentException insinde a try/catch that at the same time swollows it is pointless. You use ArgumentException to inform the user that he called your API in a wrong way. This is not something one should hangle because he won't see it until he looks at the logs. The app should crash in this case.
The message of the ArgumentException is too generic. When it happens, the user already knows something is wrong. Tell him how to fix that by giving him a hint what the correct path should be and what path he actually used.
The way you are handling exceptions that might be thrown by the json-serializer is unexpected (non-standard) because the user will wonder why he got a null without noticing anything. public library APIs should always throw unless they are called TryDoSomething and return a bool.
Yet another flaw of this pattern is that it doesn't help anyone to find the source of the exception. You neither add the filename to it nor the object that it tried to de/serialize. This is very important piece of information and should be included.

So, what you can/should do instead is to throw a new exception that adds more information about what happened e.g.:

public T RestoreObject<T>(string path)
{
    if (!fileSystem.Path.IsPathFullyQualified(path))
            throw new ArgumentException($"Invalid path: '{path}'. It must by fully qualified.", nameof(path));

    try
    {
        string json = fileSystem.File.ReadAllText($"{path}.json");
        return JsonConvert.DeserializeObject<T>(json);
    }
    catch (Exception ex)
    {
        throw new JsonStorageException($"Could not restore object '{typeof(T).Name}' from '{path}'.", ex);
    }
}

You'll be happy to see the type and file name when something goes wrong.


First reaction: wow this is scary: Python script generating Bash which again calls some Bash in it. But I see the filter-env technique comes straight out from an example in the docs.

I would have written this in pure Bash, using a helper function that takes as parameters:

author name
author email
one or more bad email addresses

And then for each bad email address, call git filter-branch like you did,
but all in pure Bash.

As far as the Python part is concerned, this can be done better:

emails_string = ""
for email in dev["emails"]:
    emails_string += '"%s" ' % email

Using a list comprehension:

emails_string = " ".join(['"%s"' % email for email in dev["emails"]])

With this, you don't need to .strip() the emails_string when you generate the command string.


Disclaimer: I maintain the gmpy2 library which also provides arbitrary-precision arithmetic.

gmpy2 includes fast integer arithmetic based on the GMP library. If gmpy2 is not installed, mpmath uses Python's native integer type(s) for computation. If gmpy2 is installed, mpmath uses the faster gmpy2.mpz integer type. You didn't mention if you have gmpy2 (or gmpy, an older version) installed, so I ran one test with your original code, mpmath, and without gmpy2. The running time was ~91 seconds. With gmpy2 installed, the running time was ~63 seconds.

The rest of the examples assume gmpy2 is installed.

Your code include superfluous calls to mpf(). Since x is already an mpf, the result of x+1 will also be an mpf so the mpf() call is not needed. If I remove those calls, the running time drops to ~56 seconds.

You import from both numpy and mpmath. mpmath.sin and mpmath.log10 replace the functions imported from numpy. But you are still using numpy.absolute. Numpy can be very fast but only when uses types it natively supports. If I remove numpy and change absolute to abs, the running time drops to ~48 seconds.

Here is the code with all the changes listed from above:

from __future__ import division
from mpmath import *
import time
imax = 1000001
x = mpf(0)
y = mpf(0)
z = mpf(0)
t = mpf(0)
u = mpf(0)
i = 1
mp.prec = 128
start_time = time.time()
while i < 1000001:
    i += 1
    x = x + 1
    y = y + x * x
    z = z + sin(y)
    t = t + abs(z)
    u = u + log10(t)

print("--- %s seconds ---" % (time.time() - start_time))
print x
print y
print z
print t
print u

I don't see any other significant improvements for an mpmath based approach.

gmpy2 also provides arbitrary-precision floating point based on the MPFR library. If I use gmpy2 instead, the running time is reduced to ~18 seconds.

Here is the code for a gmpy2 based solution:

from __future__ import division
import gmpy2
from gmpy2 import mpfr, sin, log10
import time
imax = 1000001
x = mpfr(0)
y = mpfr(0)
z = mpfr(0)
t = mpfr(0)
u = mpfr(0)
i = 1
gmpy2.get_context().precision = 128
start_time = time.time()
while i < 1000001:
    i += 1
    x = x + 1
    y = y + x * x
    z = z + sin(y)
    t = t + abs(z)
    u = u + log10(t)

print("--- %s seconds ---" % (time.time() - start_time))
print x
print y
print z
print t
print u


naming da* + all lower case makes it hard to parse the difference between the prefix and the name of the function, instead either pick da_snake_case or daCamelCase.
returning void* is not ideal instead create a opaque (incomplete) struct and just let the use pass pointers to that struct around:

struct DynamicArray;

DynamicArray* danew(size_t unitsize);


Is there a more efficient way of loading views within my java app?

First off, its not clear what you're trying to achieve, so its hard to evaluate.

But, looking a the code there comes after you forward to the view, that could be confusing, because it will still execute.

At a higher level, I also don't really see the need for this complicated of a setup to get to your edit page when you can just link straight to the edit jsp all nice an RESTful like.  If you're just experimenting and trying to learn that's cool, but if you're really trying to get something done then you should look at just using an existing framework.


Click textbox to show answer and highlight related text

Here are my thoughts:

Most importantly from the first look at the code: Use proper variable names. No one knows what you mean with EEE, xxx or e2. And while you are at it: in JavaScript it's a convention to start variable names with a lower case letter.
Don't make up attributes such as "answer" - you can't say if an unknown browser can work with them. At least you should adhere to HTML5 and prefix the custom attribute with data-.
name is not a valid attribute for span (or any other object other than form elements). Unfortunately there is no simple, cross-browser alternative for selecting multiple elements. The easiest soltuion with be to use a class and getElementsByClassName, however the latter isn't supported by all browsers yet, but there are implementations for the non-supporters easily available on the web.
The "Click" text is bad for two reasons: A) You can't actually click on it and B) texts such as "click here" is bad UI. Instead wrap the text together with the checkbox in a <label> element, such allows the user to click on the text to activate the checkbox and use a text such as "Show solution" instead.
Finally, there are more elegant ways to switch on the answers. Instead of looking of a specifc ID, set (or remove) a class on an element surrounding the question and use CSS to highlight/show the sub elements. Example: http://jsbin.com/ayoqem/7/edit


Consider using conditional aggregations to avoid the multiple subqueries:

SELECT e1.city,
    SUM(CASE end_date > (sysdate - interval '1' minute) THEN 1 ELSE NULL END) as las_min,
    SUM(CASE end_date > (sysdate - interval '1' hour) THEN 1 ELSE NULL END) as last_hours,
    SUM(CASE TRUNC(end_date) <= sysdate THEN 1 ELSE NULL END) as today,
    SUM(CASE end_date BETWEEN add_months(trunc(sysdate,'mm'),-1)
        AND last_day(add_months(trunc(sysdate,'mm'),-1)) THEN 1 ELSE NULL END) as last_months
FROM Employee e1
GROUP BY e1.city;

And even shorter, sum the logical expressions:

SELECT e1.city,
       SUM(end_date > (sysdate - interval '1' minute)) as las_min,
       SUM(end_date > (sysdate - interval '1' hour)) as last_hours,
       SUM(TRUNC(end_date) <= sysdate) as today,
       SUM(end_date BETWEEN add_months(trunc(sysdate,'mm'),-1)
           AND last_day(add_months(trunc(sysdate,'mm'),-1))) as last_months
FROM Employee e1
GROUP BY e1.city;


Using dapper Unit of Work in 3-tier architecture

You're correct in point #1 that passing the connection string to each service to get your UoW instance is bad form.  I'm not sure if that code was designed for a DI first world as is the case Asp.Net Core.

My recommendation (for #2) is keep it simple.  Remove the Unit of Work shell, but keep the repository contained inside.  Repository methods are usually transactional, and according to your question, you're using Dapper, so maintaining transactional consistency can be done per method call (not based on state as with the UoW).

SQL transactions are part of the natural semantics of Dapper:

public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

So your repository methods have the rough form of:

(assuming an open connection)

using(var tran = connection.BeginTransaction()) {
    try {
        // multiple operations involving connection and tran here

        tran.Commit();
    } catch {
        tran.Rollback();
        throw;
    }
}

The Dispose() is implicit to the using and you've neutralized your issue.

See: using Statement

If you absolutely need UoW style, you may consider moving to something like Entity Framework (or a heavier weight ORM in general), as the DBContext is essentially a much better featured and maintainable unit of work design, if not overkill for your project.


There are several advantages to writing proper HTML and using semantic tags. Instead of asking yourself "How should this look?" Ask yourself "What does this mean?".

What does it mean for a text to be red? Does it mean <em>phasized text? Maybe <strong> text? You can always apply the style="color: red;" on top of that (or even better, with a classname).

What are the advantages?

<font> is deprecated. Today it's still supported, mainly due to idiots who want their sites to run with IE5.5, but that may not be the case in the future. One day, <font> might just stop working altogether. Its behavior is currently undefined in latest versions of HTML, and will lead to unpredictable variations between browser implementations, and between browser versions.
Using proper elements (<em>, <strong> as opposed to <span> or <font>) makes machines understand your text better. That's good for accessibility, SEO, and a bunch of other things that entities which are not actual human readers do.
Using proper elements makes your site look better by default. Say a client does not use CSS, he's on a very old phone, or just uses some obscure browser. <em> shows up as italicized, <strong> shows up as bold. <span> shows up completely normally.

Other than that, if you're already defining all of the CSS rules in your template engine, why not use HTML to begin with? There's no point in complicating things with yet another syntax. Write valid, proper HTML from start to end, and be done with it.


You are right that returning an object where a is a function would not work, but it would work to return the result of a call to a function!

You can also restructure things a bit to reduce duplicated code. By having a starting string or a starting object, and optionally adding to that string or object if some conditions are fulfilled.

This is untested code, but I think it should do the same as your original.

function result(addAlpha, rgb, asObject) {
    if (asObject) {
        var obj = { r: rgb[0], g: rgb[1], b: rgb[2] };
        if (addAlpha !== false) {
            obj.a = addAlpha;
        }
        else if (rgb.length == 4) {
            obj.a = rgb[3];
        }
        return obj;
    }

    var a = (addAlpha !== false) || (rgb.length == 4) ? "a" : "";
    var alpha = "";
    if (addAlpha !== false) alpha = "," + addAlpha;
    else if (rgb.length == 4) alpha = "," + rgb[3];
    return "rgb" + a + "(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + alpha + ")";
}


I would make a single function, since all your functions do the same thing. It just needs an extra argument.

    /// one all-purpose function
    function saveData ($user_ID, $data_field) {
        $data = !empty($_POST[$data_field]) ? wc_clean($_POST[$data_field]) : '';
        update_user_meta( $user_ID, $data_field, $data );
    }

    /// define actions
    $actions=array("sfirst","slast",...);

    /// run actions
    foreach ($actions as $action) {
        add_action( 'woocommerce_save_account_details','saveData',$action);
    } unset($action);


The test if (so.scan_complete and force) or not so.scan_complete: only fails when so.scan_complete is True and force is False. So it can be simplified to if force or not so.scan_complete:.

Also, since the test is identical for every src, it only needs to be done once:

for src in engines:
    for query in queries:
        so = Source.objects.get(term__term=query, engine=src)
        if force or not so.scan_complete:
            if src == 'alibaba':
                ali_results.delay(src, query)
            elif src == 'madeinchina':
                made_results.delay(src, query)
            elif src == "google" or src == "bing":
                search_engine_scraper.delay(query=query, source=src)


From the comments, I guess you would like a theoretical review ;)

This:

<button onclick="javascript:alfred('greet')">Arrive at Hotel</button>
<button onclick="javascript:alfred('acceptTip', 10)">Tip Alfred $10</button>

in my mind should be wired by the controller,  that is, the linking of UI elements to data and UI changes
This:

greet: function () {
    this.model.view.innerHTML = '"' + this.model.greeting + '"';
},

has your controller access data straight in your view, updating the DOM. This is wrong in my mind. The view should have functions that the controller can call with either the model as a parameter or already passed in advance.
Object.create(controllerPrototype); <- Any reason you are eschewing new and prototype ?
Not that it truly matters but, method === "model" will not catch new String('model')
args = [].slice.call(arguments, 1); works as well as the ternary

All in all, I think this could use some more polishing.


Python - Making A Valid Date Checker - using Regular Expressions

Docstrings / Type hints
These allow you to describe how your code works in a pythonic manner. Docstrings allow IDE's and other documentation tools to see what your function/class does. Type hints allow you to show what types of parameters are accepted, and what types of values are returned.
check_date
Instead of calculating a leap year yourself, you can use calendar.isleap from the calendar module.
Return comparisons, not raw booleans
Instead of
if day <= day_bound:
    return True
return False

do this
return day <= day_bound

Does the exact same thing, but looks a lot nicer.
Split code into functions
You've done a good job splitting your code into functions, but I think you could use one more. Instead of parsing the date in the "main" code, put that code in another function, and pass it the date string.
def get_date_values(...) -> ...:
   ...

With all these changes, your final code would look something like this:
import re
import calendar
from typing import Tuple, Union

def check_date(day: int, month: int, year: int) -> bool:
    """
    Returns a bool based on if the date passed is a valid date.

    :param int day: Day.
    :param int month: Month.
    :param int year: Year.

    :return: True if a valid date, False otherwise.
    """
    # April, June, September, November = 30 days/ February = 28 days, unless leapyear so 29/ rest has 31 days
    month_dict = {4: 30, 6: 30, 9: 30, 11: 30, 2: 28}
    day_bound = month_dict.get(month, 31)

    if day_bound == 28:
        if calendar.isleap(year):
            day_bound = 29

    return day <= day_bound

def get_date_values(date: str) -> Union[Tuple[int, int, int], None]:
    """
    Returns a tuple containing the day, month, and year of the passed date.

    :param str date: Date to parse and retrieve values.

    :return: Either a Tuple, or for an invalid date, None.
    """
    date_regex = re.compile(r"([0-2]\d|3[01])/(0\d|1[0-2])/([12]\d{3})")
    match = date_regex.search(date)
    if match:
        return (int(match.group(1)), int(match.group(2)), int(match.group(3)))
    return None

if __name__ == "__main__":
    date = "31/02/2020" #DD/MM/YYYY
    if check_date(*get_date_values(date)):
        print('Valid Date!')
    else:
        print('Invalid Date!')

I'll explain a bit more since I made some changes I haven't mentioned already.
Unpacking
if check_date(*get_date_values(date)):

This line unpacks each item from the tuple returned by get_date_values and passes them to the function. Since the tuple has three values, and check_date accepts three parameters, the * unpacks the tuple and passes each value to the function.


Getting a connection to the database and executing statements

I think both classes have problems. Class A looks like an improperly implemented singleton and Class B has so many issues (detailed below) that it should probably just be thrown away as it is not really close to being suitable for inclusion in any code base.

In class A, why store both an instance of the class and an instance of PDO?  If you really wanted to stick with singleton I would simplify this down to something like:

class PdoSingleton
{
    public static $pdo;

    private function __construct() {}

    public static function getInstance() {
        if(self::$pdo instanceof PDO === false) {
            self::$pdo = new PDO(...);
        }
        return self::$pdo;
    }
}

I would however suggest you guys consider using dependency injection rather than (or at least in conjunction with) singleton.  Taking a dependency injection approach allows you to remove code in classes that need a dependency (such as a PDO object) and enforce strict contracts in your code.

So rather than this sort of code:

class ClassThatNeedsPDO
{
    protected $pdo;

    public function __construct() {
        try {
            $this->pdo = PdoSingleton::getInstance();
        } catch (PDOException $e) {
            // do something
        }
        // do other stuff
    }
}

You take this approach:

class ClassThatNeedsPDO
{
    protected $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
        // do other stuff
    }
}

With you either passing PDO object defined in you bootstrap sequence upon instantiation, or possibly using singleton provider like this:

$obj = new ClassThatNeedsPdo(PdoSingleton::getInstance());

This makes it to where the class that needs that dependency can never even be instantiated if the appropriate dependency, which is type-hinted in parameter declaration, is not passed (an InvalidArgumentException would be thrown).   Your code fails loudly, which is what you want.

In class A, why require your config? It should be considered very unusual to have a require inside a class like this.  The require should be somewhere in your bootstrap sequence prior to where this singleton is first used.  Then you just use the constants as you are currently doing since constants are global in scope.

In class A, while I appreciate that you are trying to work with PDO in exception mode (a good thing) and using try-catch here around the instantiation.  Think about what impact this has on your code.

Here if PDO instantiation fails with exception, you basically just swallow it up with only some output to standard out to indicate there was a problem. Subsequent code could call this class, expecting an instance without knowing that the class was instantiated in a bad state.  You should be failing loudly here and letting the caller to the class make the decision on how to handle the situation.

I don't think that there is really a case here to even use try-catch, as I would think it reasonable that a PDOException bubble up from a PDO singleton class.  Maybe the only reason to use try-catch here is in case you wanted to log some information about the internal state of the class before re-throwing or wrapping the exception.  Either way, an exception should be thrown externally when you can't instantiate in an expected state.

A class such as this should never output anything by the way. It should log errors and/or throw exceptions, but not output directly to the user.  Leave this to code up the call stack that is better positioned to provide end-user messaging.

In class B, I don't understand global declarations throughout.  Using global is generally a PHP coding anti-pattern that should be removed from the code.  It seems as if the intent here is to access the class properties, which should be done using $this->*.

Class B looks like it wants to grow into a database wrapper, which to me is a bit of an anti-pattern unless that wrapper adds some specific value like:

managing connections (like using singleton or factory patterns)
abstracting user from specific database implementation details (PDO itself is already such an abstraction)
providing abstract ORM/model behaviors to be implemented in object-specific inheriting classes (it seems like you might be trying to achieve this in this class though I don't know why specific class/table logic like you have in updateStock() would be in a generalized database class)
providing natural language query-building functionality

My suggestion would be to abandon such an approach in favor of writing individual classes for your database entities such as artikelen, or better yet  using a proper PHP ORM.

Never hard code database or other security credentials into your code.  These should be derived from configuration that lies outside your code repository (ideally derived from environmental configuration).

You should change your DB password NOW as you just posted all your credentials for the whole world to see.

You have unreachable lines of code in updateStock(). When return is called, any lines of code after that call in that code path will never be reached.

You should never have unreachable lines in your code.

In class B, you should be using parametrized prepared statements vs. concatenating string values into your query strings.  You are totally open to SQL injection as you are doing nothing to sanitize your parameters for use in the queries.

The public methods in class B that accept arguments have no guarding code to validate those arguments.  You should, at a minimum make sure you have reasonable values (non-zero length strings, integer values, etc.) before getting to the point of making the (relatively) expensive query against the database.

Ideally you would throw InvalidArgumentException if parameters don't meet basic validation criteria.  This lets calling code know it did something wrong.

There is no reason to ever perform two queries in updateStock().  The first select is just a wasteful query against the database and it seems your code just assumes the record will exist anyway. You can go directly to trying the update (after validating and sanitizing input of course), setting the new values based on the old value.

That query might look like the following (of course you should parametrize this):

UPDATE `artikelen`
SET  `stock` = IF(`stock` > $amountToDecline, `stock` - $amountToDecline, 0)
WHERE  `artikelen`.`artnr` = $artnr

You can look at the number of affected rows to determine if the record was found or not (should should get 0 if nothing was done and 1 if an update was performed), alleviating the need to perform an upfront select at all.

It seems clear that you two are not working using a common coding standard or styleguide.  If you are going to collaborate, you should agree on this so that you don't end up with poorly written code that varies from script to script and class to class.  I would recommend looking at the PSR standards, particularly PSR-1 and PSR-2 as a starting point.

http://www.php-fig.org/psr/

You should enforce whatever style you decide upon using a style checker before committing code to your repository.

I would also suggest that you both familiarize yourself with http://www.phptherightway.com/ as a reference you can use to help guide your development.


Read my rewrite from the bottom up.  To appreciate the benefit, you notice how it clarifies the high level logic: your whole script is really only 4 lines long.

Some notes:

Isolate your begin... rescue code.  This way all servers will be processed even if there's an error
Break up each of your tasks into smaller, more focused methods (see below)
Make sure your names are accurate: eg, scanning_all_ssh_servers really means "ping a particular server"
Watch out for hidden entanglements in your code: your scan function takes a cmd argument, but this is a false abstraction, since the cody of the function assumes the cmd is a ping.  In this case, better to just leave the argument out.
breaking out the mailer into its own method will make the high level logic clearer
You can shorten up the ping function, while making it clearer imo, by losing the case statment (see below).  But if you don't like that, you should probably still use the regex version of case to avoid the repeated ping.include? calls.
Another small point on naming: Avoid unnecessary adjectives.  In this context, all your "servers" are "ssh servers", so better to use names like server_list rather than ssh_server_list, which adds visual and auditory cruft without adding precision.

Rewrite:

def mail_error(e)
  x = AD::Mail.new
  x.from     = "email@email.email"
  x.to       = "email@email.email"
  x.subject  = "Server Loading Error"
  x.body     = e.message
  x.send
end

def ping_server(server)
  begin
    check = Net::SSH.start(server, @username, :password => @password)
    cmd = "ping -c 1 #{server}"
    check.exec!(cmd)
  rescue => e
    mail_error(e)
    :error
  end
end

def server_status(server)
  ping_result =  ping_server(server)

  online_text = /1 received, 0% packet loss/
  offline_text = Regexp.union('0 received, +1 errors', 'Connection closed')

  ping_result =~ online_text  ? :online  :
  ping_result =~ offline_text ? :offline : :error
end

def status_message(server, status)
  status == :online  ? "server online: #{server}"  :
  status == :offline ? "SERVER OFFLINE: #{server}" :
                       "Error loading server: #{server}. Exiting.."
end

@username = "username"
@password = "password"
server_list = %w(these are all the servers that we can ssh too)

server_list.each do |server|
  status = server_status(server)
  puts status_message(server,status)
end

UPDATE: Additional Explanation

Regexp.union allows you to easily create an "or"ed regexp from a number of strings.  So that when you match strings against the regexp you created, you'll get a match if any of the strings match.  It's equivalent to the regexp | "or" operator, but can often be a more readable way to create the regexp.

Re: your question about the rescue block, it depends, but I would think you only want the "server can't be reached" email when the "reach server" code fails.  That is, even though this code is simple, it's still possible you get some other error executing it, which should be reported as a script error (using a library like airbrake) rather than spawning a "server can't be reached" email.  Again, just separating you concerns.

Re: the distinction between ssh and rdp servers, that makes sense.


Working with resources

Whenever possible,
anything that must be closed after using,
in this example the database connection,
it's good to wrap it in a with ... as, like this:

with sqlite3.connect(sqlite_file) as conn:
    cursor = conn.cursor()
    # ...

This way, conn will be automatically closed when exiting the block,
so it's impossible to forget to close it, therefore more robust.

Using enumerate

enumarate is really handy, but you're not using it to its full potential:

for i, e in enumerate(prod_list):
    prod_list[i] = prod_list[i].split('_')

Do you see the unused variable e? Since you have it, why not use it:

for index, item in enumerate(prod_list):
    prod_list[index] = item.split('_')

Naming

The posted code is filled with poor names, for example:

the main function
the c cursor variable -> cursor
the i loop variable for index -> index
the e loop variable for an element -> item

At the minimum, try to avoid single-letter names.

mm/dd/yyyy format

If at all possible, I'd recommend to use any other date format.

Comprehensive map of all countries in the world that use the MMDDYYYY format:


Picking a time based on when the app was last used

Whether you use ternaries or classic if/else you can often make your nesting easier to read by inverting your conditions. i.e.

! window.localStorage
    ? console.warn('Current browser doesn\'t support Local Storage API');
    : NotificationsStorage
    && NotificationsStorage.lastCheck
    && NotificationsStorage.lastCheck > today
        ? (
            this.lastCheck = NotificationsStorage.lastCheck,
            localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: now }))
        )
        : (
            localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: today })),
            this.lastCheck = today
        )

Although you can't do it with a ternary operator, I also usually prefer to use early returns to limit nesting. This also avoids the issue that you access localStorage in your first line even though it might not exist.

if (! window.localStorage) {
  console.warn('Current browser doesn\'t support Local Storage API');
  return;
}

const NotificationsStorage: { lastCheck: number } = JSON.parse(localStorage.getItem('NotificationsStorage'));
const today: number = moment().startOf('day').valueOf();
const now: number = moment().valueOf();

if (NotificationsStorage
    && NotificationsStorage.lastCheck
    && NotificationsStorage.lastCheck > today) {
      this.lastCheck = NotificationsStorage.lastCheck,
      localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: now }))
 } else {
      localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: today })),
      this.lastCheck = today
}

You could simply that last if by separating the variables and the logic to update them:

const {newStoredValue, newLocalValue} =
    NotificationsStorage
    && NotificationsStorage.lastCheck
    && NotificationsStorage.lastCheck > today
    ? [now, NotificationsStorage.lastCheck]
    : [today, today];

 localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: newStoredValue }));
 this.lastCheck = newLocalValue;


Transforming http request into linq query

Here's a stab at making it a tad more performant while simplifying the syntax a bit:

//case where an array of possible values is sent
private const string MyRegex = "\\[.*\\]";

private static readonly Regex replacer = new Regex(MyRegex, RegexOptions.Compiled);

public IList<Lead> GetLeads(NameValueCollection nvc)
{
    var queryBase = QueryBase();

    foreach (var key in nvc.Cast<string>().Where(key => nvc[key] != "all"))
    {
        // case where an array of possible values is sent
        Expression<Func<MyContext, bool>> predicate = c => false;

        foreach (var value in nvc[key].Split(','))
        {
            const string Format = "dd-MM-yyyy";
            Expression<Func<MyContext, bool>> predicateTemp;
            var localValue = value;

            switch (replacer.Replace(key, string.Empty))
            {
                case "nature":
                    predicateTemp = c => c.Typologies.NatureDemande == localValue;
                    break;
                case "departementCode":
                    predicateTemp = c => c.Geographies.DepartementCode == localValue;
                    break;
                case "start":
                    predicateTemp = c => c.Temps.Date >= DateTime.ParseExact(localValue, Format, null);
                    break;
                case "end":
                    predicateTemp = c => c.Temps.Date <= DateTime.ParseExact(localValue, Format, null);
                    break;
                default:
                    predicateTemp = c => true;
                    break;
            }

            predicate = this.OrElse(predicate, predicateTemp);
        }

        queryBase = queryBase.Where(predicate);
    }

    // query all leads
    return queryBase.Select(x => new Lead
    {
        id = Convert.ToInt32(x.Leads.DemandeWeb_FK),
        lng = Convert.ToDouble(x.Leads.longitudeClient.Replace(",", ".")),
        lat = Convert.ToDouble(x.Leads.latitudeClient.Replace(",", ".")),
        temps = Convert.ToInt32(x.Leads.GeolocDureeTrajetDistrib),
        distance = Convert.ToInt32(x.Leads.GeolocDistanceRouteDistrib),
        nature = x.Typologies.NatureDemande,
        type = x.Distributeurs.DistribType,
        reseau = x.Distributeurs.ReseauDistributeur,
        instance = x.Demands.IdInstance,
        distribution = Convert.ToInt32(x.Distributeurs.DistribIdPointDeVente),
    }).ToList();
}


public static bool DownloadImage(string url, bool isDirect) // returns if repost

C# supports something called XML Documentation Comments which allow you to document your code directly while writing it in a processor (as in IDE) friendly way.

public static bool DownloadImage(string url, bool isDirect) // returns if repost

Liar! This does not download the image but does checking on the URL, downloads the image, creates a MD5 sum for that image and then returns if it is already in the list of hashes.

You have one function that does everything, that's bad. Ideally you would split the responsibilities between multiple methods in one class, in some kind of such a structure (pseudo code):

class RepostChecker
    byte[] ComputeMD5(byte[] data)
    byte[] GetImage(string url)
    bool IsKnown(byte[] hash)

All of these methods can be static. So you can chain them like this:

IsKnown(ComputeMD5(GetImage(url)))

Or you can write a convenience method:

bool IsRepost(string url)

Which does the chaining for you. Then you define a class which does hold your hashes:

class Hashes
    static string HashToString(byte[] hash)

    void Add(string hash)
    bool Contains(string hash)
    void Load(whateverDatastoreYouUse)
    void Save(whateverDatastoreYouUse)

Internally this should use a HashSet<String>, not a normal List<String> like your implementation.

These changes would allow a more structured approach to the problem.

if (url.Contains('?'))
{
    url = url.Split('?')[0]; // if it has a query at the end like ?1
}
string filename = null;
if (url.Contains("imgur"))

You should use the Uri class if you work with URLs.

Uri uri = new Uri(url);           // http://imgur.com/blabla?whatever
uri.GetLeftPart(UriPartial.Path); // http://imgur.com/blabla
uri.Host;                         // imgur.com

Ideally you would not have one if {} else {} construct to handle this situation, but an interface which implementations and a static factory:

interface ImageHosterInteractor // Notice that the name is not optimal
    byte[] GetImage(string url)

From this interface you can now derive implementations for imgur and/or any other site. The static factory would look like this:

public static class ImageHosterInteractorFactory
{
    public static ImageHosterInteractor Create(Uri uri)
    {
        if (uri.PathAndQuery.EndsWith(".png")) // Or any other for that matter
        {
            // Implementation which simply loads the data from
            // the given Uri.
            return new ImageHosterInteractors.Plain();
        }

        // The uri does not end with an explicit ending,
        // so there's a good chance that we need to follow
        // redirections or perform some other magic.
        // So we use one of the explicit implementations.

        switch(uri.Host)
        {
            case "imgur.com":
                return new ImageHosterInteractors.Imgur();
                break;

            case "whatever.com":
                return new ImageHosterIntactors.Whatever();
                break;

            default:
                throw new NotImplementedException("There is no implementation assigned to handle: " + uri.Host);

        }
    }
}

That allows your code to simply process the URL, pass it into the factory and get something back that knows how to treat that site and you don't need to worry about it further down.

Uri uri = new Uri(fromwhatever);
ImagerHosterInteractor interactor = ImageHosterInteractorFactory.Create(uri);
byte[] image = interactor.GetImage(uri);

Also adding new sites to handle is as easy as implementing ImageHosterInteractor and adding it to the factory method.

At the moment it looks like you're saving the images you download, is that necessary or is it enough to simply save the hashes?


Finding the indices of the two items whose price adds up to to a value

Code organisation

Instead of building cases, then use it to build credits and items then use them to fix the problem, you could do things in a more straightforward way with less temporary containers.

with open(sys.argv[1]) as file_:
    next(file_)
    for i, case in enumerate(zip(*[file_]*3)):
        credit = int(case[0])
        prices = [int(item) for item in case[2].split()]
        for tow_items in combinations(prices, 2):
            if sum(tow_items) == credit:
                print("Case #{}:".format(i+1), end=' ')
                print(' '.join([str(i+1) for i, price in enumerate(prices) if price in tow_items]))

Also, it would probably make sense to split your code into multiple functions : you could write a function handling input/ouput and a function to handle the algorithmic part of the problem.

def get_indices_with_sum(prices, credit):
    for tow_items in combinations(prices, 2):
        if sum(tow_items) == credit:
            return [i for i, price in enumerate(prices) if price in tow_items]
    assert False  # Is not suppose to happen

def run_on_file(filename):
    with open(filename) as file_:
        next(file_)
        for i, case in enumerate(zip(*[file_]*3)):
            credit = int(case[0])
            prices = [int(item) for item in case[2].split()]
            j, k = get_indices_with_sum(prices, credit)
            print("Case #{}: {} {}".format(i+1, j+1, k+1))

run_on_file(sys.argv[1])

Now, different great things are easily doable :
 - you can your call to run_on_file behind an if __name__ == "__main__": guard to have reusable code on one hand (you could need the get_indices_with_sum function to solve other problems) and code actually doing something on the other hand.
 - you can write tests to check your code automatically. The great thing is that the problem description gives you a few examples.

def unit_tests():
    j, k = get_indices_with_sum([5, 75, 25], 100)
    assert (j, k) == (1, 2)
    j, k = get_indices_with_sum([150, 24, 79, 50, 88, 345, 3], 200)
    assert (j, k) == (0, 3)
    j, k = get_indices_with_sum([2, 1, 9, 4, 4, 56, 90, 3], 8)
    assert (j, k) == (3, 4)

if __name__ == "__main__":
    unit_tests()
    # run_on_file(sys.argv[1])

At this step, your code is already better but we haven't improved performance. We've only make improvements easier to write and to test.

Algorithm

In order to write a faster algorithm, I am assuming we are interested in the case when we are given a store with a huge number of elements n (called I in the problem description).

At the moment, you (potentially) iterate over all combinations and there are n * (n-1)/2. Assuming you always find what you are looking for, we may assume that you go through n * (n-1) / 4 combinations in average. Then, when the solution is found, your iterate once more over prices so you roughly perform n + n * (n-1) / 4 operations. We usually keep only the asymptotic behavior of the program and remove the constant factor and say that your program is 'O(n^2)'.

You could try to run your program with bigger and bigger inputs and see the time it takes. Usually when you take a input twice as big, your algorithm will take 4 times as much time.

If you want to give it a try, I've tweaked the original test to add the following cases (adding elements costing 101 in the store doesn't change what you can get with 100 dollars):

nb_added_elements = 10000
j, k = get_indices_with_sum([101] * nb_added_elements + [5, 75, 25], 100)
assert (j, k) == (nb_added_elements + 1, nb_added_elements + 2)
j, k = get_indices_with_sum([5, 75, 25] + [101] * nb_added_elements, 100)
assert (j, k) == (1, 2)

The problem you are trying to solve is pretty common and has a O(n) solution on a sorted array (you'll find explanations looking for "array find pair sum" in our favorite search engine).

Your case is slightly more complicated because the array is not sorted and sorting it would cause a mess in the indices.

Many solutions are possible : either build an array with value and index before sorting it by value and/or keep a copy of the unsorted array so that you can find its initial position back at the end.

The resulting solution is likely to be O(n*log(n)) because of the sorting (other operations such as lookup/copy and obviously the proper algorithm are only O(n) and as such considered negligeable).

Other details

count and enumerate can be given a starting position (defaulting to 0) so that you don't have to add 1 yourself if you want to count from 0.


Updated review

Peter Taylor noticed that I was solving for the wrong problem.  The problem calls for a sum of xor sums, not a single xor sum.  So I'm updating a review to talk about the actual problem (the old review is at the end, for reference).

Current solution is \$O(n)\$, is it enough?

The current solution with memoization runs in \$O(n)\$ time.  I was able to run with n = 200000000 (200 million) in under one second.  The question did not specify how many test cases there would be and how large \$n\$ could be for each testcase.  But since the OP said it wasn't fast enough, I'm going to assume that \$n\$ could be very large.  In that case, both time and space become a concern.

Can be solved in \$O(\log n)\$ time and space

Peter Taylor's answer outlined a solution where you solve for each of four bits (1,2,4,8) separately and then add up to a final total.  This solution requires \$O(\log n)\$ time due to its recursive nature, but does not use any extra space other than the \$O(\log n)\$ space needed to handle the recursion.

I got interested in how difficult it would be to implement this solution, so I did it.  I also tested versus the memoized version to make sure it worked.  Here is the result (quite long due to the number of comments):

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>

#define MAX_DIGITS        20

const uint8_t ones[]   = { 1, 3, 5, 7, 9 };
const uint8_t twos[]   = { 2, 3, 6, 7 };
const uint8_t fours[]  = { 4, 5, 6, 7 };
const uint8_t eights[] = { 8, 9 };

// Returns true if "digit" is in the given set of digits "digitSet".
// For example, 3 is in the set { 1, 3, 5, 7, 9 }.
static bool isInSet(int digit, const uint8_t *digitSet, int numDigitSet)
{
    int i = 0;

    for (i=0;i<numDigitSet;i++) {
        if (digitSet[i] == digit)
            return 1;
    }
    return 0;
}

// Returns (n choose k), which is the number of ways to choose k objects from
// a set of n objects.
static uint64_t combinations(int n, int k)
{
    int      i   = 0;
    uint64_t ret = 1;

    // nCk equals nC(n-k), so solve for the easier case.
    if (n-k < k)
        k = n-k;

    for (i=0;i<k;i++) {
        ret *= (n-i);
        ret /= (i+1);
    }
    return ret;
}

// Given every possible number of numDigits length, return the number of ways
// that you can make a number with an odd/even number of digits coming from
// a set of size numInSet.  For example:
//
// 5 digits
// 4 numbers in the set
// odd
//
// Let D be a digit in the set and x be a digit not in the set.
//
// Since we are considering only odd possibilities, we can make numbers with
// either 1 D, 3 Ds, or 5 Ds, like this:
//
// Dxxxx xDxxx xxDxx xxxDx xxxxD = 1 D  (5 choose 1 =  5 ways to place)
// DDDxx DDxDx DDxxD DxDDx etc.  = 3 Ds (5 choose 3 = 10 ways to place)
// DDDDD                         = 5 Ds (5 choose 5 =  1 way  to place)
//
// Within each of the ways above, such as Dxxxx, there are also many ways
// to build the digits.  There are numInSet digits (4 in the example) that
// can be put in each D slot, and (10 - numInSet) digits (6 in the example)
// ways to fill each x slot.  So for Dxxxx, there are 4*6*6*6*6 ways to create
// a matching number of that pattern.  For DDDxx, there are 4*4*4*6*6 ways.
// For DDDDD there are 4*4*4*4*4 ways.
//
// So the answer for the example above would be:
//
// 5*(4*6*6*6*6) + 10*(4*4*4*6*6) + 1*(4*4*4*4*4) = 49984 ways
//
static uint64_t computeCount(int numDigits, int numInSet, bool odd)
{
    int      i            = (odd ? 1 : 0);
    int      j            = 0;
    uint64_t ret          = 0;
    int      numNotInSet  = 10 - numInSet;
    uint64_t waysPerCombo = 1;

    // Special case for 0 digits.
    if (numDigits == 0)
        return odd ? 0 : 1;

    // Preinitialize waysPerCombo so we don't have to recompute the whole
    // thing every time through the next loop.  We will only need to adjust
    // it for 2 digits every loop iteration.  This is the 4*6*6*6*6 factor
    // from the example above.
    for (j=0;j<i;j++)
        waysPerCombo *= numInSet;
    for (j=i;j<numDigits;j++)
        waysPerCombo *= numNotInSet;

    // Loop through each possible way to make an odd/even number of digits
    // up to numDigits (such as 1, 3, 5 in the example above).  For each
    // number of digits, there are (numDigits choose i) possible ways to
    // make a Dxxxx pattern, and waysPerCombo ways of filling that pattern
    // with digits.
    for (; i <= numDigits; i += 2) {
        ret += combinations(numDigits, i) * waysPerCombo;
        waysPerCombo /= numNotInSet * numNotInSet;
        waysPerCombo *= numInSet * numInSet;
    }
    return ret;
}

// This function computes the "digit xor sum" for the specified number and
// "bit" (either 1, 2, 4, or 8).  This bit is specified by the digit set that
// is passed in.  The number is given as an array of digits, with the least
// significant digit in digits[0].  For example, the number 573 would be
// passed in as the array { 3, 7, 5 }.
//
// digits   : An array of digits for a given number, with the least significant
//            digit in digits[0].  For example, if the number was 573, then the
//            digit array would be { 3, 7, 5 }.
// numDigits: The length of the digits array.
// digitSet : The set of digits we are solving for (e.g. ones, twos).
// numDigitSet: The length of the digitSet array.
// odd:       True if we are looking for an odd number of occurrences of the
//            specified bit.  False if we are looking for an even number.
static uint64_t computeXorSumForBit(int *digits, int numDigits,
                const uint8_t *digitSet, int numDigitSet, bool odd)
{
    int      i            = 0;
    int      leadingDigit = digits[numDigits-1];
    uint64_t sum          = 0;
    bool     findOdd      = false;

    // Special case for 0 digits.
    if (numDigits == 0)
        return odd ? 0 : 1;

    // For each digit leading up to the leading digit, we can use all of the
    // other digits.  For example, given the number 521, we can use all of
    // 0xx 1xx 2xx 3xx 4xx, but we can't use all of 5xx, only up to 521.
    //
    // If the digit we use is part of the set, then we need to flip the odd
    // variable because we are using 1 of that digit already.
    for (i=0; i<leadingDigit; i++) {
        findOdd = odd ^ isInSet(i, digitSet, numDigitSet);
        sum += computeCount(numDigits - 1, numDigitSet, findOdd);
    }

    // For the leading digit (5 in the 521 example), we are limited by the
    // other digits.  We can recurse into this same function, and solve for
    // one fewer digit.  For example, with 521, we solve for 21, and flip
    // the odd variable if 5 is part of the set.
    findOdd = odd ^ isInSet(leadingDigit, digitSet, numDigitSet);
    sum += computeXorSumForBit(digits, numDigits-1, digitSet, numDigitSet,
                findOdd);

    return sum;
}

// Computes the sum of "xor of digits" for all numbers from 1..n.  The xor of
// digits is the xor of each digit (base 10) in a number.  For example, if the
// number was 521, the xor of digits is 5 ^ 2 ^ 1 = 6.
//
// The method used here is to solve for each of the four bits (1, 2, 4, 8)
// separately.  For a particular bit such as 1, we count how many numbers
// between 1 and n have an odd number of digits containing the 1 bit (i.e.
// an odd number of these digits: 1,3,5,7,9).  These numbers will have an
// xor of digits value with 0x1 set.  All other numbers will have an xor
// of digits value with 0x1 clear.
static uint64_t computeXorSum(uint64_t n)
{
    uint64_t sum       = 0;
    int      numDigits = 0;
    int      digits[MAX_DIGITS] = {0};

    while (n > 0) {
        digits[numDigits++] = n % 10;
        n /= 10;
    }

    sum +=   computeXorSumForBit(digits, numDigits, ones,  sizeof(ones), true);
    sum += 2*computeXorSumForBit(digits, numDigits, twos,  sizeof(twos), true);
    sum += 4*computeXorSumForBit(digits, numDigits, fours, sizeof(fours), true);
    sum += 8*computeXorSumForBit(digits, numDigits, eights,sizeof(eights),true);

    return sum;
}

int main(void)
{
    uint64_t sum      = 0;
    int      numTests = 0;

    scanf("%d", &numTests);
    while (numTests--) {
        uint64_t n;

        scanf("%lld", &n);
        sum += computeXorSum(n);
    }
    printf("%lld\n", sum);
    return 0;
}

Old review (solves a different problem)

I don't know about \$O(1)\$ but it seems doable in \$O(\log n)\$.  Given a number \$n\$, you can compute how many times each digit appears in each decimal place.  For example, given the number 1000, I can tell you the digit 1 appears 1 time in the thousands digit, 100 times in the hundreds digit, 100 times in the tens digit, and 100 times in the ones digit, for a total of 301 times.

If you xor a digit an even number of times, you get 0.  If you xor a digit an odd number of times, you get the digit.  So in my example, you xor the digit 1 an odd number of times (301 times) and get 1.  Then you solve for digits 2..9 and xor all the digit results together.

Now the question is, how did I compute the count of the digit 1 in each decimal place?  I suggest you start with the ones place (the rightmost digit) and think about why the answer for any digit is always N/10 or N/10 + 1.  Then think about the tens place and think about why the answer is always between N/10 - (digit-1) and N/10 + (10-digit).  Once you figure out the pattern, you should be able to write a function like this:

int GetCount(int n, int digit, int decimalPlace);

Then your main computation would look like:

int ComputeDigitXor(int n)
{
    int totalXor = 0;
    int maxDecimalPlace = ComputeMaxDecimalPlace(n);
    for (int digit = 1; digit <= 9; digit++) {
        int count = 0;
        for (int place = 0; place <= maxDecimalPlace; place++) {
            count += GetCount(n, digit, place);
        }
        if (count & 1)
            totalXor ^= digit;
    }
    return totalXor;
}

I'll leave it up to the reader to figure out how to write GetCount() given the hints above.


There are issues with your test function, don't return true, just return the result of the test you're doing or your function won't return anything if the test is false:

stockCheck = (stock, msg) ->
    console.log {msg}
    return !stock or stock is 'in stock'

Also, why {msg}? Shouldn't it be just console.log msg?

Your console.log tests are erronous too, your function is supposed to do the test not you when you call it, remove the ? from these lines:

console.log stockCheck(obj.one.stock) # true
console.log stockCheck(obj.two.stock) # true
console.log stockCheck(obj.three.stock) # false


Flagging system: Check for changing values in a data frame

I reduced the example data, for easier viewing

# new example data:
mydata <- data.frame(ta = 1:13)
mydata[2:3, 1] <- 1L
mydata[6:12, 1] <- 2L

n <- 3 # how many equal values we need

require(data.table)
setDT(mydata) # convert to data.table
mydata
mydata[, mathcPrev := fifelse((ta - shift(ta, 1)) == 0L, T, F, F)]
mydata[, g := cumsum(!mathcPrev)] # grouping value, if value has changed
mydata[, count := cumsum(mathcPrev), by = g]
mydata[, qc2 := fifelse(count >= n, 1L, 0L)]
mydata
#     ta mathcPrev g count qc2
#  1:  1     FALSE 1     0   0
#  2:  1      TRUE 1     1   0
#  3:  1      TRUE 1     2   0
#  4:  4     FALSE 2     0   0
#  5:  5     FALSE 3     0   0
#  6:  2     FALSE 4     0   0
#  7:  2      TRUE 4     1   0
#  8:  2      TRUE 4     2   0
#  9:  2      TRUE 4     3   1
# 10:  2      TRUE 4     4   1
# 11:  2      TRUE 4     5   1
# 12:  2      TRUE 4     6   1
# 13: 13     FALSE 5     0   0

So, the idea is to create index mathcPrev, that shows if this value matches previous, and then we can count how many equal values we have in a row.


According to PEP8, import re should come first
In free dictionary there is only one div having the class ds-single. You can simplify your code to search for this div
This doesn't apply to your program, but if you want to scrape multiple pages, it's better to use grequests.


Don't flip back and forth between string manipulation and arithmetic. When is a number 2 digits? When it's greater than 9. Yes, you can convert to a string, and check the string length, but why bother? Just convert everything to a number immediately and stick to it.
Don't bother with adding digits when a number is greater than 9; just subtract 9. The result is the same.
Don't use split("") when there's the String#chars method.
Don't chain off of #each_with_index, when you can use the Enumerator#with_index "modifier" on #map, i.e. .map.with_index { ... }
Don't do this i.odd? and x.to_i * 2 or x.to_i when you have ternary branching: [condition] ? [true branch] : [else branch]
A slightly more descriptive method name would help too. Right now it's hard to tell if the method calculates the check digits, or checks the credit card number. Something like #valid_credit_card_number? is an option. That it's a Luhn algorithm is an implementation detail; external code just want to know if it's valid or not.

That said there are many, many ways to implement the Luhn algorithm. A simple refactoring could be

def luhn(card_no)
  card_no
    .chars       # Break into individual digits
    .map(&:to_i) # map each character by calling #to_i on it
    .reverse     # Start from the end
    .map.with_index { |x, i| i.odd? ? x * 2 : x } # Double every other digit
    .map { |x| x > 9 ? x - 9 : x }  # If > 9, subtract 9 (same as adding the digits)
    .inject(0, :+) % 10 == 0        # Check if multiple of 10
end

A different approach could be:

def luhn(card_no)
  card_no
    .chars
    .reverse
    .each_slice(2)
    .inject(0) do |sum, (a, b)|
      double = b.to_i * 2
      sum + a.to_i + (double > 9 ? double - 9 : double)
    end % 10 == 0
end

Oh and remember to also check the length of the card number, and that it is, in fact, all-numeric.


There is no need using the 'this' keyword, or such as angularjs provides for those scenario. One thing you can do is to abstract the loadProducts functions and load prices function to a factory and then pass the factory as a parameter to your controller as shown below.

var priceQuoteApp = angular.module('priceQuoteApp', [])
    .constant("loadProductUrl", "scripts/json/sample-products.json")
    .constant("loadPricesUrl", 'scripts/json/sample-product-prices.json');

priceQuoteApp.factory("ProductsFactory", function ($http, loadProductUrl, loadPricesUrl) {
        return {
            loadProducts: function () {
                //Create an object to hold your result
                var result = {};

                $http.get(loadProductUrl)
                .then(function (allProducts) {
                    result.listOfProducts = allProducts.data.Connectivity;
                })
                    .finally(function () {
                        result.loadingProducts = false;
                        result.loadedProducts = true;
                    });
            },

            loadPrices: function () {
                $http.get(loadPricesUrl)
                    .then(function (res) {
                        result.selectedProductPrices = res.data.ProductVariants;
                      result.selectedProductAddOns = res.data.product_addons;
                    })
                    .finally(function () {
                        result.loadingPrices = false;
                        result.loadedPrices = true;
                    });
            }
        });

Then you inject the factory into your controller as shown below

priceQuoteApp.controller("quoteBuilderController", function ($scope, $http, $timeout, ProductsFactory) {
        var products = ProductsFactory.loadProducts();
        //Your other codes

        //When the user clicks the button
        $scope.clickAction = function () {
            var prices = ProductsFactory.loadPrices;
            //Then do other things with it.
        }
    });

One good thing is that this increases code return and thereby making every part of your code to focus on a single responsibility. Hope this helps.


perform fuzzy matching on a large set of dictionary keys

Take a look at BKTrees. Here is a less technical description. There is a Python library on PyPI: pybktree.
You create the BKTree once (once a day?) from the keys in the dictionary. Then run all the queries against the BKTree.
It would look something like this untested code:
import pybktree
from pyxdameraulevenshtein import damerau_levenshtein_distance

tree = pybktree.BKTree(damerau_levenshtein_distance, word_dict.keys())

all_matches = []

for target in set(name.split()):
    all_matches.extend(tree.find(target, MAX_DISTANCE))]

all_matches would be a list of (distance, word) tuples.


Splitting an Excel file into separate sheets by data

20,000+ is pretty close to 32,767, so first thing is to declare NearEnd As Long. Actually, you can declare all variables used as row numbers as Long, there is no gain on performance when you use Integer, and you are less prone to have overflow error.
Secondly, the issue with Worksheets("Group " & Groups).Range("A2:AE2").Offset(r, 0) line. As mentioned in comments above, it should be either continuation sing in line above "(space)_" or .pastespecial on the end.
And third, you could make code running faster just by replacing For-Next loop with the Object Loop. So, define range:

With Sheets("Sheet1")
    Set rng = Range(.Range(NearStart, "AB"), .Range(NearEnd, "AB"))
End With

and then

For Each cl in rng
(....)
Next cl

rng and cl declared as Range, of course.

If you have formulas and they don't need to be calculated while macro is running, I should turn of automatic calculation, together with screen flickering. You probably know this, just for the record:

With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationmanual
End With

and back to xlCalculationAutomatic on the end.


A small module that allows threads to return their result

What you are experiencing is a common problem that occurs with threads and lazy evaluation. What happens is that the thread creates only an unevaluated thunk, which is passed through RThread to the main thread, and evaluated only then, and the exception is thrown there. This is also a very good example why using exceptions in pure values is a bad idea (but of course if you're making a library like this you have to take this possibility into account).

The solution is to fully evaluate a value inside the try block, so that any exception that might occur is thrown there. For this we need a combination of two functions: evaluate and force. The former creates an IO action that forces the evaluation, the latter one performs deep evaluation (to a normal form, not just to a weak head normal form).

Also you might also want to separate the return value from the thread action. If you're not going to operate on thread actions, you can even omit them from the data type, as once you start an action, all you need is the MVar channel.

An updated solution could look like this:

import Control.Applicative
import Control.Concurrent
import Control.DeepSeq
import Control.Exception

newtype RValue a = RValue (MVar (Either SomeException a))

returnFork :: (NFData a) => IO a -> IO (RValue a)
returnFork act = do
    chan <- newEmptyMVar
    forkIO $ try (act >>= evaluate . force) >>= putMVar chan
    return $ RValue chan

waitForResult :: RValue a -> IO (Either SomeException a)
waitForResult (RValue chan) = takeMVar chan

main = returnFork (return $ Just (1 `div` 0 :: Int)) >>= waitForResult >>= print


Code quality has 3 priorities:

the code works as expected
the code is easy to read and does not surprise the reader
the code is (almost) free from duplications

Please read the following with this 3 priorities in mind.

Naming

Finding good names is the hardest part in software development so always take your time to improve the names of your identifiers.

Single letter names

Do not use single letter names or abbreviations. There are only few exceptions like loop variables or very common  abbreviations. While reading this code your brain has to do additional work to resolve single letters to their meaning.

Always use expressive names for your identifiers taken from the problem domain, not from the technical solution.

Naming Conventions

Please keep to the Java Naming Conventions. This will make the life of your coworkers easier as it does for you when your coworkers follow this suggestion.

eg.:
You have this method:

public static boolean Continue()

In Java only class names start with an uppercase letter. Also the method name (if correctly spelled) would collide with a reserved Java key word (which is no technical problem since java does distinguish between keywords and method names). This may confuse the reader.

Also since the method returns a boolean its name should start with is or has.

Names should express intention

Your method Continue() reveals another problem: it does not what its name implies.

What it really does is to ask the user what to do.
So its name should be ie.:  isUserRepeating()

Comments

Comments should always describe why the code is like it is.

Your comments somehow structure the code into individual sections.
You should better extract those individual sections to separate methods with names derived from the comments you wrote.

When doing so this will support a very important principle of object oriented programming: separation of concerns.

Visibility scopes

All your variables are declared at the top of your
main method or the top of your main loop.

You should reduce the visibility to the least possible block which means that you should declare them at first use. This will help to refactor your code later.

Code duplications

You have lots of duplicated code which does merrily the same but  the names of the variables differ.
eg.:

 //Placing the two integer numbers into array
 while(m > 0){
     g = m % 10;
     m = m / 10;
     num1[a] = g;
     temp[a] = g;
     a++;
 }
 while(n > 0){
     g = n % 10;
     n = n / 10;
     num2[b] = g;
     b++;
 }

The only difference is that the first loop additionally sets the values in the temp array.

So the better approach would be to fill the temp array in its own loop (for now, but there are even better approaches):

 //Placing the two integer numbers into array
 while(m > 0){
     g = m % 10;
     m = m / 10;
     num1[a] = g;
     a++;
 }
 a=0; // reset the currentDigitIndex
 while(m > 0){
     g = m % 10;
     m = m / 10;
     temp[a] = g;
     a++;
 }
 while(n > 0){
     g = n % 10;
     n = n / 10;
     num2[b] = g;
     b++;
 }

now you can create a method that does the loop:

private static int placeIntegerIntoArray(int numberToSplit, Integer[] individualDigits){
   int currentDigitIndex=0;
   while(numberToSplit > 0){
         int currentDigit = numberToSplit % 10;
         numberToSplit = numberToSplit / 10;
         individualDigits[currentDigitIndex] = currentDigit;
         currentDigitIndex++;
     }
     return currentDigitIndex;
}

and in your main you change to:

a = placeIntegerIntoArray(m, num1);
placeIntegerIntoArray(m, temp); // initialite to same as num1
b = placeIntegerIntoArray(n, num2);

BTW: this removes variable g from the scope of the main method.

Magic numbers.

Your code uses some literal numbers. You should extract them to constants so that you can give them meaningful names.

eg.: the literal number 10 in

 sum[i] = sum[i] % 10;

might be the SINGLE_DIGIT_MAX_VALUE

whereas in

 Integer[]  num1 = new Integer[10];

it might be the MAXIMUM_DIGIT_LENGTH


Python implementation of Netcat, new design

test.py

If you look at the definition of main(), you will see that it doesn't explicitly return anything.  By default, functions return None, so you will always be exiting with None.  Since it is always the same, it is useless even to use sys.exit().  The program will exit once the file has been read, so you don't need to tell Python to do that.  If you want to use exit codes, you'll need main() to return them.

main() doesn't use its arguments, so why give it any?  If sys.argv is ignored, take it out and remove the useless import of sys.

netcat.py

if s in r:
    if not cat_line(sf, outfile):
        break

The only time your program does something in the case of s in r is when not cat_line(sf, outfile).  Since you want to handle only the cases where both are true, use and:

if s in r and not cat_line(sf, outfile):
    break

Same with the next if block.  I wouldn't recommend it because it makes your lines too long, but you could put both if blocks in one:

if ((s in r) and not cat_line(sf, outfile)) or ((infile in r) and not cat_line(infile, sf):
    break

servers.py and cat.py look okay to me, but my opinion is that you don't need multiple files.  You don't have a bunch of lines that need to be split up, so you might as well put all of it in one file (not including test.py).


Inventories of iPods for different countries

Before looking at your design, a few trivial points that you can correct,

#include<iostream>
#include<string>
#include<cstdlib>

Avoid c style header usage. Instead use the c++ header style, and namespaces.
Instead of conio.h/getch() is not really portable. Avoid it.
Your setData method should really be the constructor. Using setData to populate the structure is a c habit. Also be sure to use the member initializers for construction.

You really want to keep the members private

class country {
  private:
    int name;
    int items,unit;
    float cost,price;

    bool try_purchase(std::string,int);

  public:
    country(int,int,float,float, int);
    void do_purchace(std::string a);
};
country::country(int name,int items,float cost,float price,int unit)
          :name(name),items(items),cost(cost),price(price){}

// false indicates that the purchase failed.
bool country::try_purchase(std::string a, int b) {
  if(b > items) return false;
  items = items - b;
  return true;
}
void country::do_purchace(std::string a) {
  int b;
  std::cout<<"enter the items needed: ";
  std::cin>>b;
  if (try_purchase(a,b))
    std::cout<<name<<":"<<items<<":"<<cost * b<<std::endl;
}
int main()
{
  country t[] = {country(0,100,100,0,0), country(1,100,50,400,20)};
  std::string a;
  std::cout<<"enter the country: ";
  std::cin>>a;
  int con = (a=="brazil") ? 0 : 1;
  t[con].do_purchace(a);
}

Avoid incorporating io statements with your logic. Refactor purchase so that logic is separated to another method.

Regarding your assertion that code changes have to be made if you change price, I do not see why. You can read the information to construct a country from a file and thus avoid hard coding it in the main file. However, this does not change the design as a whole.


Remove (not extract) timestamp from HTML string

You're right that it's ugly, I thought it didn't work at first until I realised how you're splitting to remove the first two whitespace separated strings. It's very unclear and very specific to these formats. If you're going to be format specific, then shouldn't you just use a regex?

r'^\d+:\d+\s+(am|pm|a\.m\.|p\.m\.)' will match the format in both the provided cases.

A brief breakdown is that it will match digits, then a colon, then digits again, then whitespace followed by either am, pm, a.m. or p.m.. You can make it case insensitive to avoid manually marking upper cases too. Also the ^ at the start means it will only work on strings that have this pattern at the beginning, so it wouldn't affect strings that happen to include similar formats as part of the text. I used this site for figuring out this regex and it's very helpful for stuff like this.

You can compile this regex simply with this:

import re

pattern = re.compile(ur'^\d+:\d+\s+(am|pm|a\.m\.|p\.m\.)', re.IGNORECASE)

Then just call it on your stripped soup text:

string1 = re.sub(pattern, "", soup1.text.strip())
print repr(string1)
string2 = re.sub(pattern, "", soup2.text.strip())
print repr(string2)


You defined a CENTER constant. Could you not do the same with SKY_BLUE, instead of the comment?

super().__init__(*SKY_BLUE)

def update_counter(self):
    self.text.element.text = str ( int(self.text.element.text)+1 )
    self.text.element.position = 320, 240

Using the text label as your data model is cumbersome. Keep an internal count instead of parsing the count back out of the UI.

Do you really need to re-center the label after each change? If so, explain why in a comment, and reuse a CENTER constant.

def on_mouse_press(self, x, y, buttons, modifiers):
    if x > 241 and x < 399 and y > 161 and y < 319 \
    and self.b_released and buttons & pyglet.window.mouse.LEFT:

Python supports double-ended inequalities like 241 < x < 399. I'm having a hard time understanding why the hot zone is defined with those particular bounds.  I'm guessing that you are hard-coding some coordinates that should be automatically determined.


To start with, I see what's likely to be a logic error. At the bottom, you do:

if (problem == null) {
    errors.push({
        msg: `Problem with id ${problem_id} does not exist `,
        param: "id"
    });
}
return monet.Validation.success(problem)

If the problem isn't found, you push an error object to the errors array, but then you return .success anyway and don't use the errors array again. In such a case, I think you want to call monet.Validation.fail with the error object instead, and not call .success.

Once that's done, note that you only ever have at most one element in the errors array, which .fail gets called with. It would be less repetitive to immediately call .fail and return when an error is encountered. Also, since the fail calls are all similar (monet.Validation.fail([{ msg: SOME_MESSAGE, param: 'id' }])), you can make the code DRY by putting that into a helper function:

const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);

Also, switch is almost never the right tool for the job IMO - it's quite verbose and can be error-prone when one forgets to break (which is surprisingly common). If the request type will be either post or get, use the conditional operator to figure out the property to look up on req instead:

const { id } = req[requestType === 'post' ? 'body' : 'query'];

I'd highly recommend against using loose equality ==. It requires an expectation that any reader of the code understands its strange rules. Better to use strict equality. Or, if the id or problem, if it exists, will be truthy (which sounds likely), it would look even nicer to use a truthy test:

if (!id) {
    return fail('Missing id of the problem');
}

If you actually need the logic you're implementing with == to check that the expressions aren't null and aren't undefined (but could be anything else, including other falsey values), then best to test both of those explicitly:

if (id === null || id === undefined) {
    return fail('Missing id of the problem');
}

I think it would also be useful to follow the standard Javascript naming conventions and use camelCase for variable names in most cases.

All together:

const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);
async function validateRequestArgs(req, requestType) {
    const { id } = req[requestType === 'post' ? 'body' : 'query'];
    if (!id) {
        return fail('Missing id of the problem');
    }
    const problem = await models.Problem.findByPk(id);
    if (!problem) {
        return fail(`Problem with id ${id} does not exist`);
    }
    return monet.Validation.success(problem);
}


Thanks for incorporating the various suggestions and posting a new code review.  This is looking really excellent.  Some nits and answers to your concerns:

creating a function for curling is good.  "$@" is the right choice as well.  But it would be nice if the stuff within squiggly brackets was indented like:

function _curl {
    curl --fail -u $USERNAME:$PASSWORD "$@"
}

I would stick with deleting the temporary file each time so the test is complete each time.  One scenario that might happen would be for the disk to fill up, and so no WebDAV writes are possible, but your test succeeds because it has the space of the existing file to work with or maybe there's code so it doesn't rewrite the file for performance reasons.  Either way leads to a false negative check which is best avoided.
It would be more thorough and nice to check the return value from the delete as well.  Doing this with a nested case statement could get unwieldy and certainly duplicates a lot of code.  If you can turn the case statement into its own function that could bucket the return values for creates or deletes that might be easier to maintain.  There might be other nagios checks where you want to check the output of curl similarly which would be good to keep in mind when designing this curl return evaluator.
Aren't you linking to the wrong prior question?  nagios plugin webdav check was how I got here.  :)


Shell script to create a boilerplate proyect

I'm not a shell expert, but I think I could help a bit. The most relevant tips I could give are:

1. Quote your expansions

Unquoted expansions are the most common source of bugs and security issues in shell scripts. There are cases where it's safe to leave expansions unquoted (as in foo=$bar) but, unless extremely necessary, it's preferable to double-quote every expansion you have.

2. Prefer $(command) over `command`

The $(command) syntax is POSIX-compliant and it can be easily nested.

3. Be consistent

You mix different styles in your code.

Quotes: There are both quoted and unquoted expansions. As I said before, prefer quoted expansions unless you are explicitly looking for side effects like word splitting.
Braces: When doing parameter expansions, sometimes you use braces, sometimes not. Braces are optional in most of the simple substitutions but they are useful when you have two-digit positional parameters or to avoid ambiguity. I personally prefer to always put my parameters within braces.
[ and [[: If portability is a concern, use [. If not, use [[.

4. Be careful with eval

Avoid it if you are not completely sure of what you are doing.

5. Arrays

I suppose you use the rest variable to save your remainder arguments. The problem is that you are saving them as a single string and you are relying on word splitting to handle it.

If your shell support arrays, this would be a safer and cleaner solution:

rest=( "${@:3}" )
...
mix phx.new "${name}" "${rest[@]}"

6. Shell builtins

If available, prefer them over external commands.

For example, if you use a recent version of bash and portability is not a big deal, you could rewrite uppercased_name=`sed -e "s/\b\(.\)/\u\1/g" <<< "${name}"`  as uppercased_name="${name^}"

7. Arguments parsing

First, I recommend you to read the Utility Conventions chapter of the POSIX specification. It's useful to understand how argument syntax works in standard utilities and serves as a guide to the rules you should follow when you create some program.

The goal is to make sure your script follows the program [options] [operands] syntax. I mean, instead of rely on the position of arguments to assign variables (as in name=${1}), your script should parse --name foo (or something similar) to change the value of the name variable.

There are basically two approaches:

Using utilities like getopts

Pros:

getopts is a POSIX builtin command.
It can handle things like -abc without effort.
Easy and intuitive.

Cons:

Can't handle long options.

Writing your own parser

Pros:

Full control of what and how it is parsed.
Handling of long options.
Could implement non-standard syntax.

Cons:

It's harder to handle things like -abc and edge cases.

Greg's and Bash Hackers' (1, 2) wikis have tutorials for both approaches, so check them out.

I've also written an example script to show how to do manual parsing and colored output:


Using QuickCheck to Verify Free Monad's Functor Instance

Use Eq1 to implement Eq, Show1 to implement Show

While it's a very recent addition, you should implement Eq via Eq1 and Show via Show1. That removes the UndecidableInstances pragma from your code:

import Data.Functor.Classes

data Free f a = Var a
               | Node (f (Free f a))

instance (Eq1 f) => Eq1 (Free f) where
  liftEq f (Var x)    (Var y)    = f x y
  liftEq f (Node fu1) (Node fu2) = liftEq (liftEq f) fu1 fu2
  liftEq _ _ _                   = False

instance (Eq1 f, Eq a) => Eq (Free f a) where
  (==) = eq1

instance Show1 f => Show1 (Free f) where
  liftShowsPrec sp sl = go
    where
      go d (Var a) = showsUnaryWith sp "Var" d a
      go d (Node fa) = showsUnaryWith (liftShowsPrec go (liftShowList sp sl)) "Node" d fa

instance (Show1 f, Show a) => Show (Free f a) where
  showsPrec = showsPrec1

We need to lift twice: once through the functor f, and once through the next Free.

QuickCheck

Your instance isn't very flexible. Furthermore, QuickCheck cannot set its size. Instead of a fixed size, use sized:

instance Arbitrary (Free Maybe Int) where
    arbitrary = sized go
      where
        go 0 = Var <$> arbitrary
        go n = Node <$> oneof [pure Nothing, Just <$> go (n - 1)]

However, that only yields a single instance. As with Show and Eq, there exists an Arbitrary1 class we can use instead:

instance Arbitrary1 f => Arbitrary1 (Free f) where
  liftArbitrary a = sized (go . min 3)
    where
      go 0 = Var <$> a
      go n = Node <$> liftArbitrary (go (n - 1))

instance (Arbitrary1 f, Arbitrary a) => Arbitrary (Free f a) where
  arbitrary = arbitrary1

We can now check the functor id law easily for many combinations.

The more rigorous approach

The more rigorous approach with functor laws is to proof them by hand. So let us assume that functor laws hold for the functor f in Free f a. Then we have to show that

fmap id value = value

for any value :: Free f a. There are two cases. Either value is a Var x for some x :: a. Then

fmap id value = fmap id (Var x) = Var (id x) = Var x = value

and the law holds. Or value is a Node y for some y :: f (Free f a). Then

fmap id value = fmap id (Node y)
              = Node (fmap id y)
              = Node (id y)      -- used functor law for `f'
              = Node y
              = value

Therefore, the first functor law holds for your instance.