Procedural style Rock Paper Scissors game using Python 3

I recommend simplifying:

if decision == 'rock' or decision == 'paper' or decision == 'scissors':

to:

if decision.lower() in ('rock', 'paper', 'scissors'):

This will check whether the decision exists in a given tuple.

This helps simplifying the idea "If a variable contains one of these values".

Another example is "If variable x contains either 1, 3, or 5." Instead of coding it like this:

if x == 5 or x == 3 or x == 1

It can be simplified into:

if x in (1, 3, 5)

See this Gist to see my suggestion as a whole.


Time to learn how to DRY off your WET code!
(DRY -> "Don't Repeat Yourself"; WET -> "Write Everything Twice")
Note how the only difference between your two functions is a URL and a change in data, effectively "changing input results in changing output." Consider consolidating the two into one generic function that takes a variable url in as input and returns data which can be store in a variable of your choice.
var saleNumber1 = ""
var saleNumber2 = ""

override func viewDidLoad() {
    super.viewDidLoad()

    saleNumber1 = sale("http://example.com/folder/sale1.txt")
    saleNumber2 = sale("http://example.com/folder/sale2.txt")
}

func sale(path: String) -> String {
    let url = URL(string: path)!
    let saleNumber = ""
    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        guard let data = data else { return }
        saleNumber = "\(String(data: data, encoding: .utf8)!)"
    }

    task.resume()

    return saleNumber
}


You're right. The code can be improved. Here is how I'd write this.

We can extract post lookup into a method or before hook.
There is no need to check if Post was found. In production environment find will raise an ActiveRecord::RecordNotFound exception (I'm assuming you're using AR)
The destroy action can be a little more optimistic. When somebody unlikes the post, which cannot be found or which is not liked, we can just show the success. After all there is no like for the post.
We can use associations on models to write less.
AR understands relations in conditions. where(user: current_user) instead of where(user_id: current_user.id)
Use find_by instead of where().first

For example:

class LikesController < ApplicationController
  # before_action :find_post

  def create
    if post.likes.create(user: current_user)
      redirect_to post_redirect(post), :notice => 'Liked!'
    else
      redirect_to post_redirect(post), :alert => 'An error prevented you from liking this post!'
    end
  end

  def destroy
    post.likes.where(user: current_user).destroy_all
    redirect_to post_redirect(post), :notice => 'Unliked!'
  end

  private

  def post
    @post ||= Post.find(params[:id])
  end

  # def find_post
  #   @post = Post.find(params[:id])
  # end
end


It looks reasonable, but I don't see why you need to make the Proportional term a member of the class, it doesn't need to be saved, at best it might make sense to be able to query it with a get, but a set seems misleading.

I'd be reluctant to allow public setting of the Integral and Derivatives too, querying them might be useful, but letting users of the class set it seems odd.

Forcing the scaling by 1000.0 seems arbitrary and inflexible too, this would make sense to expose as a settable constant in my view.


You seem to have a good grasp of the concepts - this is looking pretty good for a first effort!
Those accessors (setAge() + getAge(), and setName() + getName()) are exactly equivalent to making the members age() and name() public, which would be simpler and clearer.  I'll assume that you're later going to add some code to check that the values are reasonable (don't allow negative ages, for example, nor empty or whitespace-only names).
Note also that the "get" accessors can be marked const, because they don't change the Person:
int getAge() const {
    return age;
}

std::string getName() const {
    return name;
}

In passing, I'll note that storing age as a member might not be the best design, especially when storing to a file that might be read back several years later.  If we store the year of birth, that's something that won't normally change, and we can always calculate the age from it.

The operator>>() is mostly what I'd expect.  You can chain the reading like this:
int age;
std::string name;
is >> age >> name;

However, there's a bug here.  is >> name will read up to the next whitespace, but our names can have whitespace in them.  We actually want to read up to the next newline, like this:
std::string name;
std::getline(is, name);

Another consideration here is that we don't want to update the person if we failed to read both values (otherwise, operator<<() could be a friend function, and read directly to person.age and person.name).  We can easily test whether the reads succeeded:
if (is) {
    person.setAge(age);
    person.setName(name);
}

When we have a reader, it's a good idea to have a matching writer that produces the same format.  That's very simple to write:
std::ostream& operator<<(std::ostream& os, const Person& person) {
    return os << person.getAge() << ' '
              << person.getName() << '\n';
}

Note that we have a reference to a const person here - the writer is promising not to modify person.

When reading the people in, we don't need to copy each line of text into a buffer (once we've fixed the bug I mentioned with reading names) - we can stream directly from the file stream into the person object:
std::vector<Person> people;

Person person;
while (mysamefile >> person) {
    people.push_back(std::move(person));
}

(The std::move() is a non-essential optimisation - it says we won't be using person until it's re-written using >>).

When displaying the people, we can make the code simpler using range-based for like this:
for (const Person& person: people) {
    person.printInfo();
    std::cout << "\n\n";
}

Of course, this is slightly different, because we're now printing the newlines after the last person too.  A good way to solve this is to print the newlines before each person, but not if it's the first person.  To do this, we can initially set our separator to be an empty string, and update after it's used:
auto separator = "";
for (const Person& person: people) {
    std::cout << separator;
    separator = "\n\n";

    person.printInfo();
}

A nice touch would be to allow printing to somewhere other than std::cout, by passing the stream as an argument to printInfo():
void printInfo(std::ostream& out = std::cout) const {
    out << "Name: " << name << '\n'
        << "Age: " << age << '\n';
}

Modified code
I've rearranged the headers a bit, to ease the process for when you want to separate the class definition from the test program.  I've changed the file read/write to work purely in memory for the test (I don't like tests that leave files lying about; using real files also increases fragility of the tests).  And I've added some validation of ages and names.
#include <algorithm>
#include <istream>
#include <ostream>
#include <stdexcept>
#include <string>

class Person
{
private:
    int age;
    std::string name;

public:
    void setAge(int age) {
        if (age < 0) {
            throw std::range_error("Negative age");
        }
        this->age = age;
    }

    int getAge() const {
        return age;
    }

    void setName(std::string name) {
        auto first_nonspace
            = std::find_if_not(name.begin(), name.end(),
                               [](unsigned char c){ return std::isspace(c); });
        if (first_nonspace == name.end()) {
            throw std::range_error("Invalid name");
        }
        this->name = name;
    }

    std::string getName() const {
        return name;
    }

    void printInfo(std::ostream& out) const {
        out << "Name: " << name << '\n'
            << "Age: " << age << '\n';
    }
};

std::istream& operator>>(std::istream& is, Person& person)
{
    int age;
    is >> age;

    std::string name;
    std::getline(is, name);

    if (is) {
        person.setAge(age);
        person.setName(name);
    }

    return is;
}

std::ostream& operator<<(std::ostream& os, const Person& person)
{
    return os << person.getAge() << ' '
              << person.getName() << '\n';
}

#include <iostream>
#include <sstream>
#include <vector>

int main()
{
    std::ostringstream myfile;
    myfile << "3 Baby\n";
    myfile << "48 Linus Torvalds\n";
    myfile << "62 Bill Gates\n";
    myfile << "115 Kane Tanaka\n";

    std::istringstream mysamefile(myfile.str());

    std::vector<Person> people;
    Person person;
    while (mysamefile >> person) {
        people.push_back(std::move(person));
    }

    auto separator = "";
    for (const Person& person: people) {
        std::cout << separator;
        separator = "\n\n";

        person.printInfo(std::cout);
    }
}


Cache with limited size; If full remove the oldest

Naming of data members: I would avoid duplicating the information that carries with the type. Can you think of something more meaningful?
Unsigned vs. signed integer for handling the size: as the maximum size is passed to the contructor as an int, static_cast<int>(_set.size()) should be safe. However, when it's foreseeable that you'll implement the class template using containers from the standard library (they all use std::size_t for their sizes), why not go with std::size_t for Cache, too?
Related to the above: always compile with warnings enabled. clang++ -Wall -pedantic -Wsign-conversion -Wextra -std=c++11 gives me

  warning: comparison of integers of different signs [...]

if(_set.size() == _maxSize){ // if set is 'full'

Again, as _maxSize is an int, this can be considered a non-issue in practice, but it's still somewhat brittle, if you change some implementation details later on.
You can only instantiate the Cache template when T mets the standard hash container requirements (i.e., a std::hash specialization is available as well as a comparison operator). To make your class template more reusable, consider adding template parameters that can be passed to std::unordered_set. If they have sensible defaults, you don't need to specify them most of the time.

template <class T, class Hash = std::hash<T>, class EqualTo = std::equal_to<T>>
class Cache {
    std::unordered_set<T, Hash, EqualTo> _set;
    // ...
};

When caching an object, you save it twice, one in _queue and once in _set. For small objects, the duplication might be acceptable, but what if T is large? Remember that std::unordered_map doesn't invalidate iterators/pointers upon insertion and removal of entries. Consider a std::queue of iterators into _set.
Passing T by value in bool add(T value) can be a reasonable choice as long as you std::move it when it's used the last time and T supports move semantics. In your case:

bool add(T value) {
   // ...
   _queue.push(value); // Don't move here
   _set.insert(std::move(value));  // ... but here!
}

You could also consider an overload set bool add(const T&) and bool add(T&&) instead as std::vector::push_back does for example.
When you worry about performance and you have varying max. cache sizes known at compile time, consider adding a non-type std::size_t template parameter to Cache. This way, you could specialize on smaller caches to e.g. use std::vector instead of std::unordered_map, which can be faster due fewer cache (ha!) misses. You need to do some benchmarking first though, and take different sizeof(T) into account.
A last note on performance: std::unordered_set was designed as a drop-in replacement for std::set. That's why it doesn't invalidate iterators/pointers into an instance, but that's also why it's not the fastest hash set. Of course, make sure to benchmark this properly, but you might want to have a look at some open address hash set, e.g. the one provided by abseil could be an option.


Python's str.isAlpha(), reimplemented without Unicode support

In this answer I am assuming that high performance is not needed

In general that approach is okay but I do not think that code is fulfilling the requirements. For example

ascii_letters("A2") == True
ascii_letters("") == None

I propose following steps:

Fix your algorithm (some unit tests would be great!)
Think about if is this really necessary to check whether the letter is in set of containing both lower and upper case letters.
Next, think about iteration over whole string: is this needed? There are functions in python which can check logical condition on whole list.
Why do you need to include string ? There is no need to override already existing variables.
Try to do pythonic one liner using all points above.


Prelude

  I've also seen that many in the C++ community seem to favor comments instead of descriptive variable/function names. Example:

int a = 3.14159265359; // pi with 11 decimal numbers

Not really, you should use meaningful names (and not only in C++). pi_eleven_decimal add nothing. Worst, it can be lying or source of trouble. What happen if later you wand to change  to take only 6 digit? You'll leave the lying name, or you'll change all occurrences, opening way to mistakes. The number of digits is an implementation detail which the user don't (have to) care. a isn't even better, you loose completely the sens of your variable. Here, I would name it simply pi.

Also, note that you used the wrong type. You used int so it will be truncated to 3 (plus get some compiler warnings). So, here you can use float pi = 3.14159265359,  double pi = 3.14159265359,  auto pi = 3.14159265359f or   auto pi = 3.14159265359 per example.

Coding idiomatically

Avoid using namespace std;

Putting using namespace std at the top of every program is a bad practice that can cause a lot of problems that are easy to avoid, most people are used to the prefix, and three letters aren't that hard to type.

Although it's "safe" to use it in some place (e.g. implementation files), as long as you aren't familiar with the features of c ++, try to avoid it.
It led to a world of name collisions. (best case)
It's source of silent errors and weird bugs. (worst case)
If typing std:: is so tedious for you, try to import only truncated namespaces. ( e.g. using namespace std::string;).
If importing nested namespaces still too awful for you, try to do it inside a restricted scope (e.g. a functions) and not in global scope.

Randomization

Avoid using rand for randomization. Instead use the  <random> header's facilities.  You have a lot of interesting post on SO:

How to generate a random number in C++?
Generate random numbers using C++11 random library
Random number generation in C++11: how to generate, how does it work?

And, if you want a higher randomness, you can try seeding like described here.

But in all case, you don't have to call four times your choses random function. Just call it once and get a number from 0 to 9999.

Then, don't forget to add leading 0's if number is lesser than 1000 (see below *).

Expressions and statements

Declare variables late as possible

Don't declare variables at the top of your functions or before you need it, try to keep their scope as small as possible.  Wait until you have a value to initialize it with.

Always initialize variable (as mush as possible)

Declaring variable and then initialize it much later is a source of mistakes that lead to undefined behavior. Instead, Initialize your variables in the declaration.

Don't be redundant in your conditions

As explained in the Core Guideline, comparing a boolean to true in a condition, not only is useless, but it's also much more verbose.

while (run_game == true) should be while (game_running) (look also at the name change, it's a lot more fluent).

run_game = (again == 'y') ? true : false; should be game_running = (again == 'y');

Input/Output

Don't use std::endl

Using std::endl send a '\n' and then flushes the output buffer. So std::endl is more expensive in performance. Instead, use '\n' and then, if you want to manually flush the stream, explicitly call std::flush.

Sanitize inputs

Don't think users will not try to break your program, they will do, even by mistake. Ensure user give something you expect. Here, you ask for a integer (not a string) and then, only after insuring correctness of the input (lower than 10000 and greater or equal to 0), use std::to_string (or std::stringstream) to convert it to a string. Don't forget to add leading 0's in case where inputed number is lower than 1000. (see below *)

You can also use the same method than linked above for the "play again" input.

Wrap code into functions and factorize

Don't put the code into the main, but instead, move the game's code into its own function.
You are outputting in many place and ask for input then read, in many other place. Try to wrap theses two behaviors into own functions (eg, print and ask_input). it will be easier, if later you want to modify the way you print or read inputs, to just modify one place.
(*) Also, you can have a function (or local lambda) to ensure secret and guess are 4 length, and add padding 0's otherwise.

Choose the right algorithm

Your two for-loop can be rewritten with std::mismatch for the first and  std::set_intersection for the second.

Just after, the cows calculation can be simplified with cow = std::max(0, find_count - bull);

Misc

There are still some refactoring possible, as moving the output "You win!" outside of the loop.

You can also remove the return statement from your main. Quoting C++ Standard :

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;


Good job on closing your Scanner! I see a lot of people forget/miss that.

An alternative, just for your information, is using try with resources so you don't have to worry about closing/remembering to close it. As an aside, in general, you want to use more meaningful names than just 'a' and 'b' in your code (Though I'm totally going to be a hypocrite in a second, names are hard).

I would consider using Scanner's nextInt() method, you're using integers, using nextLine() isn't intuitive. As it is, despite your request for two numbers(should specify integers), if a user actually tries to input two space delimited numbers it'll throw an error.

Here's what the start of your code would look like with these suggestions:

        int first;
        int second;
        System.out.print("Please enter 2 integers: ");

        try(Scanner in = new Scanner(System.in)) {
            first = in.nextInt();
            second = in.nextInt();
        }

As for the actual logic of your code, You can use the Euclidean algorithm

// Greatest Common Denominator
public int computeGCD(int a, int b) {
    return b == 0 ? a : computeGCD(b, a % b);
}


Making the code testable and tested

The first step to improve your code is to try to make it testable. By doing so, you usually have to deal with Separation of Concerns: in your case, you have to split the logic doing the output from the logic computing games. The easiest way to do so it to rewrite slightly the simulate_XXX functions to return values instead of writing them.

Once it it done, you can easily write tests for the function computing the games (in order to make this easier to implement, I've extracted out the randomising part as well).

At this stage, we have something like:

import random

def simulate_draw(teams):
    """Return the list of games."""
    if len(teams) % 2 == 0:
        return simulate_even_draw(teams)
    else:
        return simulate_odd_draw(teams)

def simulate_even_draw(teams):
    """Return the list of games."""
    matches = []
    dic = {}
    for i in range(len(teams)):
        dic[i] = teams[i]

    games = []
    arr1 = [i+1 for i in range(int(len(teams)/2))]
    arr2 = [i+1 for i in range(int(len(teams)/2), len(teams))][::-1]

    for i in range(len(teams)-1):
        arr1.insert(1, arr2[0])
        arr2.append(arr1[-1])
        arr2.remove(arr2[0])
        arr1.remove(arr1[-1])
        zipped = list(zip(arr1, arr2))
        games.append(zipped)
        zipped = []

    for game in games:
        for gm in list(game):
            r = gm # remove randomness for now - random.sample(gm, len(gm))
            a, b = dic[r[0]-1], dic[r[1]-1]
            matches.append((a, b))
            # print(a + ' plays ' + b)
    return matches

def simulate_odd_draw(teams):
    """Return the list of games."""
    matches = []
    dic = {}
    for i in range(len(teams)):
        dic[i] = teams[i]
    dic[i+1] = ''
    games = []
    arr1 = [i+1 for i in range(int((len(teams)+1)/2))]
    arr2 = [i+1 for i in range(int((len(teams)+1)/2), len(teams)+1)][::-1]
    for i in range(len(teams)):
        arr1.insert(1, arr2[0])
        arr2.append(arr1[-1])
        arr2.remove(arr2[0])
        arr1.remove(arr1[-1])
        zipped = list(zip(arr1, arr2))
        games.append(zipped)
        zipped = []
    for game in games:
        for gm in list(game):
            r = gm # remove randomness for now - random.sample(gm, len(gm))
            if len(teams)+1 not in r:
                a, b = dic[r[0]-1], dic[r[1]-1]
                matches.append((a, b))
                # print(a + ' plays ' + b)
    return matches

def displays_simulated_draws(teams):
    """Print the list of games."""
    for gm in simulate_draw(teams):
        a, b = random.sample(gm, len(gm))
        print(a + ' plays ' + b)

def test_simulate_draw():
    """Small tests for simulate_draw."""
    # TODO: Use a proper testing framework
    TESTS = [
        ([], []),
        (['A'], []),
        (['A', 'B', 'C', 'D'], [('A', 'C'), ('D', 'B'), ('A', 'B'), ('C', 'D'), ('A', 'D'), ('B', 'C')]),
        (['A', 'B', 'C', 'D', 'E'], [('A', 'E'), ('B', 'C'), ('A', 'D'), ('E', 'C'), ('A', 'C'), ('D', 'B'), ('A', 'B'), ('D', 'E'), ('B', 'E'), ('C', 'D')]),
    ]
    for teams, expected_out in TESTS:
        # print(teams)
        ret = simulate_draw(teams)
        assert ret == expected_out

if __name__ == '__main__':
    test_simulate_draw()
    displays_simulated_draws(['A', 'B', 'C', 'D'])

Now we can start improving the code in a safer way.

Remove what's not required

dic[i+1] = '' is not required, we can remove it.

Also, resetting zipped to the empty string is not required, we can remove it. Maybe we could get rid of zipped altogether.

Finally, we call for gm in list(game) when game is already a list. We can remove the call to list.

Loop like a native

I highly recommend Ned Batchelder's talk "Loop like a native" about iterators. One of the most simple take away is that whenever you're doing range(len(iterable)), you can probably do things in a better way: more concise, clearer and more efficient.

In your case, we could have:

for i in range(len(teams)):
    dic[i] = teams[i]

replaced by

for i, team in enumerate(teams):
    dic[i] = team

And we could do:

for _ in teams:

instead of

for i in range(len(teams))

(Unfortunately, this can hardly be adapted to the "even" situation)

Note: "_" is a usual variable names for values one does not plan to use.

Dict comprehension

The dictionnary initiation you perform via dict[index] = value in a loop could be done using the Dictionnary Comprehension syntactic sugar.

Instead of:

dic = {}
for i, team in enumerate(teams):
    dic[i] = team

we you can write:

dic = {i: team for i, team in enumerate(teams)}

Now it is much more obvious, it also corresponds to:

dic = dict(enumerate(teams))

Finally, we can ask ourselves how we use this dictionnary: the answer is "to get the team at a given index". Do we really need a dictionnay for this ? I do not think so. We can get rid of the dic variable and use teams directly.

At this stage, we have:

import random

def simulate_draw(teams):
    """Return the list of games."""
    if len(teams) % 2 == 0:
        return simulate_even_draw(teams)
    else:
        return simulate_odd_draw(teams)

def simulate_even_draw(teams):
    """Return the list of games."""
    matches = []
    games = []
    half_len = int(len(teams)/2)
    arr1 = [i+1 for i in range(half_len)]
    arr2 = [i+1 for i in range(half_len, len(teams))][::-1]
    for i in range(len(teams)-1):
        arr1.insert(1, arr2[0])
        arr2.append(arr1[-1])
        arr2.remove(arr2[0])
        arr1.remove(arr1[-1])
        games.append(list(zip(arr1, arr2)))
    for game in games:
        for gm in game:
            r = gm # remove randomness for now - random.sample(gm, len(gm))
            a, b = teams[r[0]-1], teams[r[1]-1]
            matches.append((a, b))
            # print(a + ' plays ' + b)
    return matches

def simulate_odd_draw(teams):
    """Return the list of games."""
    matches = []
    games = []
    half_len = int((len(teams)+1)/2)
    arr1 = [i+1 for i in range(half_len)]
    arr2 = [i+1 for i in range(half_len, len(teams)+1)][::-1]
    for i in range(len(teams)):
        arr1.insert(1, arr2[0])
        arr2.append(arr1[-1])
        arr2.remove(arr2[0])
        arr1.remove(arr1[-1])
        games.append(list(zip(arr1, arr2)))
    for game in games:
        for gm in game:
            r = gm # remove randomness for now - random.sample(gm, len(gm))
            if len(teams)+1 not in r:
                a, b = teams[r[0]-1], teams[r[1]-1]
                matches.append((a, b))
                # print(a + ' plays ' + b)
    return matches

def displays_simulated_draws(teams):
    """Print the list of games."""
    for gm in simulate_draw(teams):
        a, b = random.sample(gm, len(gm))
        print(a + ' plays ' + b)

def test_simulate_draw():
    """Small tests for simulate_draw."""
    # TODO: Use a proper testing framework
    TESTS = [
        ([], []),
        (['A'], []),
        (['A', 'B', 'C', 'D'], [('A', 'C'), ('D', 'B'), ('A', 'B'), ('C', 'D'), ('A', 'D'), ('B', 'C')]),
        (['A', 'B', 'C', 'D', 'E'], [('A', 'E'), ('B', 'C'), ('A', 'D'), ('E', 'C'), ('A', 'C'), ('D', 'B'), ('A', 'B'), ('D', 'E'), ('B', 'E'), ('C', 'D')]),
    ]
    for teams, expected_out in TESTS:
        # print(teams)
        ret = simulate_draw(teams)
        assert ret == expected_out

if __name__ == '__main__':
    test_simulate_draw()
    displays_simulated_draws(['A', 'B', 'C', 'D'])

The right tool for the task

The part:

    arr2.remove(arr2[0])
    arr1.remove(arr1[-1])

could/should probably be written with pop:

    arr2.pop(0)
    arr1.pop()

And now, these line can be merged with arrXX.append(arrYYY[ZZ]):

for i in range(len(teams)-1):
    arr1.insert(1, arr2.pop(0))
    arr2.append(arr1.pop())
    games.append(list(zip(arr1, arr2)))

Removing useless steps

A loop is used to fill an array. Another one is used to iterate over the array. We could try to use a single loop to do everything (disclaimer: this is not always a good idea as far as readability goes).

This removes the need for a few calls to list.

At this stage, we have:

def simulate_even_draw(teams):
    """Return the list of games."""
    matches = []
    half_len = int(len(teams)/2)
    arr1 = [i+1 for i in range(half_len)]
    arr2 = [i+1 for i in range(half_len, len(teams))][::-1]
    for i in range(len(teams)-1):
        arr1.insert(1, arr2.pop(0))
        arr2.append(arr1.pop())
        for gm in zip(arr1, arr2):
            matches.append((teams[gm[0]-1], teams[gm[1]-1]))
    return matches

def simulate_odd_draw(teams):
    """Return the list of games."""
    matches = []
    half_len = int((len(teams)+1)/2)
    arr1 = [i+1 for i in range(half_len)]
    arr2 = [i+1 for i in range(half_len, len(teams)+1)][::-1]
    for i in range(len(teams)):
        arr1.insert(1, arr2.pop(0))
        arr2.append(arr1.pop())
        for gm in zip(arr1, arr2):
            if len(teams)+1 not in gm:
                matches.append((teams[gm[0]-1], teams[gm[1]-1]))
    return matches

Better indices

You generate a list of indices using i+1 and then use val - 1 when you use them. You can make your life easier twice.

Iterable unpacking

Instead of using indices to get elements from an iterable with a know number of elements, you can use iterable unpacking.

You'd get

def simulate_even_draw(teams):
    """Return the list of games."""
    half_len = int(len(teams)/2)
    arr1 = [i for i in range(half_len)]
    arr2 = [i for i in range(half_len, len(teams))][::-1]
    matches = []
    for i in range(len(teams)-1):
        arr1.insert(1, arr2.pop(0))
        arr2.append(arr1.pop())
        for a, b in zip(arr1, arr2):
            matches.append((teams[a], teams[b]))
    return matches

def simulate_odd_draw(teams):
    """Return the list of games."""
    half_len = int((len(teams)+1)/2)
    arr1 = [i for i in range(half_len)]
    arr2 = [i for i in range(half_len, len(teams)+1)][::-1]
    matches = []
    for i in range(len(teams)):
        arr1.insert(1, arr2.pop(0))
        arr2.append(arr1.pop())
        for a, b in zip(arr1, arr2):
            if len(teams) not in (a, b):
                matches.append((teams[a], teams[b]))
    return matches

True divisions

Instead of using "/" and convert the float result to int, you can use "//" which is an integer division.

Other way to compute indices

We could write something like:

indices = list(range(len(teams)))
half_len = len(indices)//2
arr1 = indices[:half_len]
arr2 = indices[:half_len-1:-1]

and

indices = list(range(len(teams)+1))
half_len = len(indices)//2
arr1 = indices[:half_len]
arr2 = indices[:half_len-1:-1]

Altough, if we don't care about order, we could use the more direct:

arr1 = indices[:half_len]
arr2 = indices[half_len:]

Remove the duplicated logic

Don't repeat yourself is a principle of software development that you could easily apply here. Indeed, we have 2 functions that look very similar.

This is trickier than expected and I have to go. I may continue another day.

Batteries included

The Python standard library contains many useful things. Among them, we have the very interesting module itertools which itself contains combinations which is what you want.


1. Review

The code returns the wrong result when the graph has no Eulerian cycle. For example, if we give it the graph {0:[1], 1:[]} then the code returns the tuple (0, 0), which does not correspond to any legal path in the graph. It would be better to raise an exception if the graph has no Eulerian cycle.

I know that the problem description says that the graph has an Eulerian cycle, but in real life data is sometimes incorrect and it is a good idea to write code so that it is robust.
Similarly, the code goes into an infinite loop if the graph is disconnected:

>>> eulerian_cycle_1({0:[0], 1:[1]}, 2)
^C
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr188627.py", line 21, in eulerian_cycle_1
    if graph[cur]:
KeyboardInterrupt

It would be more robust to raise an exception in this case.
The code doesn't work if the graph doesn't have a node 0:

>>> eulerian_cycle_1({1:[1]}, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr188627.py", line 8, in eulerian_cycle_1
    choices = graph[cur]
KeyError: 0

It would be more robust to pick a starting node from the graph.
The number of edges can be easily computed from the graph like this:

sum(map(len, graph.values()))

so it would simplify the interface if the code only required the graph, and computed the number of edges itself.
But in fact there is no need to know the number of edges: you can exit the main loop if the search along the cycle for a node with an edge fails.

2. Performance

The problem with the performance is that whenever it reaches a point where the cycle cannot be extended, the code searches along the cycle to try to find a node which still has edges. In the worst case, a graph with \$n\$ nodes and \$O(n)\$ edges might have \$Θ(n)\$ points where the cycle cannot be extended, and at each of these points the code will have to search \$Θ(n)\$ nodes in the cycle. In this case the overall runtime will be \$Θ(n^2)\$, that is quadratic.

The worst case arises in graphs like this:

and we can build these graphs systematically if we define get_graph like this:

def get_graph(n):
    "Return a worst-case graph with n nodes and 2n edges."
    return {i:[min(i + 1, n - 1), max(i - 1, 0)] for i in range(n)}, 2 * n

Now, if we increase the size of the graph by 10 times, it takes 100 times as long to find an Eulerian cycle:

>>> from timeit import timeit
>>> timeit(lambda:eulerian_cycle_1(10**3), number=1)
0.08308156998828053
>>> timeit(lambda:eulerian_cycle_1(10**4), number=1)
8.778133336978499

To make the runtime linear in the number of edges, we have to avoid traversing or rotating the whole cycle, except possibly once at the end. There are two approaches we might take:

Represent the cycle as a linked list (not a deque) so that we can efficiently insert new items at any point, without having to rotate.
Don't try to join the cycles as we go along, but instead keep a collection of cycles and stitch them together at the end using a depth-first search.

I'll show here how to implement the first approach (see this answer for how to implement the second approach).

Python doesn't provide a linked list implementation, but we can easily make one:

class Link:
    "A link in a linked list."
    def __init__(self, node):
        self.node = node
        self.next = self

    def insert(self, link):
        "Insert link after self in the linked list and return link."
        link.next = self.next
        self.next = link
        return link

Now it's just a matter of keeping track of the Link objects corresponding to the nodes in the graph that still have edges, so that we can efficiently find the place to continue extending the cycle.

def eulerian_cycle_2(graph):
    """Return an Eulerian cycle in graph, if there is one, as a list of
    nodes. If there are no Eulerian cycles, raise ValueError.

    """
    # Take a copy of the graph so that we can modify it.
    graph = {k:v[:] for k, v in graph.items()}

    # Start at any node in the graph that has an edge.
    node = next(node for node, neighbours in graph.items() if neighbours)
    choices = graph[node]
    start = cur = Link(node)

    # Map from node we've visited (that still has edges) to a link for
    # that node in the linked list.
    visited = {}

    while True:
        # Extend current cycle until no more edges can be followed.
        cycle_start = node
        while choices:
            visited[node] = cur
            node = choices.pop()
            choices = graph[node]
            cur = cur.insert(Link(node))
        if node != cycle_start:
            raise ValueError("graph has no Eulerian cycle")

        # Find a visited node which still has edges, if any.
        while visited:
            node, cur = visited.popitem()
            choices = graph[node]
            if choices:
                break
        else:
            break

    if any(graph.values()):
        raise ValueError("graph has no Eulerian cycle")

    # Reconstruct cycle by following linked list.
    cycle = []
    cur = start
    while True:
        cycle.append(cur.node)
        cur = cur.next
        if cur == start:
            break
    return cycle

We should check that the performance is linear in the number of edges. Here you can see that when the graph is 10 times as big, the runtime is roughly 10 times as long, as required:

>>> timeit(lambda:eulerian_cycle_2(get_graph(10**3)[0]), number=1)
0.0049093629932031035
>>> timeit(lambda:eulerian_cycle_2(get_graph(10**4)[0]), number=1)
0.045048179978039116
>>> timeit(lambda:eulerian_cycle_2(get_graph(10**5)[0]), number=1)
0.42420267598936334
>>> timeit(lambda:eulerian_cycle_2(get_graph(10**6)[0]), number=1)
4.303449199011084

For comparison, by extrapolating the timings from earlier in this answer, we would have expected eulerian_cycle_1 to take about 24 hours to find a cycle in the worst-case graph with \$10^6\$ notes.


Homework / toy program - character matching

Your algorithm looks alright

The algorithmic idea seems correct and fit for meeting the stated requirements. There are also no unreasonable constant factors or excessive resource usage just to meet the required asymptotic complexity. Overall, I think you did the right thing.

Try to nail down the requirements

I'm not entirely sure what your function is supposed to do. Should it only take into account letters or also other characters like white-space and punctuation? Should it be case-sensitive or insensitive? Either choice is reasonable but one has to be made.

The following item is related to this.

Know your range

You're using an array from 0 (inclusive) to z (exclusive). As others have already pointed out in comments, this means an out of bounds access if the character z occurs in your input which is almost certainly a bug. Adding 1 to the array size might seem to fix the issue but I'd suggest to look more closer at the range of valid inputs.

First, you have to define your range of valid characters. This might be the whole range of the char data type. Which is implementation-defined so you should use the CHAR_MIN and CHAR_MAX macros defined in <limits.h>. (Your input actually can never contain the value 0 because you'd treat it as the sentinel value but wasting that one index seems reasonable.)

If your input range is smaller than that (for example, only ASCII characters or only alphanumeric characters), you should do two things.

Verify that the input is in range and do some reasonable error handling if it is not. If you decide to give your function a narrow contract, invalid inputs mean undefined behavior and you can use the assert macro that is only active in debug builds and gain a little performance in release builds.
Subtract the lowest permissible character from the character at hand to get the index in your array.

For the ASCII character set, the range is [0, 128) and [32, 126) for the printable sub-set. (It would probably be more readable to use ' ' (space) and '~' + 1 in code instead of these magic numbers.)

Be warned that the C standard doesn't require that the character set is ASCII and the ASCII math might be wrong for other encodings. Some encodings also have multi-byte characters and those will cause you never-ending nightmares if you wish to handle them correctly.

Beware of integral promotion

If your input can be the full range of the char data type, there is a nasty culprit here. The C standard doesn't specify whether char is signed or unsigned. If your code is used on an implementation where char is signed, the bytes 0x80 … 0xff will have negative numeric values.

If you compute your indices by subtracting CHAR_MIN, you'll be fine because it will make those values positive again. If you, however, expect values in the range [0, 256) you'll get bad surprises. The usual way to deal with this is to explicitly cast to unsigned char before using the value.

Consider saving some space – or maybe don't

You're currently using an int to count the frequency of a character. This is likely a reasonable choice but I'd like to challenge you to justify it.

If you want to be on the absolute safe side, a size_t will guarantee that you can even deal with the largest possible array, filled with the same character. If you go for size_t, be aware that it is an unsigned type so you cannot check for “less than zero” after the subtraction but have to check for “equal to zero” before subtracting.

If you want to preserve space (and thus get lower cache usage), you might want to reach for a smaller data type but you'll get undefined behavior if its range is exceeded.

Any decision can be justified but you should be aware of its implications. If your function makes assumptions about the maximum frequency of a character, its documentation should state this limitation.

Separate different concerns into different functions

You have put all code into main. This is obviously not a very modular design and hard to unit-test. I'd recommend that you break your logic into at least three functions.

One function that takes two character arrays and checks whether the former contains all characters from the latter. It doesn't print anything but returns a boolean value.
One function that converts a boolean value into a pointer to a statically allocated character array with a human-readable text. This can be as simple as return value ? "true" : "false";.
One function that obtains (or hard-codes) the input, calls the first function to get the result and then prints the human-readable representation obtained from the second function. (You can leave this logic in main if that's all your program does.)


K’th SmallestElement in Unsorted Array in python

There is no need to have a cumulative array. Using append repeatedly is also no such a great idea, because of the cost of memory reallocation.

def kthSmallest(lst, k):
    if k > len(lst):
        return None
    int_counts = [0 for x in range(8001)]
    for i in range(len(lst)):
        int_counts[lst[i] - 1000] += 1
    cumulative = 0
    for i in range(len(int_counts)):
        cumulative += int_counts[i]
        if cumulative >=  k:
            return i + 1000


Should I put default values of attributes on the prototype to save space?

related jsperf http://jsperf.com/12312412354

Well this is a really bad idea. Objects are always considered having different class if they don't have exactly the same set of properties in the same order. So
a function that accepts these objects will in best case be polymorphic and in worst case megamorphic all the while you are thinking
you are passing it same class of objects. This is fundamental to all JS engines although the specifics that follow focus on V8.

Consider:

function monomorphic( a ) {
    return a.prop + a.prop;
}

var obj = {prop: 3};
while( true ) {
    monomorphic( obj );
}

Now, since the passed object a always has the same class, we will get really good code:

    ; load from stack to eax
15633697    23  8b4508         mov eax,[ebp+0x8]
    ;; test that `a` is an object and not a small integer
1563369A    26  f7c001000000   test eax,0x1
156336A0    32  0f8485000000   jz 171  (1563372B) ;;deoptimize if it is not
    ;; test that `a`'s class is as expected
156336A6    38  8178ffb9f7902f cmp [eax+0xff],0x2f90f7b9
156336AD    45  0f857d000000   jnz 176  (15633730) ;;deoptimize if it is not
    ;; load a.prop into ecx, as you can see it's like doing struct->field in C
156336B3    51  8b480b         mov ecx,[eax+0xb]
    ;; this will untag the tagged pointer so that integer arithmetic can be done to it
156336B6    54  d1f9           sar ecx,1
    ;; perform a.prop + a.prop
    ;; note that if it was a.prop + a.prop2
    ;; then it wouldn't need to do all those checks again
    ;; so for one time check inside the function we can load all the properties
    ;; quickly
156336B8    56  03c9           add ecx,ecx

Notice what happened here, V8 saw that we always pass the same class of object to the function
monomoprhic and generated really tight code that assumes we will always get that class of object
in the future as well.

Now let's do:

function polymorphic( a ) {
    return a.prop + a.prop;
}

var obj = {prop: 3};
var obj2 = {prop: 3, prop2: 4};
while( true ) {
    polymorphic( Math.random() < 0.5 ? obj : obj2 );
}

Now the function must consider 2 different classes of objects. The classes are different but similar enough
that the client code can stay as it is as both classes contain a field prop.

Let's see:

    ; load from stack to eax
04C33E17    23  8b4508         mov eax,[ebp+0x8]
    ;; test that `a` is an object and not a small integer
04C33E1A    26  f7c001000000   test eax,0x1
04C33E20    32  0f8492000000   jz 184  (04C33EB8) ;; deoptimize if not
    ;; test that `a`'s class is one of the expected classes
04C33E26    38  8178ffb9f7401c cmp [eax+0xff],0x1c40f7b9
04C33E2D    45  0f840d000000   jz 64  (04C33E40) ;; if it is, skip the second check and go to the addition code
    ;; otherwise check that `a`'s class is the second one of the expected classes
04C33E33    51  8178ff31f8401c cmp [eax+0xff],0x1c40f831
04C33E3A    58  0f857d000000   jnz 189  (04C33EBD) ;; deoptimize if not
    ;; load a.prop into ecx
    ;; if you are still reading this you will probably notice that this
    ;; is actually relying on the fact that both classes declared the prop field
    ;; first
04C33E40    64  8b480b         mov ecx,[eax+0xb]
    ;; this will untag the tagged pointer so that integer arithmetic can be done to it
04C33E43    67  d1f9           sar ecx,1
    ;; do the addition
04C33E45    69  03c9           add ecx,ecx

Ok so the situation is still pretty good but here we are relying on the fact that properties are in same order
and that there are only 2 different classes.

Let's do the same in different order so that V8 can't use the same instruction (mov ecx,[eax+0xb]) for both objects:

function polymorphic( a ) {
    return a.prop + a.prop;
}

var obj = {prop: 3};
var obj2 = {prop2: 4, prop: 3};
while( true ) {
    polymorphic( Math.random() < 0.5 ? obj : obj2 );
}

And:

06C33E84    36  8b4508         mov eax,[ebp+0x8]
    ;; small integer check
06C33E87    39  f7c001000000   test eax,0x1
06C33E8D    45  0f84d3000000   jz 262  (06C33F66)
    ;; class check 1
06C33E93    51  8178ffb9f75037 cmp [eax+0xff],0x3750f7b9
06C33E9A    58  7505           jnz 65  (06C33EA1)
06C33E9C    60  8b480b         mov ecx,[eax+0xb]
06C33E9F    63  eb10           jmp 81  (06C33EB1)
    ;; class check 2
06C33EA1    65  8178ff31f85037 cmp [eax+0xff],0x3750f831
06C33EA8    72  0f85bd000000   jnz 267  (06C33F6B)
06C33EAE    78  8b480f         mov ecx,[eax+0xf]

06C33EB1    81  f6c101         test_b cl,0x1
06C33EB4    84  0f851e000000   jnz 120  (06C33ED8)
06C33EBA    90  d1f9           sar ecx,1
06C33EBC    92  89ca           mov edx,ecx
06C33EBE    94  03d1           add edx,ecx

Ok just as expected, just using different offsets depending on the class.

So you can see where this is going, if you end up with 10 different classes then you will
just get 30 instructions (instead of 3) whenever a function will need to lookup a property. Which is still
much better than a hash table (100s of instructions?) lookup.

Well no, turns out there is a limit of 4 different classes
and then you go into megamorphic mode.

So with this, we should see radically different code output if we use 5 or more different classes:

function megamorphic( a ) {
    return a.prop + a.prop;
}

var objs = [
    {prop: 3},
    {prop3: 4, prop: 3, prop2: 4},
    {prop4: 4, prop2: 4, prop: 3, prop5: 6},
    {prop: 3, prop12: 6},
    {prop7: 15, prop30: 12, prop314: 4, prop34: 15, prop: 3}
];

while( true ) {
    var index = Math.random() * objs.length | 0;
    megamorphic( objs[index] );
}

Indeed:

3D3342E7    39  8b5508         mov edx,[ebp+0x8]
3D3342EA    42  b9f5e2a115     mov ecx,15A1E2F5
3D3342EF    47  e84c6ffeff     call LoadIC_Initialize  (3D31B240)
3D3342F4    52  8945ec         mov [ebp+0xec],eax
3D3342F7    55  8b75f0         mov esi,[ebp+0xf0]
3D3342FA    58  8b5508         mov edx,[ebp+0x8]
3D3342FD    61  b9f5e2a115     mov ecx,15A1E2F5
3D334302    66  e8396ffeff     call LoadIC_Initialize  (3D31B240)
3D334307    71  8b4dec         mov ecx,[ebp+0xec]
3D33430A    74  f6c101         test_b cl,0x1
3D33430D    77  0f8527000000   jnz 122  (3D33433A)
3D334313    83  d1f9           sar ecx,1
3D334315    85  89c2           mov edx,eax
3D334317    87  f6c201         test_b dl,0x1
3D33431A    90  0f8546000000   jnz 166  (3D334366)
3D334320    96  d1fa           sar edx,1
3D334322    98  03d1           add edx,ecx

That actually looks a lot like code that loads properties from objects that are in hash table mode. Is it fast? Unfortunately jsperf is down now
so you have to run it yourself with code here:

Megamorphic 492
Monomorphic 30

So the same function body ran 15 times faster because the object passed to it always had the same class. It is also hard to predict if you will actually save memory
if all those 10000 objects allocate a different class for instance.

It is also complicated to really look at all the downsides but having optional properties is one of those things that it is easy to say is very bad.


As you've taken most of our advice to heart, there isn't much to complain on stylewise, but a few pointers from my personal opinion:

If possible, avoid doing function call for constants, and avoid redefining constants – You set FULL_ENGLISH_ALPHABET = FULL_ENGLISH_ALPHABET + FULL_ENGLISH_ALPHABET.lower(). Both the redefining of a constant, and doing the lower() on previous version could and should be avoided in my opinion. Just set it to the correct version directly, you know in advance what it is going to be.
Write out variable names – Type out in full the tran_tab variable, and since you're not going to change it, uppercase it, i.e make it ENGLISH_TO_ENTEAN which also encompasses the use instead of just translation_table which is kind of meaningless.
Add docstrings to functions and module – You could/should add documentation to your module, to help understand what this module does

Extend to translate both ways

A natural extension now is to extend it so that it can translate both ways. In addition to the to_english(text) function, I would also make a translate_to(language, text) function so that you can make functions which can choose which way you want to translate.

Look into unit testing and/or doctest

Another possible extension is to add testing of your methods, to ensure proper translation and handling of different cases. Loads of alternatives exists, but I'm going to point you towards unittest and doctest. Both of these are included in vanilla Python. The former can be useful for slightly more complex cases, but I've opted for doctest in my review, as it has a nice side effect of displaying with the docstrings how to use the different functions.

Doctest can be invoked on your module in a variety of ways, but the two versions I've been using the most are either to call it direcly from the command line using python -m doctest my_module.py or through calling a simple do_doctest() function from the main code. The former doesn't require anything besides the actual docstrings, and if you use python -m doctest -v my_module.py you get to see every test it performs (and not only failing tests) and the summary.

Try it out with code below, and change some of the stuff related to >>> lines, and response on following line.

Make main() useful

I know I was the one proposing the main() function you're using, but now that it is maturing, I would make it into a loop asking for which language to translate to and text to translate. This way you'll get a meaning full script to run, in addition to a meaningful module to use.

Note how I used a little trick to 'alias' input = raw_input if in Python 2, so I wouldn't need to do the if PY2 all over my script. Consider also looking into an extra module handling Python 2 and Python 3 like the six module.

Revamped code

Here is my version implementing all of the above suggestions:

"""
In the anime, "The Devil is a part timer", the language in Ente Isla is
called Entean, which is basically most of the consonants in the English
alphabet switched around. Vowels and the consonants 'L', 'N', 'Q' keep
their original position, whilst the rest is simply reversed.

The full alphabet then is that each letter of ABCDEFGHIJKLMNOPQRSTUVWXYZ
is changed to AZYXEWVTISRLPNOMQKJHUGFDCB. For example, 'human' is 'tupan',
and 'world' becomes 'foklx'. Other characters are kept as is.

Some typical usage situation offered by module:

    >>> to_entean("Text, to be translated, into to Entean!")
    'Hedh, ho ze hkanjlahex, inho ho Enhean!'

    >>> to_english("Tupan foklx!")
    'Human world!'

    >>> translate_to('entean', 'Kind of cool')
    'Rinx ow yool'
"""

import sys

# Set to True if Python major version is 2
PY2 = sys.version_info[0] == 2

if PY2:
    from string import maketrans

    # Alias input to simplify input routines
    input = raw_input
else:
    maketrans = str.maketrans

ENGLISH_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
ENTEAN_ALPHABET = "AZYXEWVTISRLPNOMQKJHUGFDCBazyxewvtisrlpnomqkjhugfdcb"

ENGLISH_TO_ENTEAN = maketrans(ENGLISH_ALPHABET, ENTEAN_ALPHABET)
ENTEAN_TO_ENGLISH = maketrans(ENTEAN_ALPHABET, ENGLISH_ALPHABET)

def to_entean(text):
    """Return text translated from English to Entean.

    >>> to_entean("Some random text to translate, with punctuation chars!")
    'Jope kanxop hedh ho hkanjlahe, fiht munyhuahion ytakj!'

    >>> to_entean(ENGLISH_ALPHABET) == ENTEAN_ALPHABET
    True
    """
    return text.translate(ENGLISH_TO_ENTEAN)

def to_english(text):
    """Return text translated from English to Entean.

    >>> to_english("Noh jo eajc ho unxekjhanx, kivth?")
    'Not so easy to understand, right?'

    >>> to_english(ENTEAN_ALPHABET) == ENGLISH_ALPHABET
    True
    """
    return text.translate(ENTEAN_TO_ENGLISH)

ALL_TRANSLATIONS = {
    'entean' : to_entean,
    'english' : to_english
    }

def translate_to(language, text):
    """Return translated text according to mode.

    >>> translate_to('english', 'Tupan foklx')
    'Human world'

    >>> translate_to('entean', 'Human world')
    'Tupan foklx'

    >>> translate_to('norwegian', 'This will fail!')
    Traceback (most recent call last):
    ValueError: Unknown translation language.
    """

    translate_function = ALL_TRANSLATIONS.get(language, None)

    if translate_function:
        return translate_function(text)
    else:
        raise ValueError("Unknown translation language.")

def do_doctest():
    """Utility method to run all doctests from within script."""

    import doctest
    doctest.testmod()

def main():
    """Loop asking for language and text to translate."""

    print(' Translation utility '.center(72, '*'))
    print('\nLegal languages: {}'.format(', '.join(ALL_TRANSLATIONS)))

    while True:
        to_language = input("Language to translate to (or 'quit'): ").lower().strip()

        if to_language == 'quit':
            break

        text = input("Enter text to translate: ")

        print('Translated text: {}'.format(translate_to(to_language, text)))

if __name__ == "__main__":
    do_doctest()
    main()


Implementation of a linear congruential generator

Your mask value M is gaining you nothing, since the types for this_seed and M are the same and you have every bit in M set to 1.  Your comment for next is wrong; it can return 264-1 (i.e., all bits set).  The correct range can be stated as either [0, 2 ^ 64 - 1] or [0, 2 ^ 64).  This in turn can cause your get functions to return a value larger than expected (1.0, x, or b).

Where did you get the values for the A and B constants?  I've not looked to see if they are appropriate.


Coding convention when using differential inheritance

I see a conceptual issue with this approach: it is nice to inherit from objects, but these entities are not the "real" object. In other words, there is no much sense in using them outside of initialization code. If you need new [Cc]ar then it will not be wise to take any car that is nearby and just modify it and enjoy numerous side effects - you probably need some "etalon" of cars. The Car.

To be honest, I frequently have an intention to use only factory methods in JavaScript and not use the operator new at all. But then I look on how many should I rewrite for that and give up because I do not see the real benefits from this approach - it is not a big task to rename the constructor Something to factory method createSomething and replace it within the code, but what is next?


2 suggestions:

do you really need a LIKE, can't you use an equality?
can't you try to first filter the XML and then (but still in the same query) going up with the needed joins to retrieve what you need ?

Also your performances obviously depend on the size of various tables and on the available indexes. Your RDBM should be able to let you know which indexes it will use for your above query and based on that you may find you are missing some. Filtering on dates, xml, and LIKE patterns has a cost.


Submit form additions or changes using AJAX, and display result

I think most of the code duplication can be taken care of by simply creating success and failure functions to handle the ajax response for both your forms. Additionally, if you're only sometimes going to pass a value to options in the ajaxHandler function, you should check if it's undefined.

// generic ajax caller
function ajaxHandler(url, data, options) {
  var ajaxOptions = {
    type: 'POST',
    url: url,
    dataType: 'json',
    data: data,
    success: function(data) {
      return data;
    },
    error: function(xhr, textStatus, error) {
      return error;
    }
  };
  return (options === undefined) ? $.ajax(ajaxOptions) : $.ajax($.extend(ajaxOptions, options));
};

function success(result, form, reset) {
  $('.field-error, .success, .error').remove();
  if (result.errorType == "fieldErrors") {
    // handle field errors
    $.each(result.data, function(key, value) {
      console.log(key, value);
      $(' ' + value.msg + '').insertBefore('#' + value.param);
    });
  } else if (result.errorType == "formErrors") {
    // handle form errors
    $('
' + result.message + '
').insertBefore(form);
  } else {
    // success
    if (reset) {
      form[0].reset();
    }
    $('
' + result.message + '
').insertBefore(form);
  }
}

function failure(form) {
  $('
Error connecting server
').insertBefore(form);
}

// This code handles course submission form
$('#add-course').on('submit', function(e) {
  e.preventDefault();
  var form = $(this);
  ajaxHandler(form.url, form.serialize())
    .then(function(result) {
      console.log('#############');
      success(result, form, false);
    })
    .fail(function(error) {
      failure(form);
    });
});

// Here is code which handles update course form
$('#change-course').on('submit', function(e) {
  e.preventDefault();
  var form = $(this);
  ajaxHandler(form.url, form.serialize())
    .then(function(result) {
      success(result, form, true);
    })
    .fail(function(error) {
      failure(form);
    });
});


You are running your select twice and saving an unused Average from your Select-Object

gci -r -ea Si `
| group { if ($_.PSIsContainer) {""} else {$_.Extension} } `
| sort Count -desc `
| ft Name, Count, @{n="SizeMB"; e={"{0:N1}" -f (($_.Group | measure Length -Sum).Sum / 1MB)};a="right"} -Auto

You have to move the Group Measurement to the FT line from the Select.

If you want this a little more readable, you can pull the formatting HashTable out of the pipeline:

$sizeMB = @{n="SizeMB";
            e={"{0:N1}" -f (($_.Group | measure Length -Sum).Sum / 1MB)};
            a="right"}

gci -r -ea Si `
| group { if ($_.PSIsContainer) {""} else {$_.Extension} } `
| sort Count -desc `
| ft Name, Count, $sizeMB  -Auto


Ohhhh.... XOR logic on booleans in Java ..... how esoteric:

if (s.charAt(i) == ' ' ^ i == s.length() - 1) {

That should be removed "just because". It's hard to understand, the logic is inverted, and it is not short-circuit, so it tests the i == s.length() - 1 even when s.charAt(i) == ' '

I think what you have is an inverted logic problem. You are looking for all the digits in the input, when, instead, you should be looking for not-digits....

The supporting logic, using StringBuilders, etc. is not a bad idea.... but, have you considered a regular-expression?

String[] digitwords = input.split("\\D+");
int[] result = new int[digitwords.length];
for (int i = 0; i < result.length; i++) {
    result[i] = Integer.parseInt(digitwords[i]);
}
return result;

The split there, is "split on all sequences that do not contain digits"

Java8 may help (with an added filter to remove empty values, not in the loop above), with:

return Arrays.stream(input.split("\\D+"))
       .filter(word -> !word.isEmpty())
       .mapToInt(Integer::parseInt)
       .toArray();


Should I copy list both in constructor and in getter?

It depends on what the goal is. Can the list never change after construction? Can it change but only the ColumnWrapper can do so? Or can it change and everyone is allowed to do that?

If the list can not change after construction, consider using an ImmutableList (from google's guava). You should then declare the field columnNames and the return value of getNames() to be of that type. You then either create an immutable list during construction or use that type for the constructor argument as well.

If the list can change after construction (but only ColumnsWrapper can do so), the getter should return an unmodifiableList. Note that this will cause exceptions if the client of your class tries to manipulate the list. You should then also copy during construction (as you currently do).

In any way should you document the behavior with comments on the respective public members (i.e. the constructor and the getter).

Edit

Ok, so the class has to be immutable. As @rolfl explains, it can be subclassed so this is not yet the case. You can either make the class final or make the constructor private and provide a static factory method.

Furthermore you have to make sure, that the list can not be modified. The easiest and most intention revealing way I know of is the ImmutableList I mentioned above. Another solution would look like this:

public class ColumnsWrapper implements Columns {

    private final List<String> columnNamesUnmodifiable;

    public ColumnsWrapper(List<String> columnNames) {
        List<String> columnNamesCopy = new ArrayList<>(columnNames);
        columnNamesUnmodifiable = Collections.unmodifiableList(columnNamesCopy);
    }

    // OPTION A

    @Override
    public List<String> getNamesUnmodifiable() {
        return columnNamesUnmodifiable;
    }

    // OPTION B

    @Override
    public Iterable<String> getNamesUnmodifiable() {
        return columnNamesUnmodifiable;
    }

}

Note that I changed the name to inform callers that they will get an unmodifiable instance.

I also provided another additional option (you have to choose one) with a different return type. If you are sure that callers will only iterate over the returned instance (as is often the case) the iterable will suffice. But it can not be used to add methods and since removal is an optional method (i.e. many iterators support no removal) it better conveys immutability.

I any way the interface documentation should also make that clear.


ASP.NET Core singleton acting as an HttpClient provider

Alternative proposal

I think, I'd approach it differently, but I may miss some important details.

As long as the configuration change does not happen too frequently OR client construction is cheap, we can actually create a new instance of the HttpClient on every configuration change event, rather than trying to keep a single object in a good state. IMO, this approach is cleaner in the functional programming sense: the Client property now becomes a pure function in a way -- no messing with state of the object.

Now, you probably still want to keep the same HttpClient instance for as long as the config does not change -- to avoid an unnecessary object construction. Your HttpClientProvider can then work as a client factory and client "cache" in a way. This class will be responsible for providing either an existing properly configured HttpClient instance, or generating a new one since configuration has changed.

As a side note, I assume you use an IoC container for injecting HttpClientProvider into the consumers. The provider is probably registered as a Singleton with the IoC container, right?

Nitpick

There's no need to immediately create a client instance on MachineDatabaseHttpClientProvider construction. This can be deferred until the Client instance is being accessed by the consumer (e.g. Lazy<HttpClient> may work).

P. S.

I know that my answer is twisting the problem definition. Hopefully, this is not an issue (especially if there are no other requirements that are forcing you to have a single instance of an HttpClient throughout the entire application lifetime).

--------------- UPDATE 1 ---------------

I am not a guru of multi-threading but I don't think you should have any issue in most of the cases even with a thread-unsafe code here. I have different concerns though (explained below).

Simplicity

If you lock around the _currentHttpClient object [obviously, not lock (_currentHttpClient) but rather lock (_currentHttpClientLock)], you will guarantee that NO unnecessary client is created "ever".
Otherwise, you may have an extra object created n times per configuration change when there're n threads asking for a client "simultaneously".

Warnings/Pitfalls

Non-locking approach is not an issue only as long as it's okay to swap the "hot" client.
I.e. the one used by a consumer for performing multiple client calls within a single body of work.
It also depends a lot on how the consumer is using the HttpClient.
Here are three different scenarios with their own problems.

Option 1

Here's a consumer that does not hold an HttpClient reference, but keeps retrieving the client from provider for EACH external call:

class ConsumingController
{
    private MachineDatabaseHttpClientProvider _provider;

    ConsumingController(MachineDatabaseHttpClientProvider provider)
    {
        _provider = provider;
    }

    // ...

    [HttpGet]
    public Task<ComplexObject> GetComplexObject(string id)
    {
        ComplexObject complexObject;

        // Moment 1
        complexObject = _myOwnCopyOfClient.Client.GetObject("base" + id);

        // Moment 2
        complexObject.Details = _myOwnCopyOfClient.Client.GetObject("datails-for-" + id);

        return complexObject;
    }
}

If the configuration changes between the moments 1 and 2 (say endpoint changes), the two requests will target different databases and it may result in funny results.
And I mean, funny in a bad way.

In a good case, you'll get an HTTP 404 for the second request, which is safe. All the consuming application needs to do is repeat the request...

In a worse case, there could be "detail" objects in the second DB that match the id from the first DB. This will result in construction of an object that presents data from two incompatible sources.

You application should be able to handle this situation.

Option 2

Another consumer design will simply hold the reference to the HttpClient instance:

class ConsumingController
{
    private HttpClient _myOwnCopyOfClient;

    ConsumingController(MachineDatabaseHttpClientProvider provider)
    {
        _myOwnCopyOfClient = provider.Client;
    }

    // ...

    [HttpGet]
    public Task<ComplexObject> GetComplexObject(string id)
    {
        ComplexObject complexObject;
        complexObject = _myOwnCopyOfClient.GetObject("base" + id);
        complexObject.Details = _myOwnCopyOfClient.GetObject("datails-for-" + id);
        return complexObject;
    }
}

Notice that if the consumer persists the reference to an HttpClient, there's NO effective WAY for the Provider to update the configuration of that instance.

Option 3

This may be the best option...

class ConsumingController
{
    private MachineDatabaseHttpClientProvider _provider;

    ConsumingController(MachineDatabaseHttpClientProvider provider)
    {
        _provider = provider;
    }

    // ...

    [HttpGet]
    public Task<ComplexObject> GetComplexObject(string id)
    {
        // This client instance is bound to the method execution scope...
        var requestScopeClient = _myOwnCopyOfClient.Client;

        ComplexObject complexObject;

        // Moment 1
        complexObject = requestScopeClient.GetObject("base" + id);

        // Moment 2
        complexObject.Details = requestScopeClient.GetObject("datails-for-" + id);

        return complexObject;
    }
}


Multiple custom file input fields with jQuery

You could certainly combine the first 3 handlers into 1, since they do the exact same thing:

$(document).on('change', ':file', function () {
  var input = $(this),
      filename = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  input.trigger('fileselect', [filename]);
});

That'll add an event handler to all file inputs on the page.

You can simplify the replace stuff a bit; there's no need to make backslashes into regular slashes, if you're just going to throw it all away afterward. So it'd be simpler to say

input.val().replace(/^.*[\\\/]/g, '')

i.e. remove everything up-to-and-including the last slash.

Handling the custom fileselect event is where you want to limit it to specific inputs. However, you can extract the truncate logic, to clean things up, and avoid the repetition.

function truncateFilename (filename) {
  if(filename.length > 14) {
    return filename.substring(0, 14) + "...";
  }
  return filename;
}

And since you've stuck to a naming convention for the elements you want to display the filenames, you can create a function to set up your event handling:

function addFileSelectHandler(inputClass) {
  $(inputClass).on("fileselect", function (event, filename) {
    $(inputClass + "-name").text(truncateFilename(filename));
  });
}

addFileSelectHandler(".compliance-guide");
addFileSelectHandler(".compliance-other");
addFileSelectHandler(".agreement-file");

Other notes:

Don't use .html() when you're just setting plain text strings; use .text() (as seen above)
Don't use classes to identify unique elements; use IDs. It's what they're for.
CSS has a text-overflow rule that'll auto-truncate text if it overflows - no need for JavaScript at all, and no need for a hard-coded length of 14. As always, letter-count has little to do with how much space it takes to display; "m"s take up a lot more space than "i"s (if you're using a non-monospaced font).

Also, you could choose to handle all of this in the generic $(:file).on("change",.. function. Instead of using specific classes on the elements that should show a filename, you could use a data-input attribute to link them to a file input.

For instance, you could have this markup:

<input type="file" id="some-file">

<input type="file" id="some-other-file">

And this JS:

$(document).on('change', ':file', function () {
  var input = $(this),
      filename = input.val().replace(/^.*[\\\/]/g, '');

  $(".filename[data-input='" + this.id + "']").text(filename);

  // you can still trigger your custom event, if you want
  // input.trigger('fileselect', [filename]);
});

That'll automatically show the filename, provided there's an element to show it. If there's no element, well, then it's not shown.


I agree with both @mjolka and @kyle-falconer. In fact the two points are very similar, because dependency injection frameworks usually work by giving you singletons by default. Mjolka's suggestion of adopting Dagger will be good long-term solution and definitely worth the time investment. Kyle's suggestion is more of a direct, simple solution you can implement right now.

If you go with Kyle's approach, I would point out the modern way of implementing singletons in Java using an enum, that's simpler and more robust:

enum SingletonRestClient {
    INSTANCE;

    private final RestClient restClient;

    private SingletonRestClient() {
        restClient = new RestAdapter.Builder().setEndpoint(BASE_URL).build().create(RestClient.class);
    }

    public RestClient getRestClient() {
        return restClient;
    }
}

You could use this in an activity like this:

public class SomeActivity extends Activity {
    private RestClient restClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        restClient = SingletonRestClient.INSTANCE.getRestClient();
    }
}

Of course, you will have to do this in all your activities that need the rest client.
But this is still better than forcing all your activities to extend a base activity.

Don't use inheritance just to share data.
The right reason to use inheritance is when there is an is-a relationship.
Can you say that SomeActivity is a BaseActivity?
This sounds inevitably wrong, because the very nature of a "base activity" is that there is just one such activity.
A good example would be an EmployeeActivity inheriting from a PersonActivity,
which could make sense, since an employee really is a person.

We don't have more details about your context.
If there is no is-a relationship between the classes involved,
then don't use inheritance, and prefer composition instead:
let each class that needs a rest client get it from the singleton.


Some minor improvements:

I would switch to a NamedTuple instead of a separate class:

from collections import namedtuple

Image = namedtuple('Image', ('master_id', 'url'))

Or, if you are going to stay with classes, consider adding __slots__ - may help performance-wise - though this part is not likely to be your bottleneck, but rather can be a quick and easy win
you can also improve your extract_data function:

def extract_data(data):
    """Extract data"""
    return [Image(*url) for _, url in data.iterrows()]

I would also try asyncio from Python 3.x. Here is also a relevant snippet.


System.out.print("Illegal move. Please pick at least 1 matches.\n");

You've got a typo there, should be 1 match.

I like how you've structured your code, but there's a couple naming points I want to address...

When a player takes a turn, you call it a "player turn". Which sounds pretty okay... but then the code reads like this: human.playerTurn(); which doesn't sound all that great. "I am now doing my player turn". There is no verb in your function name. Functions do stuff, so they should have a verb in there, or else they might be not doing stuff. Or maybe they're doing vague stuff.

Try "player takes a turn". So you get this:

computer.takeTurn();

human.takeTurn();

Next up, you've got duplicated code.

        if (computer.getMatchesLeft() != 1){
            System.out.print("Computers move: ");
            computer.playerTurn();
            computer.printStatus();

            if (computer.getMatchesLeft() == 1) {
                gameOver = true;
                System.out.println("Human loses, computer wins.");
            }
        }

        if (human.getMatchesLeft() != 1){
            System.out.print("Humans move: ");
            human.playerTurn();
            human.printStatus();

            if (human.getMatchesLeft() == 1) {
                gameOver = true;
                System.out.println("Computer loses, human wins.");
            }
        }

This is pretty much the same thing twice. If you could make computer and human print "xxx's move: " then you'd be pretty close to merging the two sections of code into one...

Specifically, the parts that are different are...

if (computer.getMatchesLeft() != 1){
if (human.getMatchesLeft() != 1){

The human and computer in statements like this;

            System.out.print("Computers move: ");
            System.out.print("Humans move: ");

These two pieces of text;

                System.out.println("Human loses, computer wins.");
                System.out.println("Computer loses, human wins.");

And these two pieces of text. If you could remove those differences, or somehow extract them from the section of code to another place, you could merge the two sections of code. Having less duplicated code is good, because if you would have to make a change, you wouldn't have to make it in two places.

For this, I'd add a method to Player: getName(). That way, you could print player.getName()+"'s move: ". Implement in Computer as return "Computer"; and in Human as, well... your choice, maybe it just returns Human, maybe it returns a string the player has entered at the start of the game.

Then, you could use an array or a List to do this:

    Player[] players = {computer, human};
    Player victor = null;
    while (!gameOver){
        for(Player player : players){ //for each item in collection
            if(player.getMatchesLeft() != 1){
                System.out.print(player.getName()+"'s move: ");
                player.takeTurn();
                player.printStatus();
                if(player.getMatchesLeft() == 1){
                    victor = player;
                    gameOver = true;
                    break;
                }
            }
        }
   }

   if(victor == human){
      System.out.println("Computer loses, human wins.");
   } else {
      System.out.println("Human loses, computer wins.");
   }

Which would simplify your game code quite a bit. You could make it even smaller by remembering that you don't need the matchesLeft check due to the existence of the break; statement.

I'd also take a look at moving the whole "Game" to a separate class. That way you could ask the player "do you want to play again" and start at the top. Aim for a structure like this:

  do {
      int matches = askForMatchCount();//maybe pass in Scanner, maybe use it from member variable
      Game game = new Game(human, computer);//Game(Player players...)
      game.setMatches(matches);
      Player victor = game.playGame();
      printVictoryMessage(victor);
 } while(askForRematch());

I've used some tricks there you might not have seen before. You'll have to google to find out what they are, but I'll help you with the search terms and short descriptions:

 do { /*code*/ } while( condition );

That's a do-while loop. It works like a while loop, but always runs at least once.

 Game(Player players...)

That ... in the argument list is called "varargs". It's useful if you have a number of arguments but don't know how many. In this case, I'm making it possible to give you a three player game.

Last point I have for now is misuse of static.

In Player, you have this:

 private static int matchesLeft;

And at first I was like "Why would you do this?" It makes no sense! The amount of matches left doesn't belong to 1 player, does it? Do they have their own matches? Isn't this a game where the matches are shared between the players... Oh.

You've made them shared between the players! Makes sense, I guess...

Except you've just made them shared between ALL the players. Which is not so good if you ever wanted there to be multiple games happening at the same time.

If you instead relocated the matches to the game (like I did a bit earlier with game.setMatches(int matches), then you can change the takeTurn to take a Game object and obtain the matches that way (takeTurn(Game game)).


Script for fetching a list of "end-positions" from a MySQL database

The comments are good; I copy them here so this question has a "proper" answer, and add some my own:

  Just off the top of my head: 1) Don't name things c. It's a very important base R function. 2) Now that you've renamed it, don't sort it twice. Sort it once, and then use head and tail. –  joran

and

  Also, change c[i,1]<-actionlist$OpenTime[i] to c[,1]<-actionlist$OpenTime and move it out of the loop. –  Richie Cotton

and

  Also, look at ?Rprof to know how you can check which part of your function is slowing everything down. –  Joris Meys

This last is important; if you don't know where the code is slow, you don't know where to apply effort to speed it up.

My comments are that, if you have a function that is doing some work, all the information that it needs should generally be passed in as arguments. It took me a bit to figure out what c and z (after I overcame the cognitive dissonance of thinking c[i,1] was itself an error).


I think you are reinventing the wheel a bit too much.  If you need something simple then go with built in .net ones.  If you going to make a simple ServiceLocator then you should implement the IServiceContainer interface.

public sealed class ServiceLocator : IServiceContainer

This is a matter of preference but I usually set static instance property in a static constructor.  There isn't a lot of overhead in creating the object right away that we need to do locking or delayed creation when they access the property.

public static IServiceContainer Instance { get; }

static ServiceLocator()
{
    Instance = new ServiceLocator();
}

Now I would create two constructors one the default and one that takes a IServiceContainer

private readonly IServiceContainer _container;

public ServiceLocator() : this(new ValidationContext(string.Empty).ServiceContainer)
{
}

public ServiceLocator(IServiceContainer container)
{
     if (container == null)
     {
         throw new ArgumentNullException(nameof(container));
     }
    _container = container;
}

I typically use the Servicecontainer from the ValidationContext class.  It's marked internal so we can not just new it up.  The difference between the ServiceContainer class and the one from the ValidationContext is two fold.  One the ServiceContainer class implements IDisposable and two it caches the results from the ServiceCreatorCallback delegate.   It would be up to you to decide which one of the ServiceContainers from .net you would prefer.

The rest of the methods I would just chain down to the container we set in the constructor

public object GetService(Type serviceType)
{
    return _container.GetService(serviceType);
}

public void AddService(Type serviceType, object serviceInstance)
{
    _container.AddService(serviceType, serviceInstance);
}

public void AddService(Type serviceType, object serviceInstance, bool promote)
{
    _container.AddService(serviceType, serviceInstance, promote);
}

public void AddService(Type serviceType, ServiceCreatorCallback callback)
{
    _container.AddService(serviceType, callback);
}

public void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote)
{
    _container.AddService(serviceType, callback, promote);

}

public void RemoveService(Type serviceType)
{
    _container.RemoveService(serviceType);
}

public void RemoveService(Type serviceType, bool promote)
{
    _container.RemoveService(serviceType, promote);
}

This is a very simple Service Locator.   There are lots of very good dependency injection library out there but this will work if you only need a simple container.


Including a C file

Convention is that all shared stuff is declared in .h files.

Minor 1

In destroy(), you have the return type void*. Remove the pointer star and it's fine.

Minor 2

sllnode *create(int value)
{
    sllnode *node;
    node = (sllnode *) malloc(sizeof(sllnode));

    if (node == NULL)
    {
        puts("Memory error");
        return NULL;
    }
    ...

It's a bad idea to abuse standard output from within algorithms/data structures. After all, everything that may go wrong is that there is no memory enough for the new node; returning NULL may well indicate that situation.

Minor 3

node = (sllnode *) malloc(sizeof(sllnode));

More idiomatic C is

node = malloc(sizeof *node);

Minor 4

You "append" the new nodes in reversed direction. Basically this is a (linked) stack and not a list.

Minor 5

while (temp != NULL)
{
    free(temp);
    temp = temp->next;
}

Don't do this. Instead have something like

while (temp)
{
    next_node = temp->next;
    free(temp);
    temp = next_node;
}

Summa summarum

For a starter, I had this in mind:

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

typedef struct linked_list_node {
    int value;
    struct linked_list_node* next;
} linked_list_node;

typedef struct {
    linked_list_node* head;
    linked_list_node* tail;
} linked_list;

void linked_list_init(linked_list* list)
{
    if (!list)
    {
        return;
    }

    list->head = NULL;
    list->tail = NULL;
}

void linked_list_free(linked_list* list)
{
    linked_list_node* current_node;
    linked_list_node* next_node;

    if (!list)
    {
        return;
    }

    current_node = list->head;

    while (current_node)
    {
        next_node = current_node->next;
        free(current_node);
        current_node = next_node;
    }
}

int linked_list_append(linked_list* list, int value)
{
    linked_list_node* new_node;

    if (!list)
    {
        return 1;
    }

    new_node = malloc(sizeof *new_node);

    if (!new_node)
    {
        return 1;
    }

    new_node->value = value;

    if (list->head)
    {
        list->tail->next = new_node;
    }
    else
    {
        list->head = new_node;
    }

    list->tail = new_node;
    return 0;
}

int linked_list_index_of(linked_list* list, int value)
{
    int index;
    linked_list_node* node;

    if (!list)
    {
        return -2;
    }

    for (node = list->head, index = 0; node; node = node->next, index++)
    {
        if (node->value == value)
        {
            return index;
        }
    }

    return -1;
}

int main() {
    int i;

    linked_list my_list;
    linked_list_init(&my_list);

    for (i = 0; i < 10; ++i)
    {
        linked_list_append(&my_list, i);
    }

    printf("%d %d\n",
           linked_list_index_of(&my_list, 4),
           linked_list_index_of(&my_list, 100));

    linked_list_free(&my_list);
    return 0;
}

Hope that helps.


Android app with config and customization classes

Public class, private Interface?

I'm pretty confused by this setup.
The meaning is always trying working towards the most highest object( this case interface) possible.
I'm thinking that you created this setup so having the keys as constants.
But there is nothing wrong to have those keys as private static final String in your class self.

Java singleton.

I can't repeat it enough but if you want a singleton, please think enum in stead of private constructor.
Your singleton isn't thread safe or Serializable in this case, while if you use enum it is, and it's even easier to created it.

Abstract class root of all evil?

While I do use abstract classes, I'm always thinking also about putting the abstract methods in an interface and use that interface in the constructor.
This has multiple advantages of the abstract class.
First of all, you can create the base class final so no unexpected behavior could be implemented later on.
Then the interface you can swap at runtime (don't forget a check on null) and your class behave different but still in the correct way.

As I don't see the whole picture here I can't say it's good or not in this case.
But still, think about it, see the advantages/disadvantages and make your conclusion if it's good in this case or not.


If you don't want any if statements then you can do the same with the operator library and a dictionary. This is by using the dict.get method that allows you to have a default value (operator.floordiv) if the value isn't in the dictionary. After getting a valid function from the dictionary, you then just have to call the function.

import operator

operators = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul
}

number1 = int(input('Enter first number: '))
number2 = int(input('Enter Second number: '))
operation = input("Enter operation\n[+,-,*,/]")
print(operators.get(operation, operator.floordiv)(number1, number2))

I would however not assume division if the user enters random data. And so I'd add an if and else. In this case I'd check that the operator is in the operators dictionary, and perform the operation if it is. If it isn't, then I'd tell the user that they entered an invalid operator:

operators = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv
}

if operation in operators:
    print(operators[operation](number1, number2))
else:
    print('Invalid operator')

You can also make the operator list in the input automatically created from the dictionary too. To create the string '+,-,*,/' you can use ','.join(['+', '-', '*', '/']), to get the array you can then use operators.keys(). Finally you'd have to insert it into the rest of the string, and so I'd use str.format.

operation = input("Enter operation\n[{}]".format(','.join(operators.keys())))

And so tying this all together you could use:

import operator

operators = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv
}

number1 = int(input('Enter first number: '))
number2 = int(input('Enter Second number: '))
operation = input("Enter operation\n[{}]".format(','.join(operators.keys())))
if operation in operators:
    print(operators[operation](number1, number2))
else:
    print('Invalid operator')


What happens when a string ends in a newline? lines "\n" ⇒ [""], but lines' "\n" ⇒ ["", ""].
ys could have a more informative name. line?
When you find yourself wanting to add new items to the end of a list, consider keeping the list in reverse order, adding items to the front and reversing it when it's done. This avoids needing to use ++. ("Done" is a fuzzy concept when working lazily with infinite lists.)
...but when reinventing the wheel, you needn't reinvent the axle and bearings as well. There is a Prelude function that will parse one line from a string: break. If you use that, you need only handle recursing on the remainder. This is how lines is really implemented.

lines s         =  let (l, s') = break (== '\n') s
                   in  l : case s' of
                                []      -> []
                                (_:s'') -> lines s''


Adding two big integers represented as strings

Loop structure's OK, logic's reasonably good. There is obviously a Java library alternative of BigInteger, but I assume you knew that. Some efficiency issues with excessive toString() and string-ification of what could be character operations.

Here are some tips:

Use int where nulls are not possible, not Integer.
carry is only used locally -- keep it local. Referencing it outside the method can only be erroneous, so it shouldn't be visibly exposed to make that possible..
Carry calculation from i3 is OK here, but could in related algorithms be brittle -- it can't handle a digit-sum > 19 as the maximum carry it can produce is 1.
If addition completes with a carry of 0, it will output an unnecessary 0 digit.
If Strings are your inputs, you should probably build a String as the result via a StringBuilder -- not an ArrayList.
myString should be called result or sb, if you're building the result in it.
Build using StringBuilder in reverse order, and do it by character calculation (char) (i3 + '0') rather than toString() if you want to maximize efficiency.
Return the result from your function, and do the printing in main() instead. there. That way you have a general-purpose add() function and a fixed-purpose main() method for testing.

Is that complete enough?


If you want to avoid the late bound .Text and .Tag you could just create your own private type, say LVI, containing these two properties and implicit Widening CType operators for ListViewItem and ListViewItem.ListViewSubItem. Then the Result As New LVI can be converted on return using Return CType(CTypeDynamic(Result, GetType(T)), T) in the latest VB.NET.

Without CTypeDynamic I don't have a working solution yet.


Moving and organizing files in download folder

File, FileList, and Data are neither class names nor constants; variable names should be lower_case in Python.  I'd call it filename instead of file to avoid clashing with Python's built-in file() constructor.

Avoid calling splitext() twice with name, extension = os.path.splitext(filename).

For portability, clarity, and to avoid accidental omission of the path component separator, it would be better to use os.path.join(dirname, filename) instead of dirname + filename, even if you only plan to run it on Android.

You open files for reading and writing but don't close them.  In particular, it's important to make sure the destination file handle is successfully closed before removing the source, or you might lose data.  Also, it's preferable to call open() instead of file().

The structure of your program can be simplified.

if a:
    ... # body a
else:
    if b:
        ... # body b
    elif c:
        ... # body c
    if c != True:
        ... # body d

can be written as

if a:
    ... # body a
elif b:
    ... # body b
elif c:
    ... # body c
else:
    ... # body d

assuming that bodies b and c do not influence the c != True test.  Also, I believe you intend for cases b, c, and d to be mutually exclusive, but I suspect it may be possible to execute both bodies b and d in your original program.

Bodies b, c, and d are very similar to each other.  You should try to reduce the redundancy in your code.  One approach would be to copy the contents to a tempfile in the destination directory (computing the hash as you copy, in case you need it), then successively try to os.rename() the temporary file to various destination filenames.


Good

good indentation
somewhat helpful comments
good to do the ; then bit on the same line as the if

Suggestions

use double brackets for conditionals
try shellcheck (It will tell you to put quotes around your variable substitutions.)
put your arguments into named variables so you don't keep have to referring to $1
put the 3 sections into if...elif...else structure to make clear that you're only going to go into one of them
check for the existance of ./done.sh at the beginning
explain what the goal of the script is somewhere.


Your divisors generation is lacking. As explained e.g. here, you should generate them from a number's prime factorization. It is much faster that way.

You may try using rem instead of mod.

Also try making (nubOrd $ map (gcd k) u) a separate expression and name it to ensure sharing, giving your function a concrete type signature too.

update so I tried my own advice and it only made the code run slower at the interviewstreet servers. The only reason I'm not removing this, is that the advice itself (and link) about divisor generation is valid in general. But here, it did not help improve the run time of this algorithm. The OP states that same algorithm in Java got through...


Algebraic Effect Monad to separate pure and impure code

This is not a direct and full answer, but whereas I did not end up getting the opportunity I was hoping for to try this out on a C# project (yet), I did hit a perfect case for one in an F# project. I rewrote this monad in F#, implemented some concrete operations with it, and used it. I have it running in production with no problems so far, but it isn't using the constrained environment that I was describing in the question, so it hasn't given me full confidence in that yet.

After having done that, there are two main criticisms I have of the version above:

It's not very flexible. It really only allows you to have effects that conform to one type (Func<TIn,TOut>). Moreover it really only allows you to have one effect of this type.
The three generic types are overkill and not necessary. The alternative will be demonstrated below.

What I came up with was this generic effect monad:

module Effect

type Eff<'E,'a> =
     private EffReq of ('E -> 'a)

let map (f : 'a -> 'b) (EffReq p : Eff<'E,'a>) : Eff<'E,'b> =
    EffReq (f << p)

// Argh F# blocks us from using unit, pure, or return...!
let init (x : 'a) : Eff<'E,'a> =
    EffReq (fun _ -> x)

let run (io : 'E) (EffReq p : Eff<'E,'a>) : 'a =
    p io

let join (e : Eff<'E,Eff<'E,'a>>) : Eff<'E,'a> =
    EffReq (fun performEff -> run performEff e |> run performEff)

let bind (f : 'a -> Eff<'E,'b>) (e : Eff<'E,'a>) : Eff<'E,'b> =
    join <| map f e

let request = EffReq

Specific operations can be implemented using request, e.g.:

module FileIO

open Effect

type FileIO = {
    ReadAllText : string -> string
}

type IOEff<'a> = Eff<FileIO,'a>

let readAllText (path : string) : IOEff<string> =
    Effect.request (fun io -> io.ReadAllText path)

I know this is in a different language than the original question but the conceptual aspect is the most important part.

I don't consider this implementation fully battle-hardened but it should allow me to evolve the C# version in a good direction.

Note that this is really a Reader monad: it reads from an impure environment (and because that environment is impure, technically it is able to write to it as well).