Throttle implementation using pure JavaScript adding and removing event listener

Overall the code appears easy to read, and does what you say it does.

General comments:

The name of the throttle function is misspelled (trottle versus throttle). Not a show stopper, but does make it harder to read.
I see a number of ECMA script language features being used, but the old function() { ... } style is being used for the callback in setTimeout. Consider using the more concise "arrow function expression" (e.g. lambda expression) syntax instead:

setTimeout(() => element.addEventListener('mousemove', throttle), 2000);

Code reusability and variable scope

Two global variables are being declared, and really should not exist in the global scope. Consider using an Immediately Invoked Function Expression (IIFE) to hide them:

(() => {
    let area;
    let result;

    ...
})();

Or you can use a build tool like Grunt to automatically wrap this script in an IIFE.
Other events are just as "spammy" as the mousemove event. The "scroll" event is just as bad, and this could be useful for that as well. Consider parameterizing the event that is being throttled.
Same thing with the updateResult function. It could be parameterized as a callback function.
Parameterizing the frequency of the throttling would be easy, and a good idea as well.
The CSS selectors used to target the element whose events are being throttled is the last thing that needs to be parameterized in order to make this truly reusable.

Given this, a function signature like the following would probably allow you to fix all the issues, including leaking variables to the global scope:

function throttleEvent(element, eventName, frequency, callback) {
    ...
}

And would be used like this:

let area = document.querySelector("#move");
let result = document.querySelector('#result');
let updateResult = (event) => {
    result.textContent = `${event.clientX} , ${event.clientY}`;
};

throttleEvent(area, "mousemove", 2000, updateResult);


The algorithm looks good overall. Here are a few comments :

using namespace std; is sometimes frowned upon : some might say that putting it in a cpp file (by opposition to a header file) is ok, some might say that it's not. In any case, it is worth having a read at the link.

#define printprimes() //for each(bool b in primes) cout << b << endl;

does not seem really useful.

If you want to handle wrong input in a better way you could have a look at the other ways to convert arrays of char to number.

bool skipprint = false;

if(argc >=3) if(!strcmp(argv[2], "noprint")) skipprint = true;

can become :

bool skipprint = false;
if(argc >=3 && !strcmp(argv[2], "noprint")) skipprint = true;

which is nothing but :

bool skipprint = (argc >=3 && !strcmp(argv[2], "noprint"));

Also it might be even better to do :

bool print = (argc < 3 || strcmp(argv[2], "noprint"));

    if(!primes[l]) {
        //cout << l << " is false" << endl;
        continue;
    }
    for(unsigned long long cl = 2*l; cl < numt; cl+= l) {
        //cout << cl << ", a multiple of " << l << endl;
        primes[cl] = false;
    }

can be written :

    if(primes[l]) {
        for(unsigned long long cl = 2*l; cl < numt; cl+= l) {
            //cout << cl << ", a multiple of " << l << endl;
            primes[cl] = false;
        }
    }

In for(unsigned long long l = 0; l<=sqrtt; l++), you can start from index 2. Please note that if you forget to initialise prime[0] to false, you'll get stuck in an infinite loop.

In for(unsigned long long cl = 2*l; cl < numt; cl+= l), you can start at index l*l because any i*l with i < l should have been crossed out already.

if(!skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
    cout << l << endl;
    count ++;
}
if(skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) count ++;

could be rewritten in many different ways. Most obvious one is to use an else :

if (skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) count ++;
else for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
    cout << l << endl;
    count ++;
}

A probably better option in order not to repeat code is to do :

for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
    if (!skipprint)
        cout << l << endl;
    count ++;
}

Also, you should probably write your algorithm in a function on its own. Other optimisation can be analysed like removing all even numbers from the beginning to use a smaller container.


I have never used Elixir in my life until seeing this question, so my feedback is very limited and I probably shouldn't be putting an answer on here. However, there are a few ways it could be simplified:

the module lstat(path, opts \\ []) reads information about a path, returns a FileStat struct which has a type: field which can be type: :device | :directory | :regular | :other | :symlink; this could be used to determine what the path is (and whether to use -r), and if there is an error it means that the path does not exist (thus adding in the error handling)
in the case {resp, exit_code} -> instead of checking the error message contents via String.contains?, do the switching based on exit code and then return the appropriate error messages.
in the case {resp, exit_code} ->, I'd add a few extra error-handlers for statuses (for example directory not found on destination, invalid credentials, etc.)
for the inputs (user and ip address), a regex could be used to ensure sanity (the ip address looks like an ip, the username is not blank, etc.)
the case true -> {:error, :errunkown, exit_code} could be replaced with _ -> {:error, :errunkown, exit_code} as _ appears to be a fall through (I'm unsure about this)


First you should add open(pp) to your with.
Always use with with open.
This is as it will always close the file, even if there is an error.

But onto your code. You seem to dislike comprehensions. I don't really get why.
Take your code:

for line in ppf.readlines():
    if not line.startswith("#"):
        temp.append(line)

This can instead be:

[line for line in ppf if not line.startswith("#")]

I know which I find easier to read. But if you don't like it fair dues.
After this I'd then slice the list, you want every third line.
To do this we can use the slice operator, say you have the string abcdefghijk, but you only want every third character.
You'd do 'abcdefghijk'[::3]. This gets adgj.
This removes the need for counter, and so can simplify your code to:

for pp in pp_files:
    with open(pp) as ppf, open(pp[:pp.rfind(".post")] + "_clean.post", "w") as outfile:
        for line in [line for line in ppf if not line.startswith("#")][::3]:
            outfile.write(" ".join(line.split()[1:3]) + '\n')

But if your file is large it'll read all of it into a list, then take a third of it put it in another list.
That's bad, instead if you use a generator comprehension and itertools.islice then you can achieve the same as above.
But the program will use less memory.

for pp in pp_files:
    with open(pp) as ppf, open(pp[:pp.rfind(".post")] + "_clean.post", "w") as outfile:
        for line in islice((line for line in ppf if not line.startswith("#")), 0, None, 3):
            outfile.write(" ".join(line.split()[1:3]) + '\n')


Creating number pattern (triangle numbers) in C++ with minimum loops

Spacing

Use as much whitespace as needed, it makes it easier to read code, especially formulas or expressions with a lot of operators.

using namespace std;

This is discouraged, I don't think it makes much difference in a program of this size, but it can be a bad habit to rely on.

int n=0, r=0, i=0;

Try and only declare variables in the smallest scope possible, as in right when you need them. Since n and i are only ever used inside the loops, only declare them there.

I would avoid assigning 0 to r, as then if later the program crashes, and I see r no value, it makes the bug much easier to spot than if r has a valid value.

for( n=1; n<=r; n++) {
    for( i=1; i<=r-n; i++) {
        cout << "  ";
    }

This is completely up to you, but I would start the loops at 0, and go until n < r or i < r-n. That is because I would consider that a standard loop, and it is very quick to see how many times it loops, what stopping condition is, and what it loops over. I understand why you are starting from 1, the number of rows, but since this is never actually used, an off by one error wouldn't actually be noticeable. It is barely worth thinking about, but if you are writing for loops over and over, it makes it easier to read. Take this with a grain of salt.

for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {

As we are printing out the natural numbers, starting from 1, and going to r*(r+1)/2, I would just have a variable that keeps counting upwards. Then I don't have to work out what number the row starts with each time, and you are incrementing i anyway, so there is essentially no extra work done by having a count, and you save a few operations too.

    if( i<10 )
        cout << " " << i << "  ";
    else
        cout << i << "  ";
}

This is exactly what padding was made for. I don't really know how to pad with cout, but printf makes it very easy. It looks like:

printf("%*d in the bed, and the little one said %s", the_amount_of_spaces, the_number_to_print, "a_piece_of_inpsiring_text");

Where everything inside the quotes is what to print, % means the next piece is a variable, %d means an int, %s means a string

There are some other things you can do, like if you never want to change the number of spaces, you can hardcode it like:
    printf("%3d ", count);

Here is a reference for it

Below are all the changes I would make thrown together, if you have any questions, ask away

#include <iostream>
#include <stdio.h>

int main() {
    int r;
    std::cout << "No. of rows: ";
    std::cin >> r;

    int count = 1;
    for(int n = 1; n <= r; n++) {
        for(int i = 0; i < r - n; i++) {
            std::cout << "  ";
        }

        while(count <= (n*(n + 1)/2)) {
            printf("%3d ", count);
            count++;
        }
        std::cout << "\n";
    }
    return 0;
}

The padding works well up until 45 rows are entered, after that, it was too wide for my screen to properly read.


First of all, the `cmd` form of running commands and capturing their output is deprecated. Use the recommended, modern way everywhere: $(cmd)

Safety

Be careful with spaces in filenames. These commands will break:

message=`cat $1`
shorten=`sed -ne 's/.*\(http[^"]*\).*/\1/p' $1`

It will be safer like this:

message=$(cat "$1")
shorten=$(sed -ne 's/.*\(http[^"]*\).*/\1/p' "$1")

The pattern there in the sed is not very safe. The text "add support for http protocol" will match. I think you want to be more strict, maybe something like:

longUrl=$(sed -ne 's/.*\(https\{0,1\}:\/\/[^"]*\).*/\1/p' "$1")

Note: if you have GNU sed (you're in Linux, or have gsed), then instead of the tedious https\{0,1\} you can simplify as https\?, though it's less portable.

And what if there are multiple URLs in the script? It will fail. You probably want to loop over the results of the sed. Or take a lazier approach and just ensure that sed will always produce at most one line:

longUrl=$(sed -ne 's/.*\(https\{0,1\}:\/\/[^"]*\).*/\1/p' "$1" | head -n 1)

What if there are no matches? An if would be good, as in that case you won't need the curl call, and it's better to not overwrite a file if you don't really have to.

When you echo $somevar, whitespaces inside like tabs and newlines would be replaced by spaces. To prevent that, quote the variable:

echo "$message" > "$1"

Naming

Your variable names are not so good:

shorten is the output of sed, a long url. Something like longUrl would have been better.
newUrl is the output of curl, a json text. Something like json would have been better.

Unnecessary things

In the curl command, you don't need the backslashes in \-H and \-d flags.

And instead of saving the output of the curl and then echo-ing to python, it would be better to skip that intermediary variable and just pipe it directly, like this:

shortUrl=$(curl -s https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -d "{'longUrl': '$longUrl'}" | python -c 'import json, sys; print(json.load(sys.stdin)["id"])')

Also notice in that python that I skipped the intermediary obj variable and just used the ["id"] directly on json.load(...).

Suggested implementation

#! /bin/bash
message=$(cat "$1")
longUrl=$(sed -ne 's/.*\(https\{0,1\}:\/\/[^"]*\).*/\1/p' "$1" | head -n 1)
if test "$longUrl"; then
    echo "Shortening Url $longUrl ..."
    shortUrl=$(curl -s https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -d "{'longUrl': '$longUrl'}" | python -c 'import json, sys; print(json.load(sys.stdin)["id"])')
    message=${message/$longUrl/$shortUrl}
    echo "$message" > "$1"
fi

This is still not perfect, because it doesn't handle multiple urls. I might add that later, gotta go now.

Online shell checker

This site is pretty awesome: http://www.shellcheck.net/#

Copy-paste your script in there, and it can spot many mistakes that are easy fix.


You must not modify the keys of a HashMap while iterating over it. You are just lucky it worked.

Instead of the put(...), write e.setValue(e.getValue() + 1).

If you have some kind of Multiset available (e.g. when you are using Guava), you could replace your HashMap with a Multiset<String>, which will make your intention clearer.

Using lambdas, your code would look like:

map.replaceAll((k, v) -> v + 1);

This looks very nice to me. It cannot get any shorter.


Grouping work hours for consecutive days

magic numbers

In

rows = [row.split(" ", 1) for row in data.splitlines()[1:-2]]

the 1 & -2 magic numbers are a bit of a wart. Perhaps you'd like to create a generator that knows to suppress 'Hours' and that won't yield any further lines after 'Holiday Hours'.

Also,

first_day, last_day = days_in_group[0][:3], days_in_group[-1][:3]

has some magic numbers, but arguably they make more sense. You could make your generator responsible for day parsing, with yield day[:3], time_range.

variable renaming

In your string formatting, you choose to rename first_day to begin, and range_end to end. I suppose my advice is "don't do that". Or if there's a name you prefer for those variables, use that consistently throughout.

In

days_in_group = [item[0] for item in group]

the identifier item is a bit vague. pair would be better (or perhaps day_range if you lean toward the verbose).

global scope

You polluted the top-level namespace with rows and other identifiers. Your file cannot be reused via import. Please use the

if __name__ == '__main__':

idiom to bury these lines of code under def main(): or similar.

Overall, yes, this is sensible code, put together in pythonic fashion.


Edge cases are where such class hierarchies often fall short.

An offhand short sword that adds to defense?
A shield that does damage when you bash with it?
A magic potion that not only makes you less hungry but also adds
armor when you drink it?

How will those fit into your current hierarchy? One way to avoid those problems is to use aggregation instead of inheritance and treat each game object as a collection of arbitrary properties, that can be added to object or removed from it. You might want to look at how, for example, things are done in Unity, to get a better understanding of how things are actually designed in modern engines.

To be clear, there is nothing wrong with having game object hierarchies in small projects. It is the easiest approach and sometimes it is enough, especially if all you want is to write some code. I just wanted to give you some perspective.

EDIT
Since this question is getting a lot of attention I though I might as well update my answer with a simplified example.

First, you have to create some "components". For the sake of this example, you can think of components as properties that define the item and make it different and special. What is a fire sword? It is an item that:

people in the village call "Lightbringer"
requires some "sword" skill to use
looks like a big burning knife
can do slicing damage to things
but does fire damage too
it weights 8 kg
it costs 1000g and can be bought or sold
etc...

Those are the aspects of a fire sword that make it what it is. And every one of those aspects can be defined as separate component.

abstract class ItemComponent
{
    //What goes into base class entirely depends
    //on how your game engine is implemented.
    //I left it out because it is irrelevant
    //in context of this example
}

class Valuable : ItemComponent
{
    public int Cost { get; set; }

    public override string ToString()
    {
        return "It is a valuable item, that can be bought for " + Cost + "g.";
    }
}

class PhysicalDamage : ItemComponent
{
    public int Slashing { get; set; }
    public int Bashing { get; set; }
    public int Piercing { get; set; }

    public override string ToString()
    {
        return String.Format("It does {0}/{1}/{2} physical damage.", Slashing, Bashing, Piercing);
    }
}

class ElementalDamage : ItemComponent
{
    public int Fire { get; set; }
    public int Water { get; set; }
    public int Earth { get; set; }
    public int Wind { get; set; }

    public override string ToString()
    {
        return String.Format("It does {0}/{1}/{2}/{3} elemental damage.", Fire, Water, Earth, Wind);
    }
}

//etc...

And this is a typical game object that theoretically can represent anything from a stone on the ground to a bullet. It's just a collection of arbitrary components.

class Item
{
    public Item(string name)
    {
        Name = name;
    }
    //Name can be a component too!
    public string Name { get; private set; }

    public Item AddComponent(ItemComponent component)
    {
        _components.Add(component);
        return this;
    }

    public T GetComponent<T>()
    {
        return (T)_components.OfType<T>().FristOrDefault();
    }

    public override string ToString()
    {
        var sb = new StringBuilder();
        sb.AppendLine(Name);
        _components.ForEach(c => sb.AppendLine(c.ToString()));
        return sb.ToString();
    }

    private List<ItemComponent> _components = new List<ItemComponent>();
}

Then to create a fire sword all you need to do is create an item with all the necessary aspects:

var fireSword = new Item("Lightbringer")
                   .AddComponent(new Valuable { Cost = 1000 })
                   .AddComponent(new PhysicalDamage { Slashing = 10 })
                   .AddComponent(new ElementalDamage { Fire = 10 })
//Maybe it also makes you weak to water attacks?
//No problem, just define and add new component
                   .AddComponent(new ElementalResistance { Water = -10 };
Console.WriteLine(fireSword.ToString())

This allows you to do all sorts of neat stuff later on. For example, to calculate total resistances of a player, you can call GetComponent<ElementalResistance>() for every equipped item and sum the result.


Mapping ExpandoObject to another object type

I've come up with a few changes that should actually speed it up.

// By using a generic class we can take advantage
// of the fact that .NET will create a new generic type
// for each type T. This allows us to avoid creating
// a dictionary of Dictionary<string, PropertyInfo>
// for each type T. We also avoid the need for the
// lock statement with every call to Map.
public static class Mapper<T>
    // We can only use reference types
    where T : class
{
    private static readonly Dictionary<string, PropertyInfo> _propertyMap;

    static Mapper()
    {
        // At this point we can convert each
        // property name to lower case so we avoid
        // creating a new string more than once.
        _propertyMap =
            typeof(T)
            .GetProperties()
            .ToDictionary(
                p => p.Name.ToLower(),
                p => p
            );
    }

    public static void Map(ExpandoObject source, T destination)
    {
        // Might as well take care of null references early.
        if (source == null)
            throw new ArgumentNullException("source");
        if (destination == null)
            throw new ArgumentNullException("destination");

        // By iterating the KeyValuePair<string, object> of
        // source we can avoid manually searching the keys of
        // source as we see in your original code.
        foreach (var kv in source)
        {
            PropertyInfo p;
            if (_propertyMap.TryGetValue(kv.Key.ToLower(), out p))
            {
                var propType = p.PropertyType;
                if (kv.Value == null)
                {
                    if (!propType.IsByRef && propType.Name != "Nullable`1")
                    {
                        // Throw if type is a value type
                        // but not Nullable<>
                        throw new ArgumentException("not nullable");
                    }
                }
                else if (kv.Value.GetType() != propType)
                {
                    // You could make this a bit less strict
                    // but I don't recommend it.
                    throw new ArgumentException("type mismatch");
                }
                p.SetValue(destination, kv.Value, null);
            }
        }
    }
}


Let's start with the basics:

$_SESSION: This is a global array that holds all your session information.
$_REQUEST: This is a global array that contains the contents of $_GET, $_POST and $_COOKIE. Read more on PHP's superglobals.

if( empty($search) ) {

    $_SESSION['keyword_exists'] = "no";

} else {

    if( isset($_SESSION['old_keyword']) && $_SESSION['old_keyword'] != $search ) {
        $_SESSION['keyword_exists'] = "no";
    }

}

The outer if depends on whether the $search variable is empty or not. Empty in context could mean:

  "" (an empty string)
  0 (0 as an integer)
  0.0 (0 as a float)
  "0" (0 as a string)
  NULL
  FALSE
  array() (an empty array)
  var $var; (a variable declared, but without a value in a class)

If $search is empty, $_SESSION['keyword_exists'] is set to "no" (can't read the author's mind, but my choice would be false, not a string). From the naming we can assume that $search holds (or not) the keyword(s) of a search. Now if that is not empty:

    if( isset($_SESSION['old_keyword']) && $_SESSION['old_keyword'] != $search ) {
        $_SESSION['keyword_exists'] = "no";
    }

The first clause, isset($_SESSION['old_keyword']) essentially checks if there's an "old_keyword" index in the $_SESSION array (and whether it's null or not), that's a pretty typical check for arrays. The second check, that executes if and only if the first one passes, checks whether what's in $_SESSION['old_keyword'] is not the same as what's in $search. I'm assuming that the author had some reason for that, but can't imagine what that reason is.

Summarizing what happens here, if:

$search is empty, or
$search is not the same as $_SESSION['old_keyword']

...then $_SESSION['keyword_exists'] = "no". A perhaps simpler way to write that would be:

if(
    empty($search)
    || ( isset($_SESSION['old_keyword']) && $_SESSION['old_keyword'] != $search )
) {
    $_SESSION['keyword_exists'] = "no";
}

Moving on to the next part:

if( isset($_REQUEST['limitstart']) && $_REQUEST['limitstart'] > 0 ) {

    ...

} else {
        $limitstart = "0";
}

The clause is very similar to the one discussed previously, only this time other than checking if $_REQUEST has a "limitstart" index, the author also checks that the value is larger than zero. That's an unsafe check, because at this point we don't now what the type of the value in $_REQUEST['limitstart'] is, and if it's anything other than a number, there will be automatic type juggling involved, and the check is completely unreliable.

From the name and context, I'm assuming the variable should hold an integer (if anything) that limits the search. If the variable doesn't hold anything, the limit is set to zero ($limitstart = "0"), curiously using a string form of zero. I'd rewrite that check as:

$limitstart = 0;

if(
    isset($_REQUEST['limitstart'])
    && ( is_int($_REQUEST['limitstart']) || ctype_digit($_REQUEST['limitstart']) )
    && $_REQUEST['limitstart'] > 0
) {

    ...

}

is_int() checks whether the value is an integer and ctype_digit() whether it's a string that only contains digits (thus a integer in string form), any of the two is acceptable for the following check, $_REQUEST['limitstart'] > 0. I've also moved $limitstart = 0; out of the check, I'm initializing it to zero and will override if and only if there's a need. But let's see what happens if the check is true:

    if ( !empty($search) ) {
        if( isset($_SESSION['keyword_exists']) && $_SESSION['keyword_exists'] === "yes" ) {
            //intentionally left blank?
        } else {
            $limitstart = "0";
            $_SESSION['keyword_exists'] = "yes";
            $_SESSION['old_keyword'] = $search;
        }
    }

This is obviously incomplete. The outer check is simple enough, it's whether $search is empty or not. If it's empty, nothing happens, if it's not, the inner check is on whether _SESSION has a "keyword_exists" index, and if it's value is "yes". If that's true, something happens, but who knows what? I'm assuming one of the things that would happen would be to set a proper value to $limitstart. Anyways, if the check is false:

$limitstart remains zero,
$_SESSION['keyword_exists'] for some reason becomes "yes", and
$_SESSION['old_keyword'] becomes $search.

Unfortunately, I have no idea why. Anyways, my full rewrite would be:

if(
    empty($search)
    || ( isset($_SESSION['old_keyword']) && $_SESSION['old_keyword'] != $search )
) {
    $_SESSION['keyword_exists'] = "no";
}

$limitstart = 0;

if(
    isset($_REQUEST['limitstart'])
    && ( is_int($_REQUEST['limitstart']) || ctype_digit($_REQUEST['limitstart']) )
    && $_REQUEST['limitstart'] > 0
) {

    if ( !empty($search) ) {
        if( isset($_SESSION['keyword_exists']) && $_SESSION['keyword_exists'] === "yes" ) {
            //intentionally left blank?
        } else {
            $_SESSION['keyword_exists'] = "yes";
            $_SESSION['old_keyword'] = $search;
        }
    }

}

The code is equivalent, and will work (?) if you replace it in your script. Hope it clarifies things a bit. The overall quality of the code is bad, there are some hints of an amateur developer there, and you shouldn't really worry that you didn't grasp what the code does, since you are unfamiliar with the language. It's an incomplete and mostly poorly written piece of code, good luck with it ;)


Allowing "plugin" programmers to subscribe to messages

Allow throwing exceptions

Do you really think your user is capable of handling all the exceptions?

interface IMessageListener {
   void onMessage(Message m) throws Exception;
}

Of course if some plugin wants to handle the exception, nothing prevents he/she of using try/catch. But no one is forced to do so and if, according to your knowledge, the catch block is almost always the same, put it outside in the code calling onMessage().

Give your user a simplified adapter

abstract class ThrowingMessageListenerAdapter implements IMessageListener {

    @Override
    public void onMessage(Message m) {
        try {
            doOnMessage(m);
        } catch (SQLException e) {
            // if an exception happens, log it, and reply to the message
            log.error(A_UNIQUE_ERROR_CODE, e);
            m.reply(false);
        }
    }

    protected abstract void doOnMessage(Message m) throws Exception;

}


Your code nicely exploits all the constraints from the instructions.

It runs in linear time, which is much better than the naive approach, which would run in quadratic time.

It doesn't need any space other than a few local variables. Perfect.

Without further explanation the code is a bit hard to follow because of the many variables, and it is not entirely clear what sum and diff are exactly. Sure, sum holds a sum, but of what?

The diff variable should move inside the for loop since it is only needed there.

Instead of tank + diff < 0, you could also write tank < diff, but since you later compute tank + diff, having this common subexpression in the code is actually useful. You could also combine the expressions: just execute tank += diff, and if there's a negative amount of gas in the tank after that, reset it to zero. It's impossible in the real world to have negative amounts of gas in the tank, but it would make the code shorter.

For understanding the algorithm I would have preferred a variant that has two for loops. In the first loop, just compute the sum. In the second loop, determine the starting index. That way, there's fewer variables who can confuse me, the human reader. But if you're going for execution speed, you approach is perfect, again.

I would have preferred a short introduction about how you constructed your algorithm. Learning the ideas and then going from ideas to code is often easier than going backwards from the code to the underlying ideas.


Because HashAlgorithm implements IDisposable you should enclose the usage of it in an using block as well.
Omitting braces {} although they might be optional can lead to hidden and therfor hard to find bugs. I would like to encourage you to always use braces.
Instead of using a for loop to copy plainText to saltedText and salt to saltedText you may take advantage of the Array.CopyTo() method.
Public methods should validate passed parameters.
Because you don't return the salt you can only generate a hash but you can't verify the hash.

Applying the mentioned points can lead to

public static byte[] GenerateSaltedHash(byte[] plainText)
{
    if (plainText == null) { throw new ArgumentNullException("plainText"); }
    if (plainText.Length == 0) { throw new ArgumentException("Length may not be zero", "plainText"); }

    using (HashAlgorithm algorithm = new SHA256Managed())
    {
        byte[] salt = GenerateSalt();
        byte[] saltedText = new byte[plainText.Length + salt.Length];

        plainText.CopyTo(saltedText, 0);
        salt.CopyTo(saltedText, plainText.Length);

        return algorithm.ComputeHash(saltedText);
    }
}

private static byte[] GenerateSalt()
{
    using (RandomNumberGenerator random = new RNGCryptoServiceProvider())
    {
        byte[] salt = new byte[MaxSaltLength];
        random.GetNonZeroBytes(salt);
        return salt;
    }
}


Single-thread worker in multi-thread webservice

Basically, you have the right idea: producer-consumer is probably the pattern you need.

The way you implemented it is the problem, because so many things have gone wrong...

Queue is not thread-safe, so access to it has to be synchronized, otherwise at best you gonna be losing tasks at worst it will straight up crash your software.
I don't see a single good reason why your ApiManager should be static. Having a mutable static dependency in code is already bad enough, having a static dependency that you also have to synchronize - is straight up awful.
Your thread is never terminated and it will keep running even if you close your application.
You have racing conditions all over the place. For example, if you have only two tasks, and the second one is added to queue after the first one is in completed but before wakeUp.Reset() is called in your loop, the second task will never be executed.
You create IDisposable objects that you never dispose (I'm talking about wait handles).

Bottom line is: it's hard to fully understand thread-safety and it's even harder to write correct thread-safe code in complex multi-threaded environment. It is not something you can just jump into. You should definitely do some reading on how multi-threading is done in C# before attempting to implement it in your production code. Reading lock keyword documentation is a good place to start.


Getting validation from inherited classes

Here's a C# version using a cross of the template method pattern and the collector pattern.
It'll pick up any issues from any derivative implementing the AddValidationIssues method.

public abstract class BaseClass
{
    public List<string> GetValidationIssues()
    {
        var result = new List<String>();
        if (Quantity < 0) result.Add("Quantity is invalid");
        AddValidationIssues(result);
        return result;
    }

    protected virtual void AddValidationIssues(List<string> result)
    {
    }
}

public class ProductBase : BaseClass
{
    protected override void AddValidationIssues(List<string> result)
    {
        if (string.IsNullOrWhiteSpace(Name)) result.Add("Name not specified");
    }
}

As a sidenote, I'd look for another name than "BaseClass". It doesn't say anything about what it does.


Counting subnumbers divisible by a given prime

Let \$N_{i,j}\$ be the subnumber of \$N\$ from the \$i\$th digit (excluded) to the \$j\$th digit (included). Here, the first digit is the least significant one.
Let  \$R_i = N \bmod 10^i \$. We have \$R_j-R_i=N_{i,j} * 10^i, 0\leq i < j \leq D(N)\$, where \$D(N)\$ is the number of digits in \$N\$. There are two cases.

If \$p \nmid 10\$, then
$$p \mid N_{i,j} \Leftrightarrow p\mid N_{i,j} * 10^i \Leftrightarrow p\mid R_j-R_i \Leftrightarrow R_j \equiv R_i \pmod{p}$$

In this case, we can compute \$R_i\bmod p\$ for all \$i=0,\ldots,D(N)\$, group them by values, count the number of pairs in each group and then take the sum. (Note: the implementation can simply count the size of each group \$|G|\$ using itertools.Counter and compute the number of pairs \$C_{|G|}^2\$)

If \$p\mid 10\$, we have either \$p = 2\$ or \$p = 5\$. In this case,
$$p \mid N_{i,j} \Leftrightarrow p \mid N_{i+1} $$
Here, \$N_{i+1}\$ is the \$(i+1)\$th digit of \$N\$. In other words, if \$p \mid N_{i+1} \$ holds, \$p \mid N_{i,j}\$ holds for all \$j\$ s.t. \$i<j\leq D(N)\$. It is easy to show that the final result is
$$\sum_{0\leq i < D(N),\,p\,\mid\, N_{i+1}}(D(N)-i)$$

The time complexity of this algorithm is \$\Theta(D(N))=\Theta(\log N)\$, which is better than the \$\Theta(D(N)^4)\$ solution in OP (see comments for explanation). Note that the runtime of the actual program depends on your implementation.
You may try to implement this approach yourself.


Computational verification of Collatz conjecture

Given that (from your comments) there is one and only one input which would cause overflow, I propose the following check at the beginning of the function:

int check_convergence(uint128_t n)
{
        const uint128_t n0 = n;
        int e;

        if (n == UINT128_MAX)
                return  1;

        do {
                ...
        } while (true);
}

I also added const to n0, given that it's constant through all the function.

if (n < UINT128_C(1) << 64 && e < LUT_SIZE64)
        return  0;

That can be rewritten as:

if (n <= UINT64_MAX && e < LUT_SIZE64)
        return  0;

Although maybe unneeded, I prefer to always parenthesize macros that evaluate to a value, just in case:

#define LUT_SIZE128  (81)


Create symmetrical matrix from list of values

First of all I would use np.zeros() to initialize your matrix. Using np.empty() can create a matrix with large values relative to your values on the diagonal which will affect the computation of 0-np.sum(my_matrix, 0) due to numeric underflow.

For example, just run this loop and you'll see it happen:

for i in xrange(10):
  print make_sym_matrix(4, [1,2,3,4,5,6])

Secondly, you can avoid taking the transpose by re-using the triu indices.
Here is the code combining these two ideas:

def make_sym_matrix(n,vals):
  m = np.zeros([n,n], dtype=np.double)
  xs,ys = np.triu_indices(n,k=1)
  m[xs,ys] = vals
  m[ys,xs] = vals
  m[ np.diag_indices(n) ] = 0 - np.sum(m, 0)
  return m


Finding the biggest product of two integers formed by the digits 1-9

Here is a quick try to implement your algorithm using 'foldr'. I did not check in depth whether my solution is correct.

I have divided the problem into parts. First we define a function that takes a list and splits the list into pairs of partitions where the order of elements is preserved.

split :: [a] -> [([a],[a])]
split []     = [([],[])]
split (x:xs) = concatMap (\(fst,snd) -> [(x:fst,snd), (fst,x:snd)]) (split xs)

Employing this definition we can define the list of tuples of decimals.

combinations :: [([Int],[Int])]
combinations = map (\(fst,snd) -> (9:fst,8:snd)) (split [7,6..1])

To transform these lists of decimals into numbers we use the following transformation.

toDeci :: [Int] -> Int
toDeci = foldl (\acc x -> x + 10 * acc) 0

Combining these functions we can redefine list as follows.

list :: [(Int,Int)]
list = map (\(fst,snd) -> (toDeci fst,toDeci snd)) combinations

Now we can define split by using foldr.

We can probably improve the code by using predefined functions like the arrow function (***).

Edit: You can generalize split by using the list monad. First we defined split using foldr as follows.

foldr (\x -> concatMap (\(fst,snd) -> [(x:fst,snd), (fst,x:snd)])) [([],[])]

Now we can observe that the neutral element is return ([],[]) in the list monad and concatMap is the implementation of (>>=). That is, we can define split as follows.

foldr (\x xs -> xs >>= (\(fst,snd) -> [(x:fst,snd), (fst,x:snd)])) (return ([],[]))

This implementation can be shortened by using the predefined function foldM from Control.Monad.

foldM (\(fst,snd) x -> [(x:fst,snd), (fst,x:snd)]) ([],[])


Checking for the nth prime number between 1 and 1,000,000, must compute 1,000,000th in under 3 minutes

Style (and related tools)

As described in Vogel612's answer, many things are wrong concerning the style. You can use pep8 (or its online version) to check it automatically and autopep8 to try to fix this automatically. You'll find various other convenient tools to check your code such as pylint, pyflakes or pychecker.

Separation of concerns and code organisation

You could create a function to look for the prime number and then call it when you want to print the result.

You'd get something like :

def get_nth_prime(goal):
    if goal > 1000000:
        return None
    if goal == 1:  # first prime is 2
        return 2
    if goal == 2:  # second prime is 3
        return 3

    chk = 5  # the next odd number after 3, which is already taken care of above
    primes = 2  # the number of primes recorded, after counting 2 and 3.
    while primes < goal:
        if chk < 9:  # if the number is odd and below 9....
            primes += 1  # it's prime
            chk += 2  # and check the next odd number

        else:  # if it's =>9......
            odds = 3  # check to see if it's divisible by the smallest odd number
            sqrtk = chk ** .5  # all the way up to the square root of chk

            while odds < sqrtk or odds == sqrtk:  # if at any time...
                if chk % odds == 0:  # ...chk is divisible by this odd number....
                    chk += 2  # then raise the value of chk to the next odd number
                    break  # and start the check from the beginning with next k
                else:  # if not...
                    # check to see if it's divisible by the next odd number.
                    odds += 2

            # if chk isn't divisible by any odds up to the square root of chk
            if odds > sqrtk:
                primes += 1  # we have a prime number
                chk += 2  # check the next odd number to see if it's prime
                odds = 3  # and reset odds back to 3 to use it next time

    if primes == goal:  # once we've reached the desired amount of prime numbers
        return chk - 2

goal = int(input("Enter a number n, 1-1,000,000 to find the nth prime number."))
print("The", goal, "prime number is:", get_nth_prime(goal))

Also, the usage is to write your code "that actually does stuff" behind an if main guard so that you can import your code if you want to re-use your function without having any polluting. In your case, it becomes :

def main():
    """Main function"""
    goal = int(input("Enter a number n, 1-1,000,000 to find the nth prime number."))
    print("The", goal, "prime number is:", get_nth_prime(goal))

if __name__ == "__main__":
    main()

Testing

Having extracted a function to get the n-th prime number, you can more easily write test. You can play it simple, manually :

assert get_nth_prime(1) == 2
assert get_nth_prime(2) == 3

Or you can go further :

assert [get_nth_prime(i) for i in range(1, 100)] == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523]

Now that we have test cases, rewriting the code is much easier.

A bit of logic

You can rewrite while odds < sqrtk or odds == sqrtk: : while odds <= sqrtk:

Then you can rewrite this using range : while odds < sqrtk or odds == sqrtk: and then the second test can be written using the infamous else on the for loop (the best way to understand it is to read it as nobreak). The code becomes :

        for odds in range(3, int(chk ** .5) + 1, 2):
            if chk % odds == 0:  # ...chk is divisible by this odd number....
                chk += 2  # then raise the value of chk to the next odd number
                break  # and start the check from the beginning with next k
        else: # no break => no divisors => prime
            primes += 1  # we have a prime number
            chk += 2  # check the next odd number to see if it's prime

The check if  chk<9 looks like a premature optimisation to me. We can get rid of it.

Then you have :

while primes < goal:
    for odds in range(3, int(chk ** .5) + 1, 2):
        if chk % odds == 0:  # ...chk is divisible by this odd number....
            chk += 2  # then raise the value of chk to the next odd number
            break  # and start the check from the beginning with next k
    else: # no break => no divisors => prime
        primes += 1  # we have a prime number
        chk += 2  # check the next odd number to see if it's prime

Then you have chk += 2 that appear in two different places : let's move it to a single place :

while primes < goal:
    for odds in range(3, int(chk ** .5) + 1, 2):
        if chk % odds == 0:  # ...chk is divisible by this odd number....
            break
    else: # no break => no divisors => prime
        primes += 1
    chk += 2

if primes == goal:  # once we've reached the desired amount of prime numbers
    return chk - 2

There is no need to compare primes and goal at every single iteration as it won't be updated that often : you can move this to the place where primes is increased :

chk = 5  # the next odd number after 3, which is already taken care of above
primes = 2  # the number of primes recorded, after counting 2 and 3.
while True:
    for odds in range(3, int(chk ** .5) + 1, 2):
        if chk % odds == 0:  # ...chk is divisible by this odd number....
            break
    else: # no break => no divisors => prime
        primes += 1
        if primes == goal:
            return chk
    chk += 2

More functions

The test of primality can easily be written in a function on its own.

Luckily, I have this ready in my toolbox :

def is_prime(n):
    """Checks if a number is prime."""
    if n < 2:
        return False
    return all(n % i for i in range(2, int(math.sqrt(n)) + 1))

def get_nth_prime(goal):
    if goal > 1000000:
        return None
    if goal == 1:  # first prime is 2
        return 2
    if goal == 2:  # second prime is 3
        return 3

    chk = 5  # the next odd number after 3, which is already taken care of above
    primes = 2  # the number of primes recorded, after counting 2 and 3.
    while True:
        if is_prime(chk):
            primes += 1
            if primes == goal:
                return chk
        chk += 2

This is getting into more advanced Python stuff so you might want to read a bit more about this.

More idiomatic

You are trying to generate prime numbers as you count them. A more pythonic way to do so would be to define a function to generate prime numbers one by one and another one to stop when we've reached what we want to reach. This could look like :

import math
import itertools

def is_prime(n):
    """Checks if a number is prime."""
    if n < 2:
        return False
    return all(n % i for i in range(2, int(math.sqrt(n)) + 1))

def yield_primes():
    """Yields prime number by checking them individually"""
    yield 2
    yield 3
    for i in itertools.count(5, 2):
        if is_prime(i):
            yield i

def nth(iterable, n, default=None):
    """Returns the nth item or a default value.
    From http://stackoverflow.com/questions/12007820/better-ways-to-get-nth-element-from-an-unsubscriptable-iterable ."""
    return next(itertools.islice(iterable, n, None), default)

def get_nth_prime(goal):
    if goal > 1000000:
        return None
    return nth(yield_primes(), goal - 1)

I just noticed I've re-used my non efficient is_prime function going through odd and even integers. I'll leave an an exercise to the reader to fun of going only through odd numbers :-)


count=0
while true; do
  printf "\r%d" $((++count))
  sleep 1
done

Your while condition is doing a lot of work just to return true: you launch a subshell, and evaluate  a test giving a 1-character string (which will always return true). Make it simpler and more readable by just executing the true program.

Note that variable names inside an arithmetic expression do not require the leading dollar sign in most cases. That's quietly documented here:

  "Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax."

printf is more portable than echo, if that's a concern for you. I also find it makes your intentions more obvious.

Instead of backing up the right number of characters, just carriage return to the first column and overwrite the previous contents.


Calculation of the Distance Matrix in the K-Means Algorithm in MATLAB

You Distance Matrix Calculation
You wrote the code (I summarize it for the Distance Matrix):
K = 3;
n = size(mX, 1);
d = size(mX, 2); %<! Number of dimensions per sample
mC = mX(randperm(n, K), :);

% mD = repmat(mX, 1, 1, K) - reshape(mC, 1, n, K); %<! Your code, Will fail because of reshape
mD = sum((reshape(mX, n, 1, d) - reshape(mC.', 1, K, d)) .^ 2, 3); %<! Correctly with no `repmat()`

The reason it won't work is the reshaping you're doing.
The number of elements in mC is K x d while your reshape() should keep the number of elements.
In the following I gave you a code snippet how to calculate the matrix mD efficiently.
K-Means
To calculate the distance you shouldn't use repmat() which will allocate new memory.
To calculate the Distance Matrix with the 3rd dimension and broadcasting you should do something like:
mD = sum((reshape(mA, numVarA, 1, varDim) - reshape(mB.', 1, numVarB, varDim)) .^ 2, 3);

But a faster way would be:
mD = sum(mA .^ 2).' - (2 * mA.' * mB) + sum(mB .^ 2);

Which utilizes the fast the Matrix Multiplication is probably the most optimized algorithm and that:
$$ {\left\| \boldsymbol{x} - \boldsymbol{y} \right\|}_{2}^{2} = \boldsymbol{x}^{T} \boldsymbol{x} - 2 \boldsymbol{x}^{T} \boldsymbol{y} + \boldsymbol{y}^{T} \boldsymbol{y} $$
For you to have a reference of K-Means algorithm with support for any Distance Function I created a function and ran it on your data:

It will converge very fast for that data:

I also created a small benchmark for various algorithm to compute the Euclidean Squared Distance Matrix.
The first test was between 3 approaches to calculate the distance between a single set of vectors (For example given by a single matrix):

The second test I compared 2 Row / Column variations of the algorithm above:

The Row / Column variations means I test the algorithm in 2 cases:

Row Variation - Each data sample is a row in the data matrix (Like your data).
Column Variation - Each data sample is a column in the data matrix (In MATLAB it means the sample is contiguous in memory).

As can be seen, it is always better to have data in the column variation.
Remark: Pay attention that the Squared Euclidean Distance doesn't obey the Triangle Inequality which is a requirement for a Metric. It is used for computational efficiency as it doesn't change the K-Means algorithm results compared to Euclidean Distance (The L2 Norm based distance).
The MATLAB Code is accessible in my StackExchange Code Review Q254186 GitHub Repository.
Remark: The K-Means algorithm, as a non convex optimization, is sensitive to the initialization. In the above code I used random initialization - randomly choosing samples form data to be the initial centroids. There are better approaches out there (See K-Means++ as an example for a more robust initialization).


Sudoku solutions finder using brute force and backtracking

Instead of using a fixed order of filling in cells you can first take the cells with the least amount of options left.

In other words if you know that cell 5,8 can only contain 5 and 6 then try each of them now and reduce the possibilities of the other cells instead of having to come back millions of times just to find out that the cell can't be filled any more.

This requires that you track the number of options in the board.

With a bitset it's doable, though un-setting a square is harder because you need to readjust all affected squares.

class SudokuBoard implements Cloanable{

    private Map<Position, BitSet> grid = new HashMap<Position, BitSet>();
    //fill in constructor

    public void setValue(Position pos, int number){
        number = number - 1;//bits are index 0 based

        BitSet square = grid.get(pos);

        if(!square.get(number))
            throw new IllegalArgumentException("number " + number + " can't be set at position " + pos);

        square.clear();
        square.set(number);

        // for each square in the row, collumn and big square do
        // square.set(number, false);

    }

    public Position getSquareWithLeastNumberOfOptions(){

        Position result = null;
        int count = 10;
        for(Map.Entry<Position, BitSet> e : grid.entrySet()){
            if(e.getValue().cardinality() < count && e.getValue().cardinality() != 1){
                result = e.getKey();
                count = e.getValue().cardinality();
            }
        }
        return result;
    }

    public int getFirstPossibleNumber(Position pos){
        return grid.get(pos).getNextSetBit(0)+1;
    }

    //returns 0 when no more options
    public int getNextPossibleNumber(Position pos, int previous){

        return grid.get(pos).getNextSetBit(previous)+1;

    }

    public boolean isSolved(){

        for(Map.Entry<Position, BitSet> e : grid.entrySet()){
            if(e.getValue().cardinality() != 1){
                return false;
            }
        }
        return true;
    }

    public boolean isSolvable(){

        for(Map.Entry<Position, BitSet> e : grid.entrySet()){
            if(e.getValue().cardinality() == 0){
                return false;
            }
        }
        return true;
    }

    @Override
    public SudokuBoard clone(){
        try{
            SudokuBoard clone = (SudokuBoard)super.clone();
            clone.grid = new HashMap(grid);
            for(Map.Entry<Position, BitSet> e : clone.grid.entrySet()){
                e.setValue((BitSet)e.clone());
            }
            return clone;
        } catch(CloneNotSupportedException e){
             return null;//can't happen
        }
    }

}

Then the algorithm looks something like:

public Set<SudokuBoard> getAllSolutions(SudokuBoard board){
    if(board.isSolved)
        return Collections.singleton(board);
    if(!board.isSolvable())
        return Collections.emptySet();

    Set<SudokuBoard> result = new HashSet<SudokuBoard>();

    Position pos = board.getSquareWithLeastNumberOfOptions();
    for(int num = board.getFirstPossibleNumber(pos); num != 0; num = getNextPossibleNumber(pos, num)){
        SudokuBoard newBoard = board.clone();

        newboard.setValue(pos, num);
        result.addAll(getAllSolutions(newBoard));
    }

    return result;
}

This will still create a lot of new partially solved boards but if you add a unSetValue(Position) to SudokuBoard then you can reuse the original board and only need to clone it when returning it in the singleton: return Collections.singleton(board.clone());.


The best way to place callback definition

In my opinion, if you use the same callback multiple times, or if the callbacks are similiar enough to be extracted and called with parameters, they should be extracted to keep DRY principle. In this case for me this does not make much difference if the callback was defined before first call, after it, or even if it exists in some other file, provided I can easily find it - and editors do help with that. For me there is slight preference to callback definition after the call, see below.

In case of single-use callbacks, I personally prefer to read them in-line. Let's consider these three options and how my brain works with them:

callback inline: I'm reading through the code in one go, learning what happens once the calling back action finishes;
callback definition after call: I perform mental GOTO, jumping to definition in order to understand what happens;
callback definition before call: I either skip it until I need it and make the same mental GOTO at some point later, or read through trying to remember and keep in mind what the callback does before I even know if and when it would be needed. I guess this could be called 'mental label' for the sake of consistent terminology.

I am lazy and prefer not to strain my brain trying to juggle multiple informations and contexts in order not to let them slip from short-term memory.


Finding the longest common suffix recursively

Recursive Solution Improvement
First, here's a rewrite of the answer you submitted yourself, which fixes a small bug and removes the inner function, which isn't needed.  Instead, we make the final two parameters optional:
function longestSuffix(X,Y,m,n) {
    var m = m === undefined ? X.length : m,
        n = n === undefined ? Y.length : n,
        keepGoing = X[m-1] && Y[n-1] && X[m-1] === Y[n-1];

    return keepGoing ? longestSuffix(X, Y, m-1, n-1) + X[m-1] : '';
};

Here's a different approach, slightly longer because I spelled everything out with variable names, but perhaps simpler in concept:
function longestSuffix (A, B, answer) {
    var answer = answer || '',
        aLast = A.slice(-1),
        bLast = B.slice(-1),
        A = A.slice(0,-1),
        B = B.slice(0,-1),
        done = !aLast || !bLast || aLast != bLast;

    return done ? answer : longestSuffix(A, B, aLast + answer);
};

You can make it shorter by, eg, removing aMinusLast and bMinusLast and replacing them inline with their definitions, but I like this expanded version because everything is clearly named, and the entire logic of the function can be seen at a glance in a single line.
Loop solution
A loop may be more appropriate here.  Here's a very brief implementation which takes advantage of slice, which exists on strings as well as arrays.
The only ugly part of this is that we have to treat the case when both A fully matches B as a special case in the return statement.  Otherwise note that the final slice(1) just adjusts back for the final decrement.
function longestSuffix (A, B) {
    var i = -1;
    while (A.slice(i) == B.slice(i) && i >= -A.length) i--;
    return i < -A.length ? A : A.slice(i).slice(1)
};

This could be expanded for further clarity, but I figured I'd leave this one in compressed form, because it's so short.


Reasons not to substitute Javascript for PHP

If you use Javascript (including jQuery), then your site won't work if Javascript is disabled.

To use Javascript, you have to give unauthenticated users the same information as authenticated users and even admins.  Someone can save the HTML and edit it to show the full information.  This doesn't matter much with a menu, but with data...

Formatting

<?php
  session_start();
   if(isset($_SESSION['Usuario']) and $_SESSION['estado'] == 'Autenticado')                     { ?>
     <?php echo $_SESSION['Usuario'];?>

    Salir
 <?php }
    else {    ?>
        Entrar
        Registrarse
<?php   }    ?>

I find your use of beginning and ending tags confusing.  Consider

<?php
  session_start();
  if (isset($_SESSION['Usuario']) && $_SESSION['estado'] == 'Autenticado') {
?>
     <?php echo $_SESSION['Usuario']; ?>

    Salir
<?php
  }
  else {
?>
        Entrar
        Registrarse
<?php
  }
?>

By always putting tags at the left margin, it is easier to see where code blocks begin and end.  Only the embedded output has the tags inline as well.  This will look more familiar to most people who might edit your code later.


Files.walkTree is causing Assignment Branch Condition too high

Well I figured out a way to refactor my code, and obtained a non-complex code by creating a method that returns the visitor named getSimpleFileVisitor(). I also created another method that will allow me to print the results that I named printFinalResults(). I have also refactored the method's name to walkFileTree().
Maybe my question was a little bit ambiguous, sorry for any inconvenience.

private void walkFileTree() {
    try{
        Files.walkFileTree(Paths.get(rootDirectory.getCanonicalPath()), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, getSimpleFileVisitor());
    }catch(IOException e) {
        System.out.println(e.getMessage());
    }
    printFinalResults();
}

private SimpleFileVisitor<Path> getSimpleFileVisitor(){
    SimpleFileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
            addToDictionary(path);
            return FileVisitResult.CONTINUE;
        }
    };
    return simpleFileVisitor;
}

private void printFinalResults() {
    System.out.println(this.indexedFileContents.keySet().size() + " files read in directory " + this.rootDirectory);
}


Finds a Character based on distance and health

The tests c.HP > 0 and c.Team != Team are probably blazingly fast tests.  Location.Dist(c.GetLocation()) <= AttackRange probably involves the square-root of the sum of the squares of the difference of coordinates in two or three dimensions. Plus, GetLocation() may involve memory allocation and/or copying constructors.  It is by far the slowest test, yet you are testing it first!  Take advantage of the short-circuit logical and operators by reordering the tests so the fastest tests are done first, so the slowest test may not even need to be executed, resulting in faster execution.

Since all conditions must pass before you update weakestEnemy, you could even test whether or not the target passes the “weakest with lowest ID” test before checking the attack range.

Bonus: the square-root can be avoided; simply compute the square distance, and compare against the \$AttackRange^2\$ (computed outside of the loop) for another speed gain.


Hmm... I cannot really make much of this code - what is the pupose of that parameter map?

However, there are a few things to note:

You make use of the modern datetime-api, which is great! And you use it in a correct way - I cannot see any flaws there. BUT in the end you throw all that precision, zoning and niceness overboard and convert everything into old.ugly.Date - why? As long as you use this internally, you should aim for the more precise and powerful api and only convert if necessary for legacy code.
Mashup of different tasks: in most cases, the formatting of data (or dates in this case) belongs to the presentation of an application, whereas the precise values belong to the business logic. Thus, I'd leave the formatting out of the method and move this into the presentation layer, which would also help with the next point...:
Map<String, Object> as a result value. With Object values you throw away all generic goodness a map has, and have to cast the values when you use them. This could be circumvented by eiher heeding my advice in the point above (returning Map<String, LocalDateTime>) or by creating a result class which just consists of the four fields with the correct data types.
Magic strings: "startTime", "endTime", etc. should probably be moved to publicly accessible constants, so the the consumer of the map can use these constants to look up the values he needs without "knowing" and duplicating the concrete key-strings.


Leftist Tree in Dyalog APL -- can it be made more compact/idiomatic?

I think your code generally looks good.

Comments

I recommend annotating functions with what the structure of their argument(s) and result are, especially when not just simple arrays, at the top of the function, rather than relying on code comments to reveal this.

Take benefit of dyadic functions

If you define Insert and Pop as dyadic functions both code and usage can be simplified. You can even let ⍬ be the default left argument, allowing easy initialisation of a tree.

Insert←{ ⍝ Insert item ⍵ into leftist tree ⍺, returning the resulting tree
    ⍺←⍬              ⍝ default to init
    1 ⍵ ⍬ ⍬ Merge ⍺
}

h←Insert 2
h Insert←10
h Insert←9

s←Insert 3
s Insert←6

Full variable names or not?

This is a personal style thing. Some people prefer mathematical-looking single-letter variables, others like full variable names that obviate comments. However, at least be consistent. (I've also moved the first element of ⍵ to become ⍺, as per above.)

Pop←{ ⍝ Pop off smallest element from a leftist tree
    0=≢⍺:⍬
    (value left right)←⍵
    (left Merge right) value
}

Unnecessary naming

⍺ and ⍵ are well understood to be the left and right arguments. I don't think renaming them t1 and t2 brings much, other than the ability to create matching keyN variables. However, here you only ever use key2 once, and its definition is very simple, and in fact as short or shorter than any appropriate name, so you might as well use it inline, freeing up key to only apply to ⍵:

Merge←{ ⍝ Merge leftist trees ⍺ and ⍵
    0=≢⍺:⍵ ⋄ 0=≢⍵:⍺                              ⍝ If either is a leaf, return the other
    (key left right)←1↓⍺
    key>1⌷⍵:⍵∇⍺                                  ⍝ Flip to ensure smallest is root of merged
    merged←right∇⍵                               ⍝ Merge rightwards
    (⊃left)≥⊃merged:(1+⊃merged) key left merged  ⍝ Right is shorter
    (1+⊃left) key merged left                    ⍝ Left is shorter; make it the new right
}


jQuery delegate events on dynamic elements with a click away handler

I believe there is no better way. Regardless, we can shorten the code a little. Also note that .delegate() has been superceded by .on() since jQuery 1.7, so I replaced your delegate with on.

$(document).on( 'click', '.button', function(e){
    var $button = $(this);
    var $menu = $button.closest('.menu');
    e.stopPropagation();

    // Close others-assumed you want all menus closed
    $('.menu').not($menu).removeClass('open');

    // Toggle target open/close
    $menu.toggleClass('open');

    $(document).on('click', function(e){
        //This function will only run when e.target isn't a button
        //Your $target.is($menu.find('button')) will always be false

        if( $menu.hasClass('open') ){
            $menu.removeClass('open');
        }
    });
});

If this does not do the same thing, you really need to share your html structure so we can get a better idea of your mark-up.

Edit
To work around the fact that the document click event is assigned every time you click on a button, you could do something like the following:

$(document).ready(function() {
   var $menu;
   $(document).on( 'click', '.button', function(e){
      var $button = $(this);
      $menu = $button.closest('.menu');
      e.stopPropagation();
      $('.menu').not($menu).removeClass('open');
      $menu.toggleClass('open');
   });
   $(document).on('click', function(e){
      if($menu && $menu.hasClass('open') ){
            $menu.removeClass('open');
        }
   });
)}


AVX512 - Add two 512-bit integers using _addcarryx_u64 function

Probably not what you're expecting, but it's possible to do a 512-bit add directly with AVX512 registers. The _addcarryx_u64() intrinsic is not necessary nor do you need to break up the register into scalars.

Taken from my blog: http://www.numberworld.org/y-cruncher/internals/addition.html#ks_add

The following is a little-endian 512-bit full-adder:

__m512i add512(uint32_t& carry, __m512i A, __m512i B){

    const __m512i MAX_WORD = _mm512_set1_epi64(0xffffffffffffffff);

    __m512i s = _mm512_add_epi64(A, B);
    __mmask16 c = _mm512_cmplt_epu64_mask(s, A);
    __mmask16 m = _mm512_cmpeq_epi64_mask(s, MAX_WORD);

    {

        uint32_t c0 = _mm512_mask2int(c);
        uint32_t m0 = _mm512_mask2int(m);
        carry += m0;
        carry = (carry + c0*2); //  lea
        m0 ^= carry;
        carry >>= 8;
        m = _mm512_int2mask(m0);

    }

    return _mm512_mask_sub_epi64(s, m, s, MAX_WORD);
}

The carry parameter indicates the carry-in. It will be replaced with the carry-out. It must be either 0 or 1.

To clarify, this is little-endian across all 512 bits. So carry propagation goes from lowest address to highest address. I'm not sure if this is what you really wanted since your example seems to do it in big-endian with 64-bit granularity.

If you really do want this in big-endian, you will need to shuffle all the inputs and outputs since there's no way to efficiently reverse the direction of the carry-propagation.

Background:

This is something I attacked back in January of 2017 while I was experimenting with parallel adder algorithms. And somewhat by chance I managed to derive the general approach to the above method.

I've since been told that this sequence was already known internally to Intel, but they never published it. And it seems quite likely that the kadd mask instructions were specifically designed for parallel-prefix algorithms like the adder given here.


Project Euler Problem #3 in Java - Largest Prime Factor

Counting downwards hurts the performance extremely as you are checking way more values than you have to (e.g. for this value you have to iterate only to the second largest prime number (1471) to know the largest prime number).

final long t0 = System.nanoTime();
final long factor = largestPrimeFactor(600851475143L);
final long t1 = System.nanoTime();
System.out.println(t1 - t0);
System.out.println(factor);

Results (significantly faster):

19071
6857

The code in largestPrimeFactors is a bit modified version of a normal primeFactor method (iterating only over values that are not a multiple of 2 or 3):

public static long largestPrimeFactor(
        final long input) {
    ////
    if (input < 2)
        throw new IllegalArgumentException();

    long n = input;
    long last = 0;
    for (; (n & 1) == 0; n >>= 1)
        last = 2;
    for (; n % 3 == 0; n /= 3)
        last = 3;
    for (long v = 5, add = 2, border = (long) Math.sqrt(n); v <= border; v += add, add ^= 6)
        while (n % v == 0)
            border = (long) Math.sqrt(n /= last = v);
    return n == 1 ? last : n;
}


Enclosing Circle Problem implementation in Haskell

As per request by Mihai , here is the accepted code of spoj problem . The only error in previous code was " The minimal enclosing circle is determined by the diametric circle of S ".  Instead of finding a circle passing through two points , i was calculating circle from three points.

import Data.List
import qualified Data.Sequence as DS
import Text.Printf
import Data.Function ( on )

data Point a = P a a deriving ( Show , Ord , Eq )
data Turn = S | L | R deriving ( Show , Eq , Ord , Enum  ) -- straight left right

--start of convex hull  http://en.wikipedia.org/wiki/Graham_scan
{--
compPoint :: ( Num  a , Ord a ) => Point a -> Point a -> Ordering
compPoint ( P x1 y1 ) ( P x2 y2 )
  | compare x1 x2 == EQ = compare y1 y2
  | otherwise = compare x1 x2

findMinx :: ( Num a , Ord a ) => [ Point a ] -> [ Point a ]
findMinx xs = sortBy ( \x  y  -> compPoint  x y  ) xs

compAngle ::(Num a , Ord a ) => Point a -> Point a -> Point a -> Ordering
compAngle ( P x1 y1 ) ( P x2 y2 ) ( P x0 y0 ) = compare ( (  y1 - y0 ) * ( x2 - x0 )  ) ( ( y2 - y0) * ( x1 - x0 ) )

sortByangle :: ( Num a , Ord a ) => [ Point a ] -> [ Point a ]
sortByangle (z:xs) = z : sortBy ( \x y -> compAngle x y z ) xs

convexHull ::( Num a , Ord a )  => [ Point a ] -> [ Point a ]
convexHull xs = reverse . findHull [y,x]  $ ys where
    (x:y:ys) = sortByangle.findMinx $ xs

findTurn :: ( Num a , Ord a , Eq a ) => Point a -> Point a -> Point a -> Turn
findTurn ( P x0 y0 ) ( P x1 y1 ) ( P x2 y2 )
  | ( y1 - y0 ) * ( x2- x0 ) < ( y2 - y0 ) * ( x1 - x0 ) = L
  | ( y1 - y0 ) * ( x2- x0 ) == ( y2 - y0 ) * ( x1 - x0 ) = S
  | otherwise = R

findHull :: ( Num a , Ord a  )  => [ Point a ] ->   [ Point a ] -> [ Point a ]
findHull [x]  ( z : ys )  = findHull [ z , x ]  ys  --incase of second point  on line from x to z
findHull xs  [] = xs
findHull ( y : x : xs )  ( z:ys )
   | findTurn x y z == R = findHull (  x : xs )   ( z:ys )
   | findTurn x y z == S = findHull (  x : xs )   ( z:ys )
   | otherwise = findHull ( z : y : x : xs  )   ys
--}

--start of monotone hull give .04 sec lead over graham scan

compPoint :: ( Num  a , Ord a ) => Point a -> Point a -> Ordering
compPoint ( P x1 y1 ) ( P x2 y2 )
  | compare x1 x2 == EQ = compare y1 y2
  | otherwise = compare x1 x2

sortPoint :: ( Num a , Ord a ) => [ Point a ] -> [ Point a ]
sortPoint xs = sortBy ( \ x y -> compPoint x y ) xs

findTurn :: ( Num a , Ord a , Eq a ) => Point a -> Point a -> Point a -> Turn
findTurn ( P x0 y0 ) ( P x1 y1 ) ( P x2 y2 )
 | ( y1 - y0 ) * ( x2- x0 ) < ( y2 - y0 ) * ( x1 - x0 ) = L
 | ( y1 - y0 ) * ( x2- x0 ) == ( y2 - y0 ) * ( x1 - x0 ) = S
 | otherwise = R

hullComputation :: ( Num a , Ord a ) => [ Point a ] -> [ Point a ] -> [ Point a ]
hullComputation [x] ( z:ys ) = hullComputation [z,x] ys
hullComputation xs [] = xs
hullComputation  ( y : x : xs ) ( z : ys )
  |  findTurn x y z == R = hullComputation ( x:xs ) ( z : ys )
  |  findTurn x y z == S = hullComputation ( x:xs ) ( z : ys )
  |  otherwise = hullComputation ( z : y : x : xs ) ys

convexHull :: ( Num a , Ord a ) => [ Point a ] -> [ Point a ]
convexHull xs = final where
    txs = sortPoint xs
    ( x : y : ys  ) = txs
        lhull = hullComputation [y,x] ys
    ( x': y' : xs' ) = reverse txs
    uhull = hullComputation [ y' , x' ] xs'
    final = ( init lhull ) ++ ( init uhull )

--end of convex hull
--start of finding point algorithm http://www.personal.kent.edu/~rmuhamma/Compgeometry/MyCG/CG-Applets/Center/centercli.htm  Applet’s Algorithm

findAngle :: ( Num a , Ord a , Floating a ) => Point a -> Point a -> Point  a  -> ( Point a , Point a , Point  a , a )
findAngle u@(P x0 y0 ) v@(P x1 y1 ) t@(P x2 y2)
    | u == t || v == t = ( u , v , t , 10 * pi )  -- two points are same so set the angle more than pi
    | otherwise =  ( u , v, t , ang ) where
        ang = acos $  ( b + c - a ) / ( 2.0 * ( sqrt $ b * c ) )  where
        sqrDist ( P x y ) ( P x' y' ) = ( x - x' ) ^ 2 + ( y - y' ) ^ 2
        [ b , c , a ] = map ( uncurry sqrDist ) [ ( u , t ) , ( v , t ) , ( u , v ) ]

 findPoints :: ( Num a , Ord a , Floating a ) => Point a -> Point a -> [ Point  a ] -> ( Point a  , a )
 findPoints u v xs
  | 2 * theta >= pi   =  circle2Points a b  --( a , b , t , theta )
  | and [ 2 * alpha <= pi , 2 * beta <= pi ]   = circle3Points a b t --( a , b , t , theta )
  | otherwise = if 2 * alpha > pi then findPoints v t xs else findPoints u t xs
     where
    ( a , b , t , theta ) = minimumBy ( on compare fn  ) . map ( findAngle u v )  $ xs
    fn ( _ , _ , _ , t ) = t
        ( _ , _ , _ , alpha ) = findAngle v t u  --angle between v u t angle subtended at u by v t
    ( _ , _ , _ , beta ) = findAngle u t v   -- angle between u v t angle subtended at v by  u t

--end of finding three points algorithm
--find the circle through three points http://paulbourke.net/geometry/circlefrom3/

circle2Points :: ( Num a , Ord a , Floating a ) => Point a -> Point a -> ( Point a , a )
circle2Points ( P x0 y0 ) ( P x1 y1 ) = ( P x y , r ) where
    x = ( x0 + x1 ) / 2.0
    y = ( y0 + y1 ) / 2.0
    r = sqrt $ ( x0 - x1 ) ^ 2 + ( y0 - y1 ) ^ 2

circle3Points :: ( Num a , Ord a , Floating a ) => Point a -> Point a -> Point a -> (  Point a , a ) --( center , radius )
circle3Points u@(P x1 y1 ) v@(P x2 y2 ) t@(P x3 y3 )
    | x2 == x1 = circle3Points u t v
    | x3 == x2 = circle3Points v u t
    | otherwise =  ( P x y , 2 *  r )
      where
        m1 = ( y2 - y1 ) / ( x2 - x1 )
        m2 = ( y3 - y2 ) / ( x3 - x2 )
        x = (  m1 * m2 * ( y1 - y3 )  +   m2 * ( x1 + x2 )  -  m1 * ( x2 + x3 )  ) / ( 2 * ( m2 - m1 ) )
        y = if y2 /= y1
                     then ( ( x1 + x2 -  2 * x  ) / ( 2 * m1 ) ) + ( ( y1 + y2 ) / 2.0 )
              else  ( ( x2 + x3 -  2 * x  ) / ( 2 * m2 ) ) + ( ( y2 + y3 ) / 2.0 )
        r = sqrt $ ( x - x1 ) ^2 + ( y - y1 ) ^ 2

--start of SPOJ code

format::(Num a , Ord a ) => [[a]] -> [Point a]
format xs = map (\[x0 , y0] -> P x0 y0 ) xs

readInt  ::( Num a , Read a ) =>   String -> a
readInt  = read

solve :: ( Num a , Ord a , Floating a ) => [ Point a ] -> (  Point a , a )
solve [ P x0 y0 ] = ( P x0 y0 , 0 ) --in case of one point
solve [ P x0 y0 , P x1 y1 ] = circle2Points ( P x0 y0 ) ( P x1 y1 )   -- in case of two points
solve  xs = findPoints x y  t where
    t@( x : y : ys )  = convexHull xs

final :: ( Num a , Ord a , Floating a ) => ( Point a , a ) -> a
final ( t , w )
    | w == 0 = 0
    | otherwise =  w

main = interact $   ( printf "%.2f\n" :: Double -> String ) . final . solve . convexHull . format . map  ( map readInt . words ) . tail . lines


Removing hackery from pair of radix functions

The reverse operation to folding is unfolding.  To be honest, I'm not very
fluent in python and I couldn't find if python has an unfolding function.
(In Haskell we have
foldr
and its complement
unfoldr.)

Nevertheless, we can easily construct one:

"""
f accepts a value and returns None or a pair.
The first element of the pair is the next seed,
the second element is the value to yield.
"""
def unfold(f, r):
    while True:
        t = f(r);
        if t:
            yield t[1];
            r = t[0];
        else:
            break;

It iterates a given function on a seed until it returns None, yielding intermediate results. It's dual to reduce, which takes a function and an iterable and produces a value. On the other hand, unfold takes a value and a generating function, and produces a generator. For example, to create a list of numbers from 0 to 10 we could write:

print list(unfold(lambda n: (n+1, n) if n <= 10 else None, 0));

(we call list to convert a generator into a list).

Now we can implement radix quite nicely:

def radix(source, radix):
    return unfold(lambda n: divmod(n, radix) if n != 0 else None, source);

print list(radix(12, 2));

prints [0, 0, 1, 1].

Edit: Folding (reduce) captures the pattern of consuming lists. Any function that sequentially consumes a list can be eventually written using reduce. The first argument to reduce represents the core computation and the third argument, the accumulator, the state of the loop. Similarly, unfolding (my unfold) represents the pattern of producing lists. Again, any function that sequentially produces a list can be eventually rewritten using unfold.

Note that there are functions that can be expressed using either of them, as we can look at them as functions that produce or consume lists. For example, we can implement map (disregarding any efficiency issues) as

def map1(f, xs):
    return reduce(lambda rs, x: rs + [f(x)], xs, [])

def map2(f, xs):
    return unfold(lambda xs: (xs[1:], f(xs[0])) if xs else None, xs)

The duality of reduce and unfold is nicely manifested in a technique called deforestation. If you know that you create a list using unfold only to consume it immediately with reduce, you can combine these two operations into a single, higher-order function that doesn't build the intermediate list:

def deforest(foldf, init, unfoldf, seed):
    while True:
        t = unfoldf(seed);
        if t:
            init = foldf(t[1], init);
            seed = t[0];
        else:
            return init;

For example, if we wanted to compute the sum of digits of 127 in base 2, we could call

print deforest(lambda x,y: x + y, 0,  # folding part
               lambda n: divmod(n, 2) if n != 0 else None, # unfolding
               127); # the seed


Foobar Fuel Injection Perfection efficiency

I was going to make this a comment, but it's easier as an answer.

Your issue very likely stems from the large amount of division / modulo, those are very slow operations, and the larger the number the slower they are.

If we consider n % 2 == 0, we can replace that modulo entirely with n & 1 == 0, because the bit-pattern of 1 is 0b00000001, which means we will only be looking at the last bit of n (which happens to be the easiest way to determine even vs. odd).

Likewise, you only ever divide by 2, which can be more easily accomplished via n >> 1, which will shift the entire bit-array right one position (which is equivalent to a divide-by-two), accomplished via n.shiftRight(1). Between the two of these, you'll probably find that performance is increased ten-fold. You could run both of these formulas with the value of 5, for example, to prove it to yourself.

The advantage to both of these is the heavily reduced instruction cost. If we take a look at the instruction tables provided by this handy PDF, we can get a rough-estimate of the issue by looking for certain, specific instructions. These may not be the exact instructions the JVM is executing, but they'll give us a good feel for how division vs. shifting and modulo vs. anding perform.

For a modulo, in x86, this is accomplished by using the DIV instruction and checking the remainder register, so we know that we need that instruction for both comparisons.

For anding, in x86, this is accomplished by the AND instruction, and for right-bit-shifting, in x86, this is accomplished by the SHR instruction.

The first instruction I want to lookup is DIV, since we need it for all our comparisons. I'm going to reference the 'Skylake' values (since that is my processor chipset). The table for it is laid out below:

                     µops   µops                        Reciprocal
                     fused  unfused µops                through
Instruction Operands domain domain  each port   Latency put        Comments
DIV         r64      36     36      p0 p1 p5 p6 35-88   21-83

The first thing that stands out there is that the latency is 35-88 cycles. That means the result will be valid after that cycle-count passes. That's a lot.

Let's look at AND:

AND OR XOR  r,r/i    1      1      p0156        1       0.25

Oh boy, latency of 1 already. What about SHR:

SHR SHL SAR r,i      1      1      p06          1       0.5

Same thing, so that gives us an estimate that we should be seeing ~35x improvement on execution time just from these optimizations. In reality it'll be less, a good conservative estimate is ~20x, just because of overhead and I'm not certain this is the course the JVM is taking. (It could have optimized something.) If the JVM did a good optimization, and not one for the special case of 2, then you're likely looking at 2-10x improvement, but that's still a lot of improvement.

The names answer and helper are very non-descriptive. Consider naming the methods after the algorithm or based on what they do, as they're currently non-sensical.


i should be initialized to lo + 1 this will reduce the while loop by 1
you should use braces {} for single if statements. This will make your code less errorprone.
instead of doing this recursively, you could do is iterativ by adding a while loop with (lo < lowerIndex - 1 && greaterIndex + 1 < hi) as condition.
for make the if..else if you shoul consider to swap the position of element and array [i] because if you imagine the array, index 0 will be on the left

if (element > array[i])


Reading input from file for bridge simulation program

Parameter shadowing a local variable:

The first issue with your code that prevented in from compiling with Clang is the
inFile parameter of getInput() that shadows the ifstream instance of the same name.

Your compiler seems to be more forgiving with that problem. If you are using GCC, I recommend using the -Wshadow warning flag to enable warnings of this kind of variable name shadowing/redeclaration. This category of bugs can be particularly hard to track in a scenario where both variables are of the same type.

Reserved suffix:

The _t suffix is reserved by the POSIX standard (read this), so it is best if avoided.
Consider renaming direction_t and priority_t to Direction and Priority.

Const correctness:

The filename parameter of the function is a read-only string, so it should at least
be a const char *. But since this is C++ code, prefer a standard string and pass it by const reference:

void getInput(const std::string & filename)

Error handling:

You did right by using std::cerr to report errors, however, exit()ing after the error is logged
seems like a very crude way of handling it. Consider throwing an exception or even
making the function return a boolean false.

Using namespace:

You are probably using namespace std somewhere, judging by the lack of the std:: prefix in the library calls. This is best if avoided as it defeats the purpose of a namespace, which is allowing equal names to coexist without clashes. Read this thread for a more in-depth discussion.

Data driven solution:

There is a more data driven and flexible way of handling the conversion between the chars
read from file to the Direction/Priority enums than an if chain or a switch statement.

You could instead use a map keyed by a char. This way, expanding and adding more chars
is simpler and involves less code change. You could even externalize the map to a file
and load it dynamically at runtime if you wanted.

Following is the refactored code with the changes above mentioned applied to it plus
the use of a std::map as a lookup table. The map associates a char (the key)
with a pair of [Direction, Priority]. Making the conversion form the file data a lot more concise.

#include <iostream>
#include <fstream>
#include <string>
#include <map>

bool getInput(const std::string & filename)
{
    enum Direction { NORTH, SOUTH };
    enum Priority  { HIGH,  LOW   };

    const std::map<char, std::pair<Direction, Priority>> lookupTable = {
        { 'n', { NORTH, LOW  } },
        { 'N', { NORTH, HIGH } },
        { 's', { SOUTH, LOW  } },
        { 'S', { SOUTH, HIGH } }
    };

    Priority    priority;
    Direction   direction;
    std::string line;

    std::ifstream inFile(filename);
    if (!inFile.good())
    {
        std::cerr << "can't open input file";
        return false;
    }

    while (getline(inFile, line))
    {
        const char key = line.at(0); // first letter signifies direction and priority

        const auto entry = lookupTable.find(key);
        if (entry != lookupTable.end())
        {
            direction = entry->second.first;
            priority  = entry->second.second;
        }
        else
        {
            std::cerr << "invalid direction given: " << key << std::endl;
        }

        size_t commaIndex = line.find(",", 2); // know first character is letter, second is |
        std::string firstNumber  = line.substr(2, commaIndex - 2);
        std::string secondNumber = line.substr(commaIndex + 1, line.length());
        std::cout << "firstNumber: " << firstNumber << " secondNumber " << secondNumber << std::endl;
    }

    return true;
}

So it turn out that the OP's compiler is missing a few C++11 features that prevent the code provided above from compiling. It can be fairly easily adapted to support older compilers though, if we are willing to add a few not so elegant workarounds. Here is one way to adapt it using an aux function that keeps a static std::map:

enum Direction { NORTH, SOUTH, DIR_INVALID };
enum Priority  { HIGH,  LOW,   PRI_INVALID };

std::pair<Direction, Priority> lookup(char key)
{
    typedef std::map< char, std::pair<Direction, Priority> > TableType;

    static bool isTableInitialized = false;
    static TableType lookupTable;

    // One time initialization
    if (!isTableInitialized)
    {
        lookupTable.insert(std::make_pair( 'n', std::make_pair(NORTH, LOW)  ));
        lookupTable.insert(std::make_pair( 'N', std::make_pair(NORTH, HIGH) ));
        lookupTable.insert(std::make_pair( 's', std::make_pair(SOUTH, LOW)  ));
        lookupTable.insert(std::make_pair( 'S', std::make_pair(SOUTH, HIGH) ));
        isTableInitialized = true;
    }

    TableType::const_iterator entry = lookupTable.find(key);
    if (entry != lookupTable.end())
    {
        return (*entry).second;
    }

    // Not found / invalid key
    return std::make_pair(DIR_INVALID, PRI_INVALID);
}

bool getInput(const std::string & filename)
{
    Priority    priority;
    Direction   direction;
    std::string line;

    std::ifstream inFile(filename.c_str());
    if (!inFile.good())
    {
        std::cerr << "can't open input file";
        return false;
    }

    while (getline(inFile, line))
    {
        // first letter signifies direction and priority
        const char key = line.at(0);

        // Lookup the conversion table:
        const std::pair<Direction, Priority> entry = lookup(key);

        if ((entry.first != DIR_INVALID) && (entry.second != PRI_INVALID))
        {
            direction = entry.first;
            priority  = entry.second;
        }
        else
        {
            std::cerr << "invalid direction given: " << key << std::endl;
        }

        size_t commaIndex = line.find(",", 2); // know first character is letter, second is |
        std::string firstNumber  = line.substr(2, commaIndex - 2);
        std::string secondNumber = line.substr(commaIndex + 1, line.length());
        std::cout << "firstNumber: " << firstNumber << " secondNumber " << secondNumber << std::endl;
    }

    return true;
}

It has its drawback, but should work just the same. It is also quite a bit more code to get it done. One important thing to keep in mind is that initialization order of the lookup table is not thread safe, so don't try to use this in a concurrent program.


In general, the code is well presented, easy to read, but, it is hard to spot the 'Horner's Scheme' in the code.

When implementing a specific algorithm in code, it is useful to clearly comment where the elements of the algorithm are being used.

In this case, the depth-first recursion is processing the most significant digits first, and as a result, it computes the high-order values in the Horner's scheme first. Making that value available to be added to the next value in the system.

Note that this makes tail-recursion optimization impossible, but it does simplify the code.

So, I had to look up how Horner's scheme would help your code, and I had to figure out how your code is helped by it. This is not work that should be hard. You should make that easy for the person reading the code.

I would expect something like:

// based on Horner's scheme: http://en.wikipedia.org/wiki/Horner%27s_method
// The source base of the value can be considered to be Xo in the algorithm, and
// the digit value is the coefficient for that base.

As for your recursion, you can simplify it a little by recursing one level more, and returning 0 (eliminating a duplicated division on each level). Consider your code:

int toDecimal (int base, int number)
{
    if (number / 10 == 0) {
        return number;
    }
    return (number % 10) + (base * toDecimal (base, number / 10));
}

and replacing that code with:

int toDecimal (int base, int number)
{
    if (number == 0) {
        return 0;
    }
    return (number % 10) + (base * toDecimal (base, number / 10));
}

The difference is marginal, trading one division/comparison with a simple comparison and an extra level of recursion.

Regardless, I prefer the reduced code duplication, and it makes the recursion termination easier to see.

The other item I see missing is validation on the input. I would prefer to see some exceptions thrown if the input is in a base that does not support the supplied digits. For example, with the input:

12345 4 10

Putting this all together, I suggest the following:

#include <iostream>
#include <stdexcept>

int toDecimal (int, int);
int fromDecimal (int, int);
int convert(int, int, int);

int main()
{
    int base, number, desiredBase;
    std::cin >> number >> base >> desiredBase;
    try
    {
        std::cout << convert(number, base, desiredBase) << std::endl;
    } catch (const std::invalid_argument& e)
    {
        std::cerr << "Unable to convert " << number << " from base " << base << std::endl;
        return 1;
    }
}

int toDecimal (int base, int number)
{
    if (number == 0)
    {
        return 0;
    }

    int digit = number % 10;
    if (digit >= base)
    {
        throw std::invalid_argument( "received out-of-range digits in the input for the supplied base");
    }

    return digit + (base * toDecimal (base, number / 10));
}

int fromDecimal (int base, int number)
{
    if (number == 0) {
        return 0;
    }
    return (number % base) + (10 * fromDecimal (base, number / base));
}

int convert(int number, int base, int desiredBase)
{
    int p = toDecimal(base, number);
    return fromDecimal(desiredBase, p);
}

In addition to handling the exceptions from invalid input numbers, you should also handle requests to/from invalid bases as well (like negative or bases > 10).


How to avoid using exec() and eval() in Python

You can use getattr, setattr and delattr to retrieve, modify and remove attributes respectively. This avoids most potential messes eval has.
input_files_dict = json.loads(cfg.get("service_info", "file_inputs"))
for key, val in input_files_dict.items():
    setattr(self, key, self.post_data(f'{value}'))


PEP-8 says:

  Imports should be grouped in the following order:

  standard library imports
  related third party imports
  local application/library specific imports

  You should put a blank line
  between each group of imports.

I follow it and then sort modules alphabetically within each group without separating from from the other imports, like this:

import re
import os
from   pprint import pprint
import traceback

import lxml

from   readers    import SomeReader
from   util.stuff import (stuff_init, stuff_close, StdStuff,
                          OtherStuff, BlahBlah)


A couple of possible bugs:

It results in this:

Knapsack(54, [Item(12, 8), Item(12, 8), Item(12, 8), Item(12, 8), Item(4, 2), Item(1, 0.1), Item(1, 0.1)])

How can you put one item in the knapsack four times over? And if you could, would you want four shovels just because one shovel is very useful? You never take anything out of the list of items once you have incorporated it.
is_full and can_incorporate both do very similar things, and interact badly in the fill function - what happens if the knapsack is not full, but it cannot incorporate any of the remaining items? It will crash trying to return the max of an empty list - or if that didn't happen, it would loop forever testing whether it could incorporate the next best thing, but never being able to. You could stay with while self.can_incorporate(item) and get rid of is_full().
When you initialise the Knapsack() object, you can pass a long list of items, which go straight into the items_inside without any capience checks - you can bypass the capacity limit and overload it. Then when you fill() it, it will crash.
Nothing stops you from just adding things to the items_inside list regardless of whether the Knapsack can take it, and it can't test for that afterwards. I feel like adding something to a full knapsack should raise an exception, like removing something from an empty list raises an exception. (e.g. putting a vehicle into the knapsack is an exceptional condition - you don't do it deliberately).

I'm no design expert for sure; but I feel a bit like you're losing the heart of the problem code by squishing the algorithm into almost a one-liner and overwhelming it with surrounding methods that are only there to support the algorithm.

I know that's what support methods are for, and in a way it's neat and tidy. But in another way, it's noisy and unclear.

I don't know what I'd change, exactly, and I'm left bikeshedding at things like:

capience isn't a word I can find on Google, what about capacity? Maybe capience is a fine word, but capacity seems like volume, so maybe weight_limit?
What about contents instead of items_inside?
Why current_weight instead of weight?
What about making current_weight a property so you have the same calling style as capience, instead of one being a property and one being a function call
It seems a lot of effort to calculate the remaining list every time in the fill loop, and calculate the sum of weights every time. You could sort the list of items by convenience, pop() them from the list, or iterate through it only once.
You pass fill a list of items, but don't know which ones it fills and which ones it doesn't.

So I've ended up rewriting it myself, and it's no shorter, and probably no clearer. But it might address some of these points. The Knapsack manages its own contents as a "private" variable (_contents), so it can protect against overload, and that means loading an item has its own method. Fill() only runs through the list once. Initialising the Knapsack can't overload it.

from __future__ import division

class Item:
    def __init__(self, weight, value):
        self.weight = weight
        self.value = value
        self.convenience = value / weight

    def __repr__(self):
        return "Item(weight={}, value={})".format(self.weight, self.value)

class Knapsack:
    def __init__(self, weight_limit, initial_items=[]):
        self.weight_limit = weight_limit
        self._contents = []
        self.fill(initial_items)

    def weight(self):
        return sum(item.weight for item in self._contents)
    weight = property(fget=weight)

    def incorporate(self, item):
        if self.weight + item.weight > self.weight_limit:
            raise Exception("Knapsack Overload Exception: {} is too heavy".format(item))
        self._contents.append(item)

    def fill(self, items):
        items = sorted(items, key=lambda item: item.convenience, reverse=True)
        rejected_items = []
        for item in items:
            try:     self.incorporate(item)
            except:  rejected_items.append(item)

        return rejected_items

    def __repr__(self):
        return "Knapsack({}, {})".format(self.weight_limit, self._contents)

def main():
    bag = Knapsack(54)
    print bag.fill([
        Item(12, 8),
        Item(20, 13),
        Item(4, 2),
        Item(200,1),
        Item(1, 0.1)])
    print(bag)

if __name__ == "__main__":
    main()

(I notice that I haven't even considered your actual question about whether the Item class is necessary! I don't know, it seems useful. Although having an item name might be good).


Find and return the earliest occurring word from a string which contains the most repeating letters

The core problem can be solved a lot quicker using the built-in max and making a generator that produces the maximum count of repeated letters. Note that max already takes the first occurrence of the maximum, as required by the challenge, but we need to take care to not compare the words lexicographically, as I did in a previous version, by using a key function. You should probably add testcases for this, such as "free greatest" -> "free" and "greatest free" -> "greatest".

from collections import Counter
from operator import itemgetter

def letter_count(s):
    words = s.split(" ")
    most_common_letters = (Counter(word).most_common(1)[0][1] for word in words)
    return max(zip(most_common_letters, words), key=itemgetter(0))[1]

This does not handle any of the edge cases, though. It fails if the most common letter is not an ASCII character, but we can easily get around this by removing all of those right at the start. I also added your check against the empty string, but improving it to exit early if there is nothing left after filtering for ASCII characters, including the case that only spaces are left. I also split on all whitespace, not just single spaces, because this way multiple spaces are joined and all other whitespace characters have already been removed. I also use if not s instead of if s == "", because empty sequences are falsey and it sounds more like English this way.

from collections import Counter
from string import ascii_letters
from operator import itemgetter

ASCII_LETTERS = set(ascii_letters) | {" "}

def letter_count(s: str):
    """Return the word in s with the largest number of repeating letters

    >>> letter_count(s="Today, is the greatest day ever!")
    'greatest'
    >>> letter_count(s="!!!Today, is the >>>>greatest day ever!")
    'greatest'
    >>> letter_count(s="!!!Today, is the greatest >>>> day ever!")
    'greatest'
    >>> letter_count(s="!!!Today, is the greatest >>>> day ever xx!")
    'greatest'
    >>> letter_count(s="Today, is thee greatest day ever!")
    'thee'
    >>> letter_count(s="!!! >>>>")
    -1
    >>> letter_count(s="")
    -1
    >>> letter_count(s="abcd efg hijk")
    -1
    """
    s = "".join(c for c in s if c in ASCII_LETTERS)
    if not s.replace(" ", ""):
        return -1
    words = s.split()
    most_common_letters = (Counter(word).most_common(1)[0][1] for word in words)
    best_word = max(zip(most_common_letters, words), key=itemgetter(0))
    return best_word[1] if best_word[0] > 1 else -1

Note that the challenge design is not the best. Normally I would recommend against returning differing types from a function unless absolutely necessary. Having it return a string in most cases and sometimes an int can be dangerous. Better to at least return None, if you absolutely need a special value, or even better, just let the caller deal with an exception.

Otherwise your code looks quite alright. You have a docstring, tests and a main guard. I must say that your comments don't help me a lot, I personally prefer plain English or, even better, self-explanatory variable names. But naming things is hard, and you have already done a good enough job at that.