Inheritance

Do not extend any class unless you you have an "is a" relationship and add new behavior to the extended class.

You extend JFrame without adding Frame related behavior, you just configure it.

  I don't understand the objection to extending JFrame here. The program needs a top level container.

Right, but you program does not need to inherit form JFrame to get one:

public class TempConvert {

private JPanel contentPane;
private final ButtonGroup buttonGroup = new ButtonGroup();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TempConvert frame = new JFrame();
                new TempConvert(frame);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public TempConvert(JFrame frame) {

    frame.setTitle("Temperature Converter");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(0, -33, 385, 272);
    frame.contentPane = new JPanel();
    frame.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    frame.setContentPane(contentPane);
    frame.contentPane.setLayout(null);

Layouting

When using NULL layout you throw away any convenience Layoutmanager could give you. Your UI will be bound to the "ideal" Frame size. The problem is that the definition of "ideal" changes with every user and every device your program runs on.

Magic Numbers

Because of your wrong interpretation of "Flexibility" that results in using the NULL Layout you need to specify bound of your buttons. And you do this by using random literal numbers (from the readers perspective). You should at least define constants for them.

Code duplication

Your code has lots of duplicated code.

You create a bunch of buttons. you could extract the creation of a single button to a parameterized method.

Also in your anonymous Listener class the try/catch block is duplicated. Here you could simply move one of then around the whole if and delete the other one.


Hum, first of all, there are way too many comments. People simply won't read them, you should only keep the meaningful ones. For example, you could remove:

if sorted_word in dict: #Check if sorted_word is already a key

Anybody who knows how Python dictionaries work will know what this lign is doing, the code is explicit by itself. Instead of always repeating what your dict is doing, you should just explain once what it does when you declare it; the code will tell the rest. You should only explain once at the beginning how your algorithm work and let your code tell the rest. Honestly, you could remove almost all of your comments. Python is designed to be readable and it is.

Second point, avoid to name a variable dict: it is already the name of a built-in type. It's bad pratice and can be confusing for people who will try to read your code.

Also, you open your file once, but never close it. You should close it once you have filled your dict. You could use the with open('...', 'r') as f: construct to have your file closed automatically at the end of the with block, therefore, you won't even have to remember to close it. Also, file, like dict is also the name of a built-in type in Python, find another name :)


Finding the right property value from array of objects

Another way to write the same thing is:
const findUser = list => list.find(u => {
  if(u.subKeys) {
    return findUser(u.subKeys);
  }
  if(checkEligible({action: u.key}) {
    callback(u);
    return true; // necessary to stop the loop
  }
});

findUser(USERS_LIST);

Once that you only need to receive a list, check if is eligible and do something with this, you can use recursion to avoid the callback repeating in user.subKeys.find and USERS_LIST.find.
Also, the return false is not necessary because the iteration of Array.prototype.find will only stop when there is a return value equivalent to true and a function without a explicit return statement will have the implicit return value of undefined:
const noop = () => {};
console.log(noop()) // undefined


Singleton class and correct way to access it in C++

Thread safety
Accessing the singleton is thread-safe. The change in C++11 has forced compilers to implement the construction of local static variables (like INSTANCE) in a thread-safe manner.
Note, however, that this doesn't make Singleton thread-safe under all circumstances: If multiple threads are calling Singleton::Test, I wouldn't be surprised to see some garbled output, as access to std::cout isn't synchronized.
Correctness
The current implementation violates the rule of 5: It has a custom destructor, but no custom copy and move constructors and assignment operators. And, to prevent making a copy of the singleton instance (or moving from it!), these 4 special functions should be deleted, like so:
public:
    Singleton(const Singleton&) = delete;
    Singleton(Singleton&&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    Singleton& operator=(Singleton&&) = delete;

Note the public specifier, this ensures that these deletions are visible everywhere needed.
Access
While taking a pointer from the reference returned by Singleton::instance() is a valid use, it seems unnecessary in MyFunction as the pointer isn't required. Why not simply capture by a reference, like so:
auto& MySingleton = Singleton::instance();
MySingleton.Test();

Or if only one call is done:
Singleton::instance().Test();


Use a ternary operator in "s"[seconds==1:].
Use a generator expression to replace the xstr = "%s... lines.
The two for loops should use enumerate(), i.e. they could be for s, i in range(...).
The two for loops should be moved into a for _ in range(2):.
i is preferred over x when using an incrementing index counter.
The filtering of the redundant strings which the for-loop does could be done earlier so that the number to string code can be modified but the filtering code will not require adjustments.

PS: I have implemented a similar function here:

    days, rem = divmod(seconds, 86400)
    hours, rem = divmod(rem, 3600)
    minutes, seconds = divmod(rem, 60)
    if seconds < 1:seconds = 1
    locals_ = locals()
    magnitudes_str = ("{n} {magnitude}".format(n=int(locals_[magnitude]), magnitude=magnitude)
                      for magnitude in ("days", "hours", "minutes", "seconds") if locals_[magnitude])
    eta_str = ", ".join(magnitudes_str)


POSIX shell function for asking questions

A couple of thoughts. There really isn't any need for correct_answers_combined. After shift, $* will hold the combined remaining arguments (answers) to your question. The additional printf, pipe, and call to sed are simply incurring additional overhead in the form of subshells and separate utility calls. You could do:

    correct_answers="$*"

    ## prompt
    printf '%b' "$question\\nPlease answer [ $correct_answers ] to confirm (Not <Enter>): "
    read -r user_answer

Since you do not want to accept [Enter] as an answer, a validation that user_answer is unset can provide the answer and return for your function in that case, e.g.

    ## validate answer provided
    [ -z "$user_answer" ] && return 1

Your "optional... speed up the whole process", with a bit of rearranging can be used as a single call to provide a return to your function. Since you want to know whether the user_answer exists among the correct_answers you can simply return the result of grep -qi:

    # this part is can be the whole process
    printf '%s\n' $correct_answers | grep -qi "$user_answer" > /dev/null 2>&1
        return $?
}

(note: using printf '%s\n' "$correct_answers" will separate each of the whitespace separated answers by newline which eliminates any possible combination of parts of adjacent answers returning true)

With those suggestions, your confirmation () function would reduce to:

confirmation ()
# $1    = a string containing the question
# $2,.. = arguments containing the right answers (case insensitive)
{
    question="$1"; shift
    correct_answers="$*"

    ## prompt
    printf '%b' "$question\\nPlease answer [ $correct_answers ] to confirm (Not <Enter>): "
    read -r user_answer

    ## validate answer provided
    [ -z "$user_answer" ] && return 1

    # this part is can be the whole process
    printf '%s\n' "$correct_answers" | grep -qi "$user_answer" > /dev/null 2>&1
        return $?
}

I haven't tested all corner cases, but for single word answers it should function as you intend. If you want the some delimiter between the answers inside [ ... ] then an additional command substitution can be used, but space separated options appear fine between the brackets.

Let me know if you have any questions over the changes.

Edit In Response to You Comments

As stated above, if you want delimiters between the possible correct answers, simply use a command substitution, e.g.

## prompt
printf '%b' "$question\\nPlease answer [ $(echo $correct_answers | tr ' ' /) ] to confirm (Not <Enter>): "
read -r user_answer

If you are concerned about the expansion of printf '%s\n', don't quote the $correct answers,

# this part is can be the whole process
printf '%s\n' $correct_answers | grep -qi "$user_answer" > /dev/null 2>&1
    return $?

Otherwise based on your stated question, it performs identical to the original saving at least half-a-dozen unnecessary subshells.


Memory Growth Issues:

When working with data in R avoid using cbind and rbind as much as possible if there are loops involved. R Inferno dedicates a chapter to the memory growth issue.

Strings are king:

In this case, you only care about column order. The order of columns within a data.frame can be easily adjusted by supplying a vector containing all of the column names in your preferred order to the data.frame object. As a result, the process is not very computationally expensive if you operate solely with column names.

With this being said, we can simplify the process greatly using:

# Starting Data Frame
df <- data.frame("x_b"=5,
                 "y_b"=2,
                 "x_a"=6,
                 "y_a"=3,
                 "y_c"=1,
                 "x_c"=4)

m = names(df) # Extract column names.

r = strsplit(m,"_") # Split the column names based on the _

# Create a data.frame with two columns X1 being x or y
# X2 being a, b, or c
q = data.frame(matrix(unlist(r),nrow=length(m),byrow=T))

# Order q according to spec
q = q[order(q$X1,q$X2, decreasing = T),]

# Reformat names
m = paste0(q$X1,"_",q$X2)

# Rearrange columns
df = df[,m]

The order of q is:

 X1 X2
  y  c
  y  b
  y  a
  x  c
  x  b
  x  a

Thus, the columns of df look like:

 y_c y_b y_a x_c x_b x_a
   1   2   3   4   5   6

Edit
The responder has clarified that they would like the order to be slightly different in the last column e.g. (c,a,b) instead of (c,b,a). There are two ways to go about this: factor() or using match(). I'll opted to only present factor() in detail as the later is more convoluted.

Factors

In this case, you should turn both columns into factors and then order on the levels without the descend option. Using factors for both columns makes the code cleaner and more logical than before since the choice of levels is able to be done in their given order e.g. y,x and c,a,b.

If you were to modify the previous example that used descend, there would be an issue in the order of the X2 column. Most notably, the column would be sorted as 'b','a','c' instead of 'c','a','b'. The reason for this is due to levels being tied to numeric values, like 1,2,3, and the prior example used descend to sort both options. Thus, if we continued to use descend, we would of been sorting X2 on 'c' => 1, 'a' => 2, 'b' => 3. The fix to this is simply reversing the order of the levels - b, a, c - which may make everything a bit more confusing later on.

Thus, we have:

# Select sort order for X1: y, x
x1.values = c("y","x")
# Select sort order for X2: c, a, b
x2.values = c("c","a","b")

# Place call to factor for both columns
q = q[order(factor(q$X1, levels = x1.values), factor(q$X2, levels = alpha)),]

Giving q as:

 X1 X2
  y  c
  y  a
  y  b
  x  c
  x  a
  x  b

So that the columns of df are now:

 y_c y_a y_b x_c x_a x_b
   1   3   2   4   6   5


An important question: why don’t you want to touch the database in the test? You have a few different options for getting phpunit to play nicely with a database. Doing so lets you test things more thoroughly as you can do assertions that the data has landed in the database as you expected.

As a starting point, based on what I see in this method, I would recommend adding something along these lines in phpunit.xml within the <php> tag

 <env name="DB_DATABASE" value="testing"/>

And create a database lined up with the “testing” value set in DB_DATABASE. These values equate to .env values, so you can add additional DB_USERNAME, etc values as appropriate.

You can use the RefreshDatabase trait to reset migrations within your newly created testing database on each test. That is described at https://laravel.com/docs/6.x/database-testing#resetting-the-database-after-each-test

It looks like you need some Location and Customer data in your database for this job to work. If you don’t already have factories for these models, make some as described at https://laravel.com/docs/6.x/database-testing#writing-factories

As a starting point you can manually call factories in your test – factory(App\Customer::class)->create(); will put a factory generated customer into your database. If you need three of them, – factory(App\Customer::class, 3)->create(); The factory method returns the created entities, so you can do:

    $customer = factory(App\Customer::class)->create();
    $locations = factory(App\Location::class, 3)->create();
    newJob(
     $customer->id,
     Arr::get($locations, 0)->id,
     Arr::get($locations, 1)->id,
     Arr::get($locations, 2)->id
);

Now the job should be in your testing.jobs table, and you can make an assertion of that:

$this->assertDatabaseHas(‘jobs’,[
‘customer_id’ => $customer->id,
‘location_id_from’ => Arr::get($locations, 0)->id,
‘location_id_to’ => Arr::get($locations, 1)->id,
‘location_id_ bill’ => Arr::get($locations, 2)->id,
]);

Yes there’s a some overhead in getting the database incorporated into your test setup and in writing the factory, but the end result is a more thorough test. Worth it, in my opinion.

I hope something here helps!


What do you think about this uint64 random generator?

DONT DO THIS

while (i--)
{
    myRand += rand();
    if (i)
    {
        myRand <<= numberOfBits;
    }
}

It seems like you are trying to increase the range of random numbers.
What you are doing is screwing up the distribution of the random numbers and thus making them less random. Have you tried plotting a histogram to show the distribution.

Luckily for you your system probably only has 32 bit rands and thus this is not changing anything; as the loop is only done once.

ASSUMPTION HERE

static const unsigned long uint_max = 0xffffffff;  // assuming that long is 32 bits

// long has at least 32 bits but can be larger.

Is this not the whole point of all the work to avoid this:

    if (high < RAND_MAX)
    {
        return (rand() & high);  // basically this is the same as using
    }                            // % high. You are folding at high
                                 // unless RAND_MAX is a multiple of high
                                 // then you have an uneven distribution.

There is plenty of documentation on the web of how to do this correctly please try and find rather than re-invent something like this. Random number generation is a non trivial task and exceedingly hard to get correct. Don't mess with it unless you have a PhD in probability.

Rand done properly: https://stackoverflow.com/a/10219422/14065


Directly accessing class attributes in Rock Paper Scissors

As has been pointed out, overriding the __call__ method is not the best way to improve the readability of your code.

Using attributes is not, in itself, a problem.

What you may want to consider is a trick you can play with Rock/Paper/Scissors.

If you create an array in the order:

Rock -> Scissors -> Paper -> Rock

Then, if you have two hands, and they select a random 'hand' from the three options Rock, Scissors, Paper.... then, you can find the first index of the first hand's value in the size-4 array above.... then if the next value is the opponent's hand, you win. If it is the same as your hand, it's a draw. Otherwise it's a loss.

winconditions = ['Rock', 'Scissors', 'Paper', 'Rock']
p1index = winconditions.index(player1.hand)
p2index = winconditions.index(player2.hand)
if p1index == p2index:
    # draw
elif p1index + 1 == p2index:
    # p1 wins!
else
    # p2 wins.

Since this is probably the most common method to call when accessing the player, it may make sense to make the hand the result of the __call__ function ..... and it would make the code read pretty nicely....

def __call__(self):
    return self.hand

and then you can use it like:

def battle(player1, player2):
    """plays one round of rock paper scissor"""
    #players choose their hands
    player1.choose_hand()
    player2.choose_hand()

    #see who wins the battle
    if player1() == "rock" and player2() == "scissors":
        player1.increase_wins()
    elif player1() == "paper" and player2() == "rock":
        player1.increase_wins()
    elif player1() == "scissors" and player2() == "paper":
        player1.increase_wins()
    elif player1() == player2():
        print "It's a tie."
    else:
        player2.increase_wins()


Boosting time performance:

Starting with minor naming issues:
maxi is better named as max_len (as stated in comment). maxi_d is renamed to max_d.
It's good to move the processing into a separate function, called like calc_longest_recur_cycle.

The main time-performance hits in your implementation is caused by quotient list and its expensive list operations:

quotient.append
quotient.index
cur_value not in quotient

According to that fact that quotient and len_recur are reset on each outer for loop iteration and on the level of while loop the fragment

len_recur += 1
quotient.append(cur_value)

tells that cur_value is appended synchronously with incrementing len_recur i.e. the cur_value will get the position equal to len_recur. That means that, on this level, cur_value can be mapped to its position contained in len_recur.Thus, quotient is initiated as dictionary (instead of list): quotient = {} or even quotient = {0: 0} as AJNeufeld suggested to eliminate cur_value evaluation on the while loop condition.

The construction:

while cur_value not in quotient:
    if not cur_value:  # If the value is not recurring:
        break

is essentially a verbose equivalent to:

while cur_value and cur_value not in quotient:

List indexing

len_recur -= quotient.index(cur_value) + 1

is now efficiently replaced with dict indexing (where values are positions)

len_recur -= quotient[cur_value]

Now, with quotient as dict, we have O(1) complexity for membership check (cur_value not in quotient) and indexing operation (len_recur -= quotient[cur_value])

The final version:

LIMIT = 5000

def calc_longest_recur_cycle():
    max_len = 0   # The maximum length
    max_d = 1     # The 'd' that has maximum length

    for d in range(1, LIMIT):
        quotient = {0: 0}  # Stores the decimal quotient
        cur_value = 1      # Variable used to perform division as if by hand
        len_recur = 0      # Recurring length

        # Performing division as if by hand
        while cur_value not in quotient:  # while the value is not recurring
            len_recur += 1
            quotient[cur_value] = len_recur
            cur_value = (cur_value % d) * 10

        if not cur_value:
            continue

        # Remove number of values that do not recur
        len_recur -= quotient[cur_value]
        # quotient.clear()

        if len_recur > max_len:
            max_len = len_recur
            max_d = d

    return max_d

What needs to be mentioned is that despite of its fast nature dict would take more space than list, but only at the time of one nominal loop iteration as it's reset and last quotient filled at the end will be garbage-collected on function exit.

Let's get to tests.
I've increased limit to LIMIT = 5000 to "turn up the heat" and have put the "old" implementation into separate function calc_recur_cycle_old for comparison.
As for resulting max_d value - both functions return the same result:

print(calc_recur_cycle_old())      # 4967
print(calc_longest_recur_cycle())  # 4967

And the most interesting time performance comparison:

from timeit import timeit

print(timeit('calc_recur_cycle_old()', 'from __main__ import calc_recur_cycle_old', number=1))
19.648109548998036

print(timeit('calc_longest_recur_cycle()', 'from __main__ import calc_longest_recur_cycle', number=1))
0.26926991600339534

The end ... )


Refactoring legacy code for unit testing

Looking at your code I see three responsibilities:

the Data Provider (component that hits the db)
the Data Formatter
the business service (your class) that uses the other two components to execute a business flow.

According to the SRP, one class should have one responsibility, so we should end up having three classes.

Therefore, I'd separate out the data provider and formatter interfaces, like so:

public interface IDataProvider
{
    List<MyClass> GetData();
}

public interface IDataFormatter
{
    List<MyClass> GetFormattedData(List<MyClass> data);
}

and refactor our business class to use these dependencies:

public class RefactoredClass
{
    private readonly IDataProvider _dataProvider;
    private readonly IDataFormatter _dataFormatter;

    public RefactoredClass(IDataProvider dataProvider, IDataFormatter dataFormatter)
    {
        _dataProvider = dataProvider;
        _dataFormatter = dataFormatter;
    }

    public List<MyClass> DoSomething()
    {
        var data = _dataProvider.GetData();

        if (data.Count == 0)
            return new List<MyClass>();

        data = _dataFormatter.GetFormattedData(data);

        if (data.Count == 0)
            return new List<MyClass>();

        //Do some more stuff

        return data;
    }
}

Now you can write all relevant unit tests, for each system component in isolation:

you can test RefactoredClass providing your mocks/stubs for the two dependencies
you can test the DataFormatter(s) in separate unit test(s)
you can test the concrete DataProvider using integration tests (since this component touches the database)

Regarding Depenedency Injection, this is how you should compose this component somewhere in your application root:

var dataProvider = new SqlDataProvider();
var dataFormatter = new MySlickDataFormatter();

var businessComponent = new RefactoredClass(
    dataProvider,
    dataFormatter);

This technique of manually instantiating the needed component and its dependencies is called "Poor man's DI". If things get any more complicated, you should consider using an IoC container for this.

Update:

Your tests make sense, but there are more tests to be added. For example, the formatting logic is not tested.

Also, regarding your second test - you have no mocks in there. The MySeparateClass instance is the system under test and the IDataProvider instance is a stub. Your test does make sense; that's just a small naming issue.

A mock is basically a fake instance that you assert against.

If you google for "mocks and stubs" you'll find plenty of articles on this subject that you can read. I also recommend the book "The Art of Unit Testing" by Roy Osherove - a great resource on this subject.


It seems that every one of your getCity(), getDepartment() etc functions loads the same web page over and over.

You should load each URL once with your curl_get_contents(), then pass its result into each get*() function to parse it.


Calculate odds of winning (UK) Lottery jackpot

A quick note to start:

Console.WriteLine(String.Format("the odds are 1/{0:n0}", totalWinOdds));

Is exactly the same as:

Console.WriteLine("the odds are 1/{0:n0}", totalWinOdds);

Now on to some maths fun... There's a multiplicative version which means you don't have to compute such massive numbers so don't need to use BigIntegers:

private int GetBinomialCoefficient(int totalNumberOfBalls, int numberOfBallsDrawn)
{
    // range checking of arguments omitted.
    var total = 1;
    for (var i = 1; i <= numberOfBallsDrawn; i++)
    {
        total *= (totalNumberOfBalls + 1 - i) / i;
    }
    return total;
}

  GetBinomialCoefficient(59, 6) == 45057474

Edit

I have changed the name of the method away from GetJackpotOdds based on 200_success's excellent answer.


var
You should use them with max_length and salt too. If the type is obvious from the right hand side of the assignment you should use var.
From here

Under what circumstances is it necessary for a variable's type to be clearly understood when reading the code? Only when the mechanism of the code -- the "how it works" -- is more important to the reader than the semantics -- the "what its for".

So basically in a line like
byte[] salt = new byte[max_length];

or
int max_length = 32;

the type of the variables does not add any value to the code. It is too obvious what the assigned type is, using the type instead of var only adds noise to the code without any real value.
Disposing
If an object implements IDisposable you should either call its Dispose() method or enclose it in an using block.
Naming
Also variables local to a method aren't mentioned in the naming guidelines I would suggest to use camelCase casing for naming them instead of snake_case casing.
For naming private methods you should use PascalCase casing.
Comments
Comments should only describe why something is done. Let the code itself explain what is done by using meaningful and readable names.
A very good answer about comments can be found here: https://codereview.stackexchange.com/a/90113/29371
getSalt()
You should allow to pass the max_length to the method instead of hardcoding it. This has the advantage that a change to this value won't need the class class/method to be changed. If you make it an optional parameter you can still call it like it whould have no parameter.
Edit
Based on the valid comment from Johnbot you should better use a overloaded GetSalt() method instead of using an optional parameter.
I don't see the need for converting to base64. Encryption algorithms use byte[] arrays, so you should better just return the byte[].

Applying the above would lead to
private static int saltLengthLimit = 32;
private static byte[] GetSalt()
{
    return GetSalt(saltLengthLimit);
}
private static byte[] GetSalt(int maximumSaltLength)
{
    var salt = new byte[maximumSaltLength];
    using (var random = new RNGCryptoServiceProvider())
    {
        random.GetNonZeroBytes(salt);
    }

    return salt;
}


Rust closure to be called on a cache miss

I like what you've done! I don't have too many comments about the content of it, since it looks good. However, you'll see below that I changed the field name value to cache and some of the generic parameter names, just to make things a little clearer. This is just a subjective preference, but I used F for function, K for key, and V for value.

Another thing to note is that in many cases, you don't need to put trait bounds on the parameters for the struct itself. You just need the bounds when you are implementing functions with it, and having the bounds on the struct doesn't save you from having to write the bounds when you use it as a parameter.

If you want to get rid of the Clone bound, you can return a reference to the value now stored within the cache. Here's one possible implementation of that, using HashMap's entry API.

use std::collections::HashMap;
use std::hash::Hash;

struct Cacher<F, K, V> {
    calculation: F,
    cache: HashMap<K, V>,
}

impl<F, K, V> Cacher<F, K, V>
where
    F: Fn(&K) -> V,
    K: Hash + Eq,
{
    fn new(calculation: F) -> Self {
        Cacher {
            calculation,
            cache: HashMap::new(),
        }
    }

    fn value(&mut self, arg: K) -> &V {
        use std::collections::hash_map::Entry;

        match self.cache.entry(arg) {
            Entry::Occupied(occupied) => occupied.into_mut(),
            Entry::Vacant(vacant) => {
                let value = (self.calculation)(vacant.key());
                vacant.insert(value)
            }
        }
    }
}


This is on top of @tim's excellent review.
I think this is a very good solution,
and a clever use of LinkedHashMap.
I can't think of a better or simpler algorithm.

Simplifications

This can be written simpler:

if (letters.containsKey(current)) {
    letters.put(current, false);
} else {
    letters.put(current, true);
}

Like this:

for (int i = 0; i < input.length(); i++) {
    char current = input.charAt(i);
    letters.put(current, !letters.containsKey(current));
}

Instead of comparing boolean expressions to true like this:

if (entry.getValue() == true) {

You can use them directly:

if (entry.getValue()) {

Unit tests

It's nice that you start adding unit tests. It will pay off!

To run your test cases in an IDE,
you need to make them public (at least I had to, in IntelliJ).

As a small extra tip,
to avoid long repeated calls like NoRepeat.retrieveFirstNonRepeatedLetter(...),
sometimes it can be practical to create a helper method, for example:

void assertFirstNonRepeatedLetter(char expected, String string) {
    assertEquals(expected, NoRepeat.retrieveFirstNonRepeatedLetter(string));
}

@Test
public void toothyTest() {
    assertFirstNonRepeatedLetter('h', "tooth");
}

@Test
public void smellyTest() {
    assertFirstNonRepeatedLetter('d', "odor");
}

Why fall back to firstNonRepeated = ' ' ?

I suggest to pay close attention to the specs.
It doesn't mention what should happen if there are no unique letters in the input.
Don't assume arbitrary fallback values.
The behavior is undefined, so it's kind of an illegal state.
It's a good move to throw an IllegalStateException in this case:

public static char retrieveFirstNonRepeatedLetter(String input) {
    Map<Character, Boolean> letters = new LinkedHashMap<>();

    for (int i = 0; i < input.length(); i++) {
        char current = input.charAt(i);
        letters.put(current, !letters.containsKey(current));
    }

    for (Map.Entry<Character, Boolean> entry : letters.entrySet()) {
        if (entry.getValue()) {
            return entry.getKey();
        }
    }

    throw new IllegalStateException("No non-repeated characters");
}

And add a corresponding unit test to cover this:

@Test(expected = IllegalStateException.class)
public void nothingUnique() {
    NoRepeat.retrieveFirstNonRepeatedLetter("abab");
}


As run() is several lines long, it should be defined outside the class.  Anything defined inside is automatically inlined.
Depending on the size of data when passing by value, it may be best to pass it to run() by const&, modify a local copy, and return that.  RVO should still kick in.
Is there a significance to the name foo here?  If not, it should be more accurate and start with a capital letter as it's a user-defined type.  The capitalization also applies to pipeline.
iter end = m_list.end(); seems pointless here.  You can just use m_list.end() inside the loop statement.

As m_list is not being modified inside the loop, you can instead use cbegin() and cend() for const-correctness.

If you have C++11, you can use auto to replace the defined iterator inside the loop statement.
Your "pause" is okay, but you can also use std::cin.get() to do the same thing.


Inserting command output into multiline string

If GUAC_PASSWORD is a string like -e foo or /etc/*, that's going to create problems.

Quote the input and avoid echo altogether.  While you're at it, whitelist the checksum output, making head redundant:

HASHED=$( tr -d '\n' <<<"$GUAC_PASSWORD" | sha256sum | tr -dc a-f0-9 )

edit: suppress newline added by <<<


Set of matrix operations for summing around a matrix element

First some simple things:

I would use end instead of endfor and endif, to keep the code compatible with MATLAB.
It is not necessary to end a function with end (though it's not harmful either). The end is only necessary when writing nested functions that have access to the parent function's workspace.
You should break up very long lines of code using ... (see an example below).
When looping through a large matrix, always make the first index your inner loop. Matrix elements M(1,j) and M(2,j) are adjacent in memory, M(i,1) and M(i,2) are not. If you switch your two nested loops, your code will be faster for large arrays, as you use the cache better.

Now for the hard part: changing your logic.

|a b c|
|d e f|
|g h i|

  Sum of difference between neighbours around element e:

(a-b)+(b-c)+(c-f)+(f-i)+(i-h)+(h-g)+(g-d)+(d-a)

Note that you compute the phase difference between two neighboring cells several times: for example, (a-b) will be computed when determining your value for e, but also in the previous loop iteration, when d was the center element; it will be computed two more times when that pair appears at the bottom of such a neighborhood.

Thus, you should pre-compute these differences and store them:

vdiff = phaseDifference(diff(M,1,1));
hdiff = phaseDifference(diff(M,1,2));

For this to work, phaseDifference must be rewritten, see below.

Now, vdiff has one fewer rows, and hdiff has one fewer columns, than M. We need to take this into account when indexing. Think of these as the elements in between the rows/columns of M.

The sum for one element at (i,j) now becomes:

phase(i-1,j-1) = hdiff(i-1,j-1) + hdiff(i-1,j) ...
               - hdiff(i+1,j-1) - hdiff(i+1,j) ...
               - vdiff(i-1,j-1) - vdiff(i,j-1) ...
               + vdiff(i-1,j+1) + vdiff(i,j+1);

The full function now becomes:

function phase = checkPhase2(M)
vdiff = phaseDifference(diff(M,1,1));
hdiff = phaseDifference(diff(M,1,2));
phase = zeros(size(M)-2);
for j = 2:size(M,2)-1
   for i = 2:size(M,1)-1
      phase(i-1,j-1) = hdiff(i-1,j-1) + hdiff(i-1,j) ...
                     - hdiff(i+1,j-1) - hdiff(i+1,j) ...
                     - vdiff(i-1,j-1) - vdiff(i,j-1) ...
                     + vdiff(i-1,j+1) + vdiff(i,j+1);
   end
end

Since Octave is slow with loops, it is likely that this vectorized version will be faster:

function phase = checkPhase3(M)
vdiff = phaseDifference(diff(M,1,1));
hdiff = phaseDifference(diff(M,1,2));
j = 2:size(M,2)-1;
i = 2:size(M,1)-1;
phase = hdiff(i-1,j-1) + hdiff(i-1,j) ...
      - hdiff(i+1,j-1) - hdiff(i+1,j) ...
      - vdiff(i-1,j-1) - vdiff(i,j-1) ...
      + vdiff(i-1,j+1) + vdiff(i,j+1);

I'm testing on MATLAB R2017a, and the vectorized form is actually slower than the version with loops, because indexing is still quite slow, whereas MATLAB has made huge strides in the last year speeding up code with loops.

Timings for an input of 2000x3000 elements:

checkPhase(M) (the OP's version) runs in 1.3s,
and swapping the loop order it runs in 1.0s,
checkPhase2(M) runs in 0.17s,
checkPhase3(M) runs in 0.25s.

Your timings on Octave will be vastly different (much slower for the code with loops).

For phaseDifference to work with an array input, it cannot use if the way that the original function does. It is possible to rewrite the same logic using logical indexing to work on a full matrix, but this version is simpler:

function deltaPhi = phaseDifference(deltaPhi)
deltaPhi = mod(deltaPhi + pi, 2*pi) - pi;

Note I replaced the two inputs with a single one, as diff already computes the difference between neighbors.


Handling optional parameters in a servlet

I suggest extract code for getting parameter to separate method (see extract method refactoring's tehnique):

param = getOptionalParameter("httpParam");
if (! param.isEmpty()) {
    // Handle parameter
}


Create Lists for Drop-Down Menus in Different Sheet

This will be hard to get right without the actual workbook.

Stop adding and removing Sheets("Filter Builder"); just hide it.
Avoid Select or Activate. Reference: Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)
By working with the data in arrays, you can avoid filtering & unfiltering you data as well as hiding and unhiding the columns.
Use With block to qualify your ranges. Reference: Excel VBA Introduction Part 12 - With Statements
Replace your static ranges ,e.g. .Range("$A$1:$AF$5150"),  dynamic ranges ,e.g. .Range(.Range("A" & .Rows.Count).End(xlup),"AF1"))

Here are some inconsistencies

The initial ActiveSheet, Sheet2 and Sheets("Checklist Builder") all appear to be the same Worksheet.  Pick 1 and use it in a With block. (e.g. With Sheet2)
Range("$A$1:$AF$5150").AutoFilter - .Range("$A$1:$AF$150").AutoFilter

This should work "As Is" but it is hard to say without the actual Workbook.  You will have to add a Worksheet, name it "Filter Builder", hide it and forget about it.  I would guess that it should take less than 1 sec to execute.

Sub Macro1()

'TURNS OFF THE SCREEN UPDATING SO IT BRING YOU TO THE FILTER OPTIONS TAB AFTER THE MACRO IS COMPLETE
    Application.ScreenUpdating = False

    Dim data As Variant, results As Variant
    Dim count As Long, x As Long
    With Sheets("Checklist Builder")
        data = .Range("$A$1:$AF$5150").Value
        ReDim results(1 To UBound(data), 1 To 2)
        'Fill array with the values
        For x = 1 To UBound(data)
            If count = 1 Or UCase(data(x, 7)) = "SPECIAL VALIDATION" Then
                count = count + 1
                results(count, 1) = data(x, 7)
                results(count, 2) = data(x, 8)
            End If
        Next
    End With

    'DELIMITS THE DATA SO THE TEXT SPLIT UP IN TO DIFFERENT COLUMNS, DIVIDED UP BY COMMAS

    With Sheets("Filter Builder")
        .Cells.Clear
        .Range("A1").Resize(UBound(results), UBound(results, 2)).Value = results

        .Columns("B:B").TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True

        .Rows("2:1150").Copy
        Sheets("Filter Options").Range("K1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                                                                                :=False, Transpose:=True
        Application.CutCopyMode = False
    End With
    Application.ScreenUpdating = True

End Sub


Split function while reading multiple lines

try-with-resources

If you're on Java 7, you should use try-with-resource on your Scanner:

try (Scanner scanner = new Scanner(System.in)) {
    // your code here
}

This takes care of closing your Scanner at the end, so you do not have do perform an explicit close().

First input

I am not too sure why are you ensuring inputSize cannot be less than 2, since the problem statement only mentioned <= 10. I'll take that to mean an implicit assumption for non-negative values, so yeah even 0 is possibly a valid input. There is also an easier way of getting your first input than performing your validation twice, and while you're at that you should consider putting it in a method:

private static int getCount(Scanner scanner) {
    System.out.println("Enter the value of T Size [0, 10]:");
    int value = scanner.nextInt();
    while (value < 0 || value > 10) {
        System.out.println("Value is not within [0, 10], try again.");
        value = scanner.nextInt();
    }
    scanner.nextLine(); // gotcha
    return value;
}

The gotcha, as you probably have already figured, is that you need to 'consume' the rest of the line first before moving to other inputs. Therefore, I will also suggesting reading as nextLine() instead and then attempt to convert to an int via Integer.parseInt(). You can then catch the NumberFormatException thrown as an invalid input, and re-prompt until a valid integer is entered.

Validating your additional inputs

Note: I'm not sure if integers are implied for numbers, so I'll just go along with what you have shown...

First, I think you are missing the validation on your integers-to-be:

  \$m\$ and \$n\$ (\$1 \le m \le n \le 1000000000\$, \$n-m \le 100000\$)

Second, you should also consider converting and saving each of the integers you encounter in a single input line immediately, instead of storing into a String[] array and then performing the conversion afterwards. This avoids the additional looping which you identified in your question. :)

Come and think of it, putting all these together does sound like a good usage for Java 8 streams...

Java 8 solution ahead

So to conclude, the steps we need are:

Get number of lines (0 <= x <= 10)

stream.limit(getCount(scanner))

We only read in this number of lines, x = getCount(scanner).
Read in a line for x times

Stream.generate(scanner::nextLine)

This creates a new stream where each element is read from the scanner, i.e. System.in, i.e. the user input. This is accessed via a method reference.
On each line, split by a ' ' character

stream.flatMap(Pattern.compile(" ")::splitAsStream)

Pattern.splitAsStream(CharSequence) is a convenient way of tokenizing a line as a stream, which in turn allows us to perform a flatMap() by replacing each element of the source stream with the contents of the resulting stream.
Convert each token as an integer within a certain range

stream.map(Generation::convert)

The sample implementation shown below for convert(String) does not perform any validation. Actually, as a result of the flatMap() operation in the previous step, it will be quite tricky to make sure that \$1 \le m \le n \le 1000000000\$, so I'll leave this as an exercise to the reader... (hint: map each String input as a List to facilitate the validation first).
Collect all results into a Collection for further usage

stream.filter(Objects::nonNull).collect(Collectors.toList())

Since convert(String) may give us null values for invalid integers, we need to exclude them first. Collecting as toList() is just for illustration. If you want to sum the results together immediately, for example, you can change that to .mapToInt(Integer::intValue).sum().

public class Generation { // you probably need a better name too
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            List<Integer> result = Stream.generate(scanner::nextLine)
                    .limit(getCount(scanner))
                    .flatMap(Pattern.compile(" ")::splitAsStream)
                    .map(Generation::convert)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            result.forEach(System.out::println);
        }
    }

    private static int getCount(Scanner scanner) {
        // see implementation above
    }

    private static Integer convert(String value) {
        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}


Program to output the same highest numbers in an array

Note: After posting my answer I found out that the question is a duplicate of this question.

Readability

If you have no values then your code will error when you try to interact with high. You should define high outside the loop.
You should use a function so it's easier to test your code.
You should use full words for variable names.

def largest_orig_pretty(values):
    max_no = 0
    highest = []
    for value in values:
        if value > max_no:
            max_no = value
            highest = [value]
        elif value == max_no:
            highest.append(value)
    return highest

Performance

This however isn't shorter or faster than your code.

When optimizing Python it's almost guaranteed that all C functions are faster than the Python equivalent. And so we can test some changes out:

Remove max_no to make your code smaller.
Remove max_no and use iter to not incur \$O(n)\$ memory.
Try using collections.Counter, in the hopes it's written in C.
Use list.sort to sort the input so we can just take the first elements that are the same.

I did this in multiple ways:

Using a for loop. largest_sort.
Using a functional/iterator approach, but using lambda. largest_sort_semifunctional.
Using a functional/iterator approach, using functools.partial and operator.eq. largest_sort_functional.

Using sorted to not mutate the input list. And otherwise using the same code as largest_sort.
Using max and build a new list using list.count.

Most of the answers in the duplicate question derive from this method.

Allan's answer is the same as my original one. largest_max_count.
Ev.Kounis's answer suggests using a comprehension to build the output list.
Daweo's answer suggested not using list.count and instead use a list comprehension. There are two varients one when they use max once and one where it's used on every iteration.

Grijesh Chauhan's answer suggested storing only the value and a count, rather than building a list.

I have not tested the output of these functions, only the timings. The sample data is also uniform, and so may not accurately describe the expected timings if this assumption is not true.

Disclaimer, graphtimer was written and is maintained by me. It is only to produce the graph.

import collections
import itertools
import operator
import functools

import matplotlib.pyplot as plt
import numpy as np

from graphtimer import Plotter, MultiTimer

def largest_orig(values):
    max_no = 0
    for i in values:
        if i > max_no:
            max_no = i
            high = [i]
        elif i == max_no:
            high.append(i)
    return high

def largest_orig_pretty(values):
    max_no = 0
    highest = []
    for value in values:
        if value > max_no:
            max_no = value
            highest = [value]
        elif value == max_no:
            highest.append(value)
    return highest

def largest_no_max(values):
    if not values:
        return []
    highest = [values[0]]
    for value in values[1:]:
        if value > highest[0]:
            highest = [value]
        elif value == highest[0]:
            highest.append(value)
    return highest

def largest_no_max_iter(values):
    values = iter(values)
    highest = [next(values)]
    for value in values:
        if value > highest[0]:
            highest = [value]
        elif value == highest[0]:
            highest.append(value)
    return highest

def largest_counter(values):
    if not values:
        return []
    c = collections.Counter(values)
    k = max(c)
    return [k] * c[k]

def largest_sort(values):
    if not values:
        return []
    values.sort(reverse=True)
    value = values[0]
    for i, v in enumerate(values):
        if value != v:
            return [value] * i
    return values

def largest_sort_semifunctional(values):
    if not values:
        return []
    values.sort(reverse=True)
    value = values[0]
    return list(itertools.takewhile(lambda i: i == value, values))

def largest_sort_functional(values):
    if not values:
        return []
    values.sort(reverse=True)
    value = values[0]
    return list(itertools.takewhile(functools.partial(operator.eq, value), values))

def largest_sorted(values):
    if not values:
        return []
    values = sorted(values, reverse=True)
    value = values[0]
    for i, v in enumerate(values):
        if value != v:
            return [value] * i
    return values

# Same as https://stackoverflow.com/a/55216417
def largest_max_count(values):
    if not values:
        return []
    maximum = max(values)
    return [maximum] * values.count(maximum)

# Derived from Ev. Kounis' answer: https://stackoverflow.com/a/55216309
def largest_max_count_comprehension(values):
    if not values:
        return []
    maximum = max(values)
    return [maximum for _ in range(values.count(maximum))]

# Derived from Daweo's answer: https://stackoverflow.com/a/55216401
def largest_max_comprehension(values):
    if not values:
        return []
    return [value for value in values if value == max(values)]

# Derived from Daweo's answer: https://stackoverflow.com/a/55216401
def largest_max_comprehension_once(values):
    if not values:
        return []
    maximum = max(values)
    return [value for value in values if value == maximum]

# Grijesh Chauhan's answer: https://stackoverflow.com/a/55254044
def largest_grijesh_chauhan(iterable):
    max = None
    count = 0
    for index, value in enumerate(iterable):
        if index == 0 or value >= max:
            if value != max:
                count = 0
            max = value
            count += 1
    return count * [max]

def main():
    fig, axs = plt.subplots()
    axs.set_yscale('log')
    axs.set_xscale('log')
    (
        Plotter(MultiTimer([
            largest_orig,
            largest_orig_pretty,
            largest_no_max,
            largest_no_max_iter,
            largest_counter,
            largest_sort,
            largest_sort_semifunctional,
            largest_sort_functional,
            largest_sorted,
            largest_max_count,
        ]))
            .repeat(10, 10, np.logspace(0, 5), args_conv=lambda n: list(np.random.rand(int(n))))
            .min()
            .plot(axs, title='Maximums')
    )
    fig.show()

    fig, axs = plt.subplots()
    axs.set_yscale('log')
    axs.set_xscale('log')
    (
        Plotter(MultiTimer([
            largest_orig_pretty,
            largest_sort,
            largest_max_count,
            largest_max_count_comprehension,
            largest_max_comprehension,
            largest_max_comprehension_once,
            largest_grijesh_chauhan,
        ]))
            .repeat(10, 10, np.logspace(0, 3), args_conv=lambda n: list(np.random.rand(int(n))))
            .min()
            .plot(axs, title='Maximums max count derived')
    )
    fig.show()

if __name__ == '__main__':
    main()

Resulting in the following timings:

The following is a comparison of the SO answers:

Conclusion

[Performance] sort is the fastest method when there are ~10 or more elements in the list. Despite the \$O(n\log{n})\$ big-O time complexity it's the fastest as it's written in C.

It mutates the input which may not be desirable, and using sorted destroys the performance gain.

Using a plain for loop is faster than itertools.
[Performance] Using max and list.count is the fastest method if you are not allowed to mutate the list.
[Size] Using max and list.count results in the smallest amount of lines of code.

And so depending on your need I'd use either largest_max_count or largest_sort.


Finding the position in a triangle for the given challenge

Your current algorithm is very inefficient. I would use the following algorithmic approach:

def answer(x, y):
    y_diff = y - 1
    corner = x + y_diff
    id = corner * (corner + 1) // 2
    id -= y_diff
    return str(id)

This method takes advantage of basic algebra. It uses the sum of the arithmetic progression of x to calculate the id of the bottom right corner, and then subtracts the difference of the input coordinate from the bottom right corner. The reason it take the y difference is because moving 45 degrees diagonally down right is equivalent to moving down (y-1) units and moving right (y-1) units. Is is much more efficient than your current method: instead of an increasing numbering of iterations through range, it does one multiplication.

Benchmark

Testing your code compared to mine, mine runs about 10,000 to 100,000 times faster for random values of x and y between 1 and 100000. This is a very significant performance difference.

Additionally, in benchmarking, I discovered a slight bug in your current implementation. I didn't analyze your implementation deeply to understand it, but it seems that your current implementation returns an output corresponding to the reversed inputs (so for example, if I input (3, 2), the output is correct for (2, 3).) I suspect this may have been missed in your personal testing because the input is reversed of traditional coordinate order, i.e. you ask for y coordinate input before you ask for x coordinate input. I fixed this in my testing by switching all occurrences of x (and related variables) with y and vice versa.

Some notes

  Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y).

So it seems your answer should be in the form:

def answer(x, y):
    # ... algorithm
    return str(output)

Also, use consistent spacing:

in_sum =i + 2 to in_sum = i + 2

And take advantage of +=:

sum_in_x = sum_in_x + range(x)[i] to sum_in_x += range(x)[i]
sum_in_y = sum_in_y + in_sum to sum_in_y += in_sum


Interesting question,

I spent a bit of time coding different approaches before writing this. Initially I just was going to point to my SO answer but then I saw you have some more requirements that are not met.

Concern #1

I dislike libraries where I have to initialize stuff outside of the constructor, the constructor should initialize an object so that it is usable! Why give me a half baked object that I cannot use? The idea of being able to swap out a separate initializer is typical YAGNI.

Concern #2

In my mind, the caller should decide whether to enable or disable (possibly based on a production flag or not), for your code to take care of both concerns independantly seems overkill.

Concern #3

It seems over-contrived to me ;)

I did like though the idea of fool-proofing all console methods for an ancient legacy code base, and kept that with 2 simple methods to turn of or on all output in my approach:

function logController(){

  var methods = [
    'assert', 'clear', 'count', 'debug', 'dir', 'dirxml',
    'error', 'exception', 'group', 'groupCollapsed', 'groupEnd',
    'info', 'log', 'markTimeline', 'profile', 'profiles',
    'profileEnd', 'show', 'table', 'time', 'timeEnd',
    'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
  ];
  //The one acceptable time we can pollute the global namespace ;]
  console = console || {};

  function stop(){
    var _method;
    methods.forEach( function (method){
      _method = '_' + method;
      console[_method] = console[_method] || console[method];
      console[ method] = function noLog(){};
    });
  }

  function start(){
    var _method;
    methods.forEach( function (method){
      _method = '_' + method;
      console[method] = console[_method] || console[method] || function noLog(){};
    });
  }
  start();

  return {
    start: start,
    stop: stop
  };
}

flow = logController();
console.log( 'Normal logging, next is 123' );
console.log(  123 );
console.log( 'Start logging (which is default state), next is 123' );
flow.start();
console.log(  123 );
console.log( 'Stop logging (which is default state), next is "start logging again"' );
flow.stop();
console.log(  123 );
flow.start();
console.log( 'Started logging (which is default state), next is 123' );
console.log(  123 );

I will keep the exercise to make this work with AMD/UMD in your capable hands ;)


Excel Data Manipulation - parse, match and create

I've not seen or used petl before, but there are some ways to improve your code.

Move things out of the global scope.
Make a function for your most common functions.
Change petl.select to petl.selectis or petl.selectisnot.

Since you do:

nok_rows = petl.antijoin(serial_rows, petl.cut(stacked_joins, ['serial number']), key='serial number')
nok_rows = petl.addfield(nok_rows, 'file', 'NOK')

So many times, you should change it to a function.
This function could take a fn of petl.antijoin, a left of serial_rows, a right of stacked_joins and a field of 'NOK'.

And so you can use:

def change_row_file(fn, left, right, field):
    rows = fn(left, petl.cut(right, 'serial number'), key='serial number')
    return petl.addfield(rows, 'file', field)

change_row_file(petl.antijoin, serial_rows, stacked_joins, 'NOK')

Adding this, with the changes to petl.select, to main_compare can result in something like:

def main_compare(table):
    serial_rows = petl.selectisnot(table, 'serial number', None)
    return petl.stack(
        change_row_file(petl.join, serial_rows, main, 'OK'),
        change_row_file(petl.antijoin, serial_rows, main, 'NOK'),
        petl.selectis(table, 'serial number', None))

There's not much more that I think could do with improving apart from having nothing in your global scope.
And then adding a global constant for the serial column, say SERIAL_COLUMN = 'serial number'.
This significantly reduces the amount of magic strings, to ones that aren't repeated (except 'NOK').

This can result in (Not pep8 compliant to remove a scroll bar):

import petl
SERIAL_COLUMN = 'serial number'

def change_row_file(fn, left, right, field):
    rows = fn(left, petl.cut(right, SERIAL_COLUMN), key=SERIAL_COLUMN)
    return petl.addfield(rows, 'file', field)

def update_main(main, one, two):
    serial_rows = petl.selectisnot(main, SERIAL_COLUMN, None)
    stacked_joins = petl.stack(
        change_row_file(petl.join, serial_rows, one, 'ok, 1.xlsx'),
        change_row_file(petl.join, serial_rows, two, 'ok, 2.xlsx'))
    return petl.stack(
        stacked_joins,
        petl.selectis(main, SERIAL_COLUMN, None),
        change_row_file(petl.antijoin, serial_rows, stacked_joins, 'NOK'))

def main_compare(main, table):
    serial_rows = petl.selectisnot(table, SERIAL_COLUMN, None)
    return petl.stack(
        change_row_file(petl.join, serial_rows, main, 'OK'),
        change_row_file(petl.antijoin, serial_rows, main, 'NOK'),
        petl.selectis(table, SERIAL_COLUMN, None))

def main():
    main = petl.fromxlsx('main.xlsx')
    one = petl.fromxlsx('1.xlsx', row_offset=1)
    two = petl.fromxlsx('2.xlsx')

    petl.toxlsx(update_main(main, one, two), 'mainNew.xlsx')
    petl.toxlsx(main_compare(main, one), '1New.xlsx')
    petl.toxlsx(main_compare(main, two), '2New.xlsx')

if __name__ == '__main__':
    main()


Dynamically changing autocomplete source option jQuery

One way to make it extensible is to make it reusable rather than stick it to one dropdown. You can even make it into a jQuery plugin so that it looks like this:

$('.someAutocompleteBox').dependentAutoComplete({

  /* the selector of the element to monitor changes */
  elementToMonitor : '.theElementToMonitor',

  /* value set, which correspond to the value of the previous input */
  sets : {
    drugs : DRUG_URL,
    hospitals : HOSPITAL_URL,
  }

  /* you can monitor depending on the event and which value to grab */
  triggeringEvent : 'keyup',
  propertyToCheck : 'value'
});

So in this example, I set .someAutocompleteBox to change sets when a keyup event is triggered from .theElementToMonitor. Then the plugin will grab the property defined in propertyToCheck and check it against the sets object which URL to use as source. Pretty simple isn't it?

As for jQuery plugin creation, you can use the jQuery Boilerplate to start off with a template. Everything else is self-explanatory, which is:

In the init() function of your plugin code, attach an event stated by triggeringEvent to the element stated by elementToMonitor.
When the event is fired, the handler should grab the value of the property defined in propertyToCheck.
Do a lookup from the passed sets property and grab the URL of the corresponding key (which is the value grabbed from the property earlier)
Update the current element's autocomplete source.

The plugin code (in the init) should look something like this:

init: function () {
  // nothing to check, nothing to check against
  if(!this.settings.elementToMonitor || !this.settings.sets) return;

  // Save the context
  var instance = this;

  // Attach the defined event to defined dependency
  $(this.settings.elementToMonitor)
    .on(this.settings.triggeringEvent,function(){

      // Get the value at defined property
      var value = $(this).prop(instance.settings.propertyToCheck);
      var url;

      // Check if we have that url in the set, return if not
      if(!(url = instance.set[value])) return;

      // Update the source accordingly
      $(instance.element).autocomplete({
        source = url;
      });
    });
}


General
I found no "dumb mistakes associated with generic code". Good job.
Still, there are some points which can be improved.
(Aren't there always?)

The first point is encapsulation.
Letting nodes float around free, instead of keeping them in their dedicated container, or (rarely) evacuating them to a handle for re-insertion, is not recommended.
Admittedly, a properly written container won't suddenly sprout a cycle, so there you are.
Also, it would detract from the point of your code, so let's leave it alone this time.
Node
Node's default ctor won't initialize its members. The fix is easy:
Just add in-class initializers.
Doing so even allows you to simplify your second constructor, removing the second mem-initializer.
That is, if Node should even have anything but its data members. I personally prefer to have my Node's not getting in the way when implementing my containers.
Floyd's algorithm
The name detect_cycle_constant_time() is a bald-faced lie. The algorithm needs linear time in the number of nodes.
Doing an early return would simplify your code. As you don't allocate any resources, there goes the only argument against. Doing data-flow analysis is much more involved.
There are more loops than the humble while-loop. Sometimes, they are even useful.
Using auto would slightly simplify your local variable definitions.
Whether to use class or typename for template arguments is a matter of taste. All else being equal, I prefer brevity.
Modified Code
template <class T>
struct Node {
    T val = T();
    Node* next = nullptr;
    Node() = default;
    Node(T x) : val(x) {}
};

template <class T>
Node<T>* detect_cycle_floyd(Node<T>* head)
{
    auto n1 = n2 = head;

    do {
        if (!n2)
            return n2;
        n1 = n1->next;
        n2 = n2->next;
        if (!n2)
            return n2;
        n2 = n2->next;
    } while (n1 != n2);

    // second phase of Floyds's algorithm
    for (n2 = head; n1 != n2; n2 = n2->next)
        n1 = n1->next;
    return n1;
}


Honestly there's not much code to comment on, it's also a programming challenge, so there's not much incentive to make it any better than it is. I too would have done it your way.

The only objective criticism I have is I'd just add a function regex_options to build the non-capturing group.

Other than that I'd apply this to the creation of g, o, l and e. As I think it's a little cleaner. But you may want to perform it before "".join, and after regex = (g, o, o, g, l, e).

import re

def regex_options(options):
    options = (re.escape(o) for o in options)
    return "(?:{})".format("|".join(options))

g = regex_options(["g", "G"])
o = regex_options(["o", "O", "0", "()", "[]", "<>"])
l = regex_options(["l", "L", "I"])
e = regex_options(["e", "E", "3"])

regex = "^{}$".format("".join((g, o, o, g, l, e)))

print(bool(re.match(regex, input())))

If this were professional code, I'd suggest using an if __name__ == '__main__': block, and possibly a main function.


Binary file Handling - Add,modify and display records

Here are some things that may help you improve your code.

Use the required #includes

The code uses strcpy which means that it should #include <cstring>.  It also uses std::cout which means it should #include <iostream>.  Always use the required include files per the standards specification and not just the ones that seem sufficient to make it compile on your machine.

Isolate platform-specific code

In this code, there are several things that are DOS/Windows only including #include <conio> and the getch() function within that, and also #include <process> which I can only guess is a C++ version of the standard process.h.  Your code runs successfully on Linux if I supply those missing functions, but it would be nice if there were an #ifdef WINDOWS already in the code so that one could recompile without having to alter the source code.

Don't use gets

Using gets is not good practice because it can lead to buffer overruns.  It has been removed from the C11 standard and marked "obsolete" in POSIX 2008.  Similarly, it should not be used in C++ program.  Instead use fgets or better, declare name to be a std::string and use std::cin >> name;

Follow standard declaration of main

Your compiler may allow you to declare void main() but that construction is technically only valid for what are called "non-hosted" environments, e.g. one in which you are not running Windows.  For that reason, you should use the standard int main() instead.

Whitespace improves readability

Allofyourwordsarecrammedtogether.  Inserting some spaces in your lines will make them much easier to read.  For example, instead of this:

while(f.read((char*)&h,sizeof(h)))

Use this:

while (f.read((char *)&h, sizeof(h)))

Fix your formatting

The formatting of this code is absolutely diabolical.  The code executed within above-mentioned while loop, for example, is at the same indent level as the while itself. Choose a standard format and use it consistently. Being consistent helps others read and understand your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  For this program, I'd advocate removing it and simply using the std:: prefix where needed.

Make better use of C++ objects

The code is already using a housing class, but doesn't make very good use of that class.  For instance, all of the actual binary input and output is done inside main while it could instead be relegated to the housing class.  Also, the file is simply a collection of housing objects.  Why not represent that in a std::vector<housing> or similar?

Create a function rather than repeating code

In several places in the code, the file is opened, read, a housing record read and then the file is closed again.  It would make much more sense and make the code easier to read, understand and maintain, if that functionality were instead encapsulated in a function; probably most appropriately a member function of a house collection object.

Use a switch instead of multiple if or if ...else chains

The logic is much easier to see if a switch statement is used instead of a long if...else chain.  The default case can then be used solely for error cases.

Use longer, more meaningful names

Names like h and f are not very descriptive.  Instead, you might use house and datafile.

Avoid the use of global variables

I see that opt is declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable. In this case, there is really no reason that opt couldn't be local to main.

Eliminate the goto

Instead of the goto, use while (!done) and set done to true when the user indicates a desire to exit the program.

Fix the bug

The assign() member function is written like this:

void assign {
    if (income < 15000)
        strcpy(type, "LIG");
    else if (income >= 15000)
        strcpy(type, "MIG");
    else if (income >= 25000)
        strcpy(type, "HIG");
}

However, I think you'll find that HIG will never be assigned no matter how high the reported income.  If the user enters a value of 999999, it will be assigned "MIG".

Eliminate "magic numbers"

In a number of cases, the code uses "magic numbers" such as 20 and 15000 that have no obvious meaning.  These would be better as named constants.  There is a similar argument to be made about the file name "hous.dat" -- this should be made a named constant instead of repeating it three times within the code.


Reverse words in a string without affecting space

Use compiler warnings

You should always enable compilers warning in c++. For your code, clang & g++ gives the following warnings (live demo):

prog.cc:14:29: warning: multi-character character constant [-Wmultichar]
        if(s[i]!=' '||s[i]=='/0'){
                            ^
prog.cc:13:19: warning: comparison of integers of different signs: 'int' and '...' (aka 'unsigned long') [-Wsign-compare]
    for(auto i=0;i<s.size();){
                 ~^~~~~~~~~
prog.cc:14:27: warning: result of comparison of constant 12080 with expression of type '...' (aka 'char') is always false [-Wtautological-constant-out-of-range-compare]
        if(s[i]!=' '||s[i]=='/0'){
                      ~~~~^ ~~~~

The ones about s[i]=='/0' are especially concerning. You probably meant s[i]=='\0'. I don't know if you want to handle other possible separators of a string (like tabs, line feeds). If it's the case, you should have a look at std::isspace or std::isblank.

The one about the for suggests that the type int (deduced for auto) might not be the most suited as a string/vector index. According to this post, the most portable index type to use would be std::string::size_type.

Avoid std::string copy

Your code is performing a lot of string construction / copy / concatenation. They all can cause memory allocation/deallocation, which can be quite costly compared to the rest of your code. You should be able to avoid most of them.

Output: generate the result directly in a single std::string

You know exactly the size of the output string re (same size as input). You can preallocate it with std::string::reserve.
Pass a reference to re to void oreverse(std::string& output,/*InputType*/ input), and directly push_back the characters of the input in reverse order.

Input: work directly on the input string

pass your input string by (const) references in both functions: const std::string&.
avoid std::string::substr:

C++17: you can use std::string_view instead of std::string. It's substr method won't do any copy.
Pre-C++17: pass iterators to the input string to oreverse. Or a (const) reference to the input string, with start/end indices.

Use "static" for global functions when applicable

Declaring a global function as "static" indicates to your compiler that your function is used only in the current translation unit (current *.cpp file). The compiler can use this information to do better inlining decisions (see for example gcc/g++: -finline-functions-called-once option).


If true, true. If false, false.

Your code is filled with situations like this:

if someCondition:
    variable = True
else:
    variable = False

You can replace all those occurrences with a simple assignment:

variable = someCondition

If, and if not

Additionally, there's no need to add == True in a comparison. The Python way of x == False is to do not x

Conditional ternary operator

if wordy11:
    wordy = "sametrue"
else:
    wordy = "samefalse"

Can be written as:

wordy = "sametrue" if wordy11 else "samefalse"

Variable names

What on earth is wordy? What type is it? It seems to be one variable used for all kinds of things. I'd recommend making these separate variables and using more descriptive variable names.

Result

This will clean up your code a bit at least, to this point:

"""Docstring"""
import words

def nicer_englishify_word(word):
    """Docstring"""
    wordx = word.lower()
    wordy = ""

    if wordx.endswith('moo'):
        wordy1 = wordx[-3] + wordx[:-3]
        wordy2 = wordx[:-3]
        wordy11 = wordy1 in words.get_word_list()
        wordy22 = wordy2 in words.get_word_list()
        if wordy11 == wordy22:
            wordy = "sametrue" if wordy11 else "samefalse"
        else:
            if not wordy22:
                wordy = "[" + wordx[-3] + wordx[:-3] + "]"
            else:
                wordy = "[" + wordx[:-3] + "]"
        wordy = wordx[-3] + wordx[:-3] + " or " + wordx[:-3]
        wordy = "<" + wordy + ">" if wordy == "sametrue" else "(" + wordy + ")"
    else:
        wordy = wordx[-3] + wordx[:-3]
    return wordy


How to make this random number game better?

A few observations:

In place of the while loop with you managing the numAttempts index,  why not use a for loop with the in keyword? i.e. for numAttempts in range(3):
Note that with the above, you can still use your else block (for supports the else clause! :)  )
Multiple games keep asking for your name. Unless your code has Alzheimer's, consider avoiding that :)
Related to the above : Structurally, you've chosen to recurse to play another game. Why not keep your game atomic and keep the whole offer another game choice/logic external to your function?
Your second elif does not make sense. Why not just else (guess can only be < number now!)


How to verify if value already added to the list and if so, then update the value?

user = User.get_by_key_name(user_key_name)
if user:

Python convention is to use user is None when checking against None

    field_names = user.field_names
    field_values = user.field_values
    field_scores = user.field_scores

Why copy these references? It doesn't help you much.

    if field_name in user.field_names:
        # field_names[field_index] = field_name
        field_index = user.field_names.index(field_name)

Use index to check if field_name is present. That way it doesn't have to search through the lists twice.

        field_values[field_index] = field_value
        field_scores[field_index] = field_score

If possible, avoid maintaing parrallel lists. In this case, it looks like maybe you should have a dictionary of strings to tuples.

    else:
        field_names.append(field_name)
        field_values.append(field_value)
        field_scores.append(field_score)
    user.field_names = field_names
    user.field_values = field_values
    user.field_scores = field_scores

Unless user does something odd, this has no effect. Assignment doesn't copy in python, it just copies the references.

    user.put()


Why not:

type KeySize   = Integer
type ValueSize = Integer
type Header    = (KeySize, ValueSize)

Instead of commenting, like you did here:

type Header    = (Integer, Integer)
               -- keysize  valuesize

Same about ValueInfo.


Populate a networkx graph with tuples of varying lengths

Tuples of varying lengths are a bit unusual.  Perhaps those would be better as lists instead.

itertools is your friend.  You can write, equivalently:

import itertools

G = nx.Graph()
for node_tuple in node_list:
    G.add_edges_from(itertools.product(node_tuple, node_tuple))

If you want to list each pair of nodes just once instead of twice, and including self-edges use itertools.combinations_with_replacement(node_tuple, 2) instead.


Unity Gravity script lowering FPS because of overlap sphere checking collision

You are allocating like crazy use Physics.OverlapSphereNonAlloc
dont do List<Rigidbody> rbs = new List<Rigidbody>();
Replace with o(1) lookup HasTagDownHierarchy(otherBody.transform, "Boat") also avoid tags. Use markup classes.
edit: With look up I mean, in Boat Awake method cache the Colliders in a look up Dictionary<Collider, Boat>


Naming

Avoid single-letter or shortened form variable names. Extra characters on a variable's name are free, and work wonders for a maintenance programmer down the line.

e.g.

double n = 0;

would better be:

double output = 0;

Additionally, I'm not sold on the name GetDoubleValue. At no point does this method retrieve the value from anywhere. What this method does is conversion, so it should be appropriately named as such.

Var

Use the var keyword when defining local variables where the right hand side of the definition makes the type obvious. This looks cleaner and saves time when it comes to changing types during refactoring.

e.g.

bool separatorFound = false;

should be

var separatorFound = false;

You should also use var when declaring foreach and for loop iterators.

e.g.

for (int k = (negative ? 1 : 0); k < input.Length; k++)

should be:

for (var k = (negative ? 1 : 0); k < input.Length; k++)

Braces

Always use braces for if statement bodies. It's cleaner, more explicit in intent, and it's quicker should you later decide to add extra lines to the body.

e.g.

if (!char.IsDigit(c))
    return Double.NaN;

should be:

if (!char.IsDigit(c))
{
    return Double.NaN;
}

Design

Why have you created the function CustomPow when all you're really doing is repeatedly multiplying by 10? It seems this is a case of over-abstraction, unless you plan to use the method elsewhere too.

Why make GetDoubleValue private? It sounds like a useful function you may want to use elsewhere or in other projects. I suspect it's private because it is in a class it does not belong in, and you don't want somebody calling StringLoader.GetDoubleValue or something like that.

Put it in a utility class or an extension method somewhere, it doesn't make sense as a method of your string loader class or whatever.


HTML 5 introduces the  element.

Don't use presentational attributes, like align, use CSS.

The alt attribute is mandatory. If the text that follows it duplicates the information in the image, then use alt="".

The longdesc attribute has been removed from HTML 5. In HTML 4 it should point to an HTML document that describes the image (for people who cannot see it), not the image itself.

          Fellows and Fullwood

The  element is obsolete and should not be used (and I'm pretty sure 12 isn't a valid size for it anyway). Use CSS.

HTML 5 introduces the  element.

          <u1>
Home

About Us

News

Careers

Contact Us

          </u1>

HTML 5 introduces

Contact us
<form  action=""

You can omit the action attribute entirely if you want to resolve to the current URI.

         method="POST" enctype="multipart/form-data">

              <input type="hidden" name="action" value="submit"/>

Most of the paragraphs in this form at dubious at best but this is just wrong. There is no content for the user at all, and certainly no paragraph.

Your name:

Please learn to love labels

            <input name="name" type="text" value="" size="30"/>

In general, prefer container elements and CSS margins/paddings to hard line breaks.
 is most useful when line breaks are a significant part of content which is otherwise continuous (such as street addresses or poetry).

&copy;Copyright Fellows and Fullwood 2014.

HTML 5 introduces the  element.


Finding 10-unique-digit number with i-first-digits divisible by i

Style (and related tools)

A few things are wrong concerning the style (mostly matter of whitespace). Python has a coding guideline called PEP 8. You can use pep8 (or its online version) to check it automatically and autopep8 to try to fix this automatically. You'll find various other convenient tools to check your code such as pylint, pyflakes or pychecker.

Making things more concise

You can use string.digits to have all digits.

Also, you are using more variables that you actually need.

Finally, you don't need to precise 0 in your string slicing and all your permutations will have 10 characters so you don't have to try to take the fist 10 :

Your code becomes :

# join the permutation lists into single numbers by joining each into a string
nums = [''.join(item) for item in itertools.permutations(string.digits)]

for i in range(10, 1, -1):
    nums = [x for x in nums if int(x[:i]) % i == 0]
    print "%-10d # of result can be divided by %d" % (len(nums), i)

print nums

Solution - algorithm, math, etc

Your solution looks interesting in that sense that you iterate through less and less numbers (also, starting from 10 to remove many solutions from the very beginning is a nice touch). However, the issue is that you have to check all iterations at the very beginning and this is quite costly. Also, you keep a list of them in memory.

Let's try to do things differently.

For a start, we know that the number has to be divisible by 10. Therefore, we know that the 0 will be in last position.

>>> print(len(list(itertools.permutations(['1','2','3','4','5','6','7','8','9','0']))))
3628800
>>> print(len(list(itertools.permutations(['1','2','3','4','5','6','7','8','9']))))
362880

Your first iteration should be 10 times faster and your code is indeed roughly 10 times faster.

# join the permutation lists into single numbers by joining each into a string
nums = [''.join(item) for item in itertools.permutations(['1','2','3','4','5','6','7','8','9'])]

for i in range(9, 1, -1):
    nums = [x for x in nums if int(x[:i]) % i == 0]
    print "%-10d # of result can be divided by %d" % (len(nums), i)

print [n + '0' for n in nums]

Simimarly, the divisibility by 9 does not need to be checked because of the following rule (and the fact that the sum of the first 10 numbers is divisible by 9) : remove that check and you have yet another performance gain.

However, for an actual gain, you could go the other wat round : trying to build number by looking at the different candidates of length 1, 2, and so on.

Here is how I did it and it seems to be really fast :

cand = {0}
for i in range(1, 10):
    cand = { n for n in (10 * c + d for c in cand for d in range(1, 10) if str(d) not in str(c)) if n % i == 0}
print [n * 10 for n in cand]

Also, if you were to do things manually, after notificing that 0 has to be in 10th position so that the number is divisible by 10, you can notice that it leaves only 5 to be in 5th position so that the number is divisible by 5. You have 2, 4, 6, 8 left for 2, 4, 6 and 8th position and 1, 3, 7, 9 for 1, 3, 7 and 9th position. You can do this programmatically for yet another performance optimisation.

cand = {0}
for i in range(1, 10+1):
    r = [0] if i == 10 else \
        [5] if i == 5 else \
        [1, 3, 7, 9] if i % 2 else \
        [2, 4, 6, 8]
    cand = { n for n in (10 * c + d for c in cand for d in r if (str(d) not in str(c))) if n % i == 0}
    print(i, len(cand), cand)
print cand


The code could be simpler and more Pythonic. For example:
pin_no = ('1111', '2222', '3333')

while True:

   pin_no = input("Input the no : ")

   if pin_no == '1111' or pin_no == '2222' or pin_no == '3333':

could simply be:
valid_pins = ('1111', '2222', '3333')
pin_no = input("Input the no : ")
if pin_no in valid_pins:

Thus avoiding repetition.
This code:
user =  input("\n\n 1. Userdetails \n 2. Education \n 3. Work History \n 4. Bank History \n" ' 5.
Credit History \n\n  '  )

could become:
str = ("Userdetails", "Education", "Work History", "Credit History")
for num, value in enumerate(str, start=1):
    print(f"{num}) {value}")

user = input("Choose an option: ")

which gets you output like this: (note that I use enumerate for automatic line numbering)

1) Userdetails
2) Education
3) Work History
4) Credit History
Choose an option:

The problem with this code is that your data is polluted with linebreaks. Just don't. The formatting can be done in your code. For example the join function can easily break down a tuple:
print("\n".join(str))

Userdetails
Education
Work History
Credit History

As it stands your class is underutilized. Instead of this:
Steve_McQueen = userdetails ('Steve McQueen \n', '\nArizona High School \n\n' 'GCSE English: Grade A
\n' 'GCSE Maths:   Grade A \n', 'GSA LTD', 'Lloyds Bank ', 'Average')

I would strongly advise to use keywords arguments like this:
Steve_McQueen = userdetails (education='Arizona High School', work_history='GSA LTD', bank_history='Lloyds Bank')

First of all, it is more clear what the values relate to. And then you can provide arguments in the order you want (so your code won't break if you insert new arguments in the future, or change their order).
Reference: Positional and Keyword Arguments
Note that by convention Python variables should be lowercase.
I am not sure the class is beneficial here. You could simply make up a dict of all users. That depends on the ultimate purpose. As an example:
people = {
    '1111': {
        'name': 'Tom Watts',
        'education': 'Sidney Stringer School',
        'grade': 'GCSE English: Grade A'
    },
    '2222': {
        'name': 'Bill Gates',
        'education': 'Binley Woods School',
        'grade': 'GCSE English: Grade A'
    },
    '3333': {
        'name': 'Steve McQueen',
        'education': 'Arizona High School',
        'grade': 'GCSE Maths:   Grade A'
    }
}

Then:
>>> people['2222']['name']
'Bill Gates'
>>> people['2222']['education']
'Binley Woods School'

And then, provided that your dict is defined beforehand, the list of valid 'pins' can be built automatically:
# list comprehension
valid_pins = [k for k in people.keys()]

# what the list comprehension returns:
[k for k in people.keys()]
['1111', '2222', '3333']

No need for hardcoding numbers.
Thus, you could do something like this:
# list comprehension: get the list of valid pins from dict 'people' defined above
valid_pins = [k for k in people.keys()]

while True:
    pin_no = input("Input the no : ")
    if pin_no not in valid_pins:
        print ("please try again ")
    else:
        # show details of matching user
        print(people[pin_no])


Python decorator to support static properties

You've masked a bug, in __setattr__ a property raises an AttributeError if the setter hasn't been defined. This causes you to overwrite the property.
(As you've said) There's no distinction between a class property and an instance property. You can change it so there is, but it doesn't allow the property to only be defined on the class, not the instance.
You can just define the static properties on the metaclass. This removes a lot of the headaches.
If you really want to define everything onto the class not the metaclass then you can make the metaclass hoist the wanted functions into a new metaclass. This means everything works as if you only defined two metaclasses with the properties correctly defined.

No fancy changes:

class MyMeta(type):
    @property
    def class_(self):
        return self._class

    @class_.setter
    def class_(self, value):
        self._class = value

    @property
    def class_instance(self):
        return self._class_instance

    @class_instance.setter
    def class_instance(self, value):
        self._class_instance = value

class Test(metaclass=MyMeta):
    class_instance = MyMeta.class_instance

    @property
    def instance(self):
        return self._instance

    @instance.setter
    def instance(self, value):
        self._instance = value

Hoisting:

class classproperty(property):
    pass

class classinstanceproperty(property):
    pass

class StaticProperty(type):
    def __new__(self, name, bases, props):
        class_properties = {}
        to_remove = {}
        for key, value in props.items():
            if isinstance(value, (classproperty, classinstanceproperty)):
                class_properties[key] = value
                if isinstance(value, classproperty):
                    to_remove[key] = value

        for key in to_remove:
            props.pop(key)

        HoistMeta = type('HoistMeta', (type,), class_properties)
        return HoistMeta(name, bases, props)

class Test(metaclass=StaticProperty):
    @classproperty
    def class_(self):
        return self._class

    @class_.setter
    def class_(self, value):
        self._class = value

    @classinstanceproperty
    def class_instance(self):
        return self._class_instance

    @class_instance.setter
    def class_instance(self, value):
        self._class_instance = value

    @property
    def instance(self):
        return self._instance

    @instance.setter
    def instance(self, value):
        self._instance = value

These both pass the following tests: (I could only get your approach to work with instance and class instance)

test = Test()
test._instance = None
test.instance = True
assert test._instance is True
assert test.instance is True
test.instance = False
assert test._instance is False
assert test.instance is False

Test._instance = None
Test.instance = True
Test.instance = False
assert Test._instance is None
test._instance = True
if Test._instance is not True:
    print("instance can't be used after modifying class")

Test._class_instance = None
Test.class_instance = True
assert Test._class_instance is True
Test.class_instance = False
assert Test._class_instance is False

test = Test()
test._class_instance = None
test.class_instance = True
assert test._class_instance is True
assert Test._class_instance is False
test.class_instance = False
assert test._class_instance is False

Test._class = None
Test.class_ = True
assert Test._class is True
Test.class_ = False
assert Test._class is False

test = Test()
test._class = None
test.class_ = True
assert test._class is None
assert Test._class is False
test.class_ = False
assert test._class is None


Try to implement comments tree for Django

A few comments regarding style:

As pointed out by @jonrsharpe

Please have a look at PEP8
Use for spaces for each indentation level

Naming

Use capitalized words for class names (commentTree -> CommentTree)
Use underscores for methods (findById -> find_by_id)

Do not use spaces around the equal sign to set default values for arguments (parentId = 0 -> parent_id=0)
Review hardcoded booleans since usually they are not needed:

self.isLeaf = True if len(self.childrens) > 0 else False
self.is_leaf = len(self.children) > 0  # True if ... else False not needed

root = 1 if self.isLeaf == False else 0
root = 1 if not self.is_leaf else 0  # False not needed
root = int(not self.is_leaf)  # boolean to int conversion

Do not use builtin name functions for arguments (id)
Note that children is already plural

Regarding the code:

addComment method

What is the goal of the new commentTree object id calculation? Shouldn't be easier to get a new id from the database itself?
What is the benefit of being able to add a node as a child of a node that is not the node for which the method was called. This makes the API confusing in my opinion.

getParent method

What is the expected returned value when self.parent is None?
If the expected value is None, then the whole method implementation could be return self.parent

getSize method

Why is there a node parameter to this method? Shouldn't return the length of the tree object itself?
This method implementation should be recursive. Note that each child may have children on its own.

findById method

Why don't you like the recursive implementation? Recursion is what makes them implementation easier and I don't think you need to handle more levels than allowed by the interpreter
In the recursion the base case, the one for a leaf node, is missing
I'd try something like this:

def find_by_id(self, comment_id):
    """Find node by id."""
    if self.node_id == node_id:
        return self

    if self.is_leaf:
        return None

    for child in self.chidren:
        node = child.find_by_id(id)
        if node:
            return node

getSiblings method

Why is there a node parameter to this method? Shouldn't return the siblings of the current node?
There is no need to implement any recursion since siblings are the nodes at the same level of the tree.
I'd try something like this:

def get_siblings(self):
    """Get sibling nodes."""

    # Get parent (not implemented, but using find_by_id on the root node should work)
    parent = ...

    return [node for node in parent.children if node.id != self.id]

I hope this helps.


Client categorisation based on hourly payment

I like @SergeiiK's first solution, but we can make this more declarative:

GRADES = {
  germany: {
    "A" => 35...Float::INFINITY,
    "B" => 30...35,
    "C" => 25...30,
    "D" => 0...25,
  },
  sweden: {
    "A" => 400...Float::INFINITY,
    "B" => 350...400,
    "C" => 300...350,
    "D" => 0...300,
  },
}

def category_for(client)
  GRADES[client.country].find do |_, range|
    range.cover?(client.hourly_rate)
  end.first
end

Client = Struct.new(:country, :hourly_rate) # just for demonstration

p category_for(Client.new(:germany, 26))
# => "C"

p category_for(Client.new(:sweden, 7000))
# => "A"

You'd probably want to add some error handling to category_for for invalid inputs.

Note that the inner Hashes are Hashes for aesthetics only. Using Enumerable#find on a Hash will iterate over its key-value pairs one by one just as it would an array of key-value pairs ([ [ "A", 35...Float::INFINITY ], ... ]), making lookup O(n) instead of O(1) (ish) like normal Hash lookup. This is just prettier than nested arrays. This won't be as fast as a case solution, either, but unless you're, say, "grading" hundreds of thousands of clients at once you won't notice a difference.


Check multiple subdirectories and delete if file exists

Your approach is very inefficient

the array $txtfile is already in memory
iterating it and per entry searching recursivly the directories (the var $dir in fact also includes files) creates a lot of unneccessary overhead.

$WorkingDir = 'D:\TEST\'
$txtFile = Get-Content "D:\TEST\Files.txt"

Get-ChildItem $WorkingDir -Recurse|ForEach-Object{
    If ($txtFile -contains $_.Name){
        Remove-Item $_.FullName -WhatIf
    }
}

If the output looks OK, remove the trailing -WhatIf


Core-data object with relationships conforming protocol in swift

NSManagedObjects already have a property for their current context. It is weak however, which is usually ok for most cases because you would retain the context in the class which is using the objects or in the fetch controller that fetched them. If you are using a child context then you need to be sure to retain that otherwise the object fetched from it will lose it.

More info here.


Convert Array CSV to Object using Header

You can also use built-in methods such as map and reduce. According to JSPerf they are as fast and the code is shorter, so you could potentially get rid of the Underscore dependency:

function csvToObject2(data) {
  return data.slice(1).map(function(xs) {
    return xs.reduce(function(acc, x, i) {
      acc[data[0][i]] = x
      return acc
    },{})
  })
}


Making a conditionally visible page-up button

I doubt that you need the throttling.  Modern browser make a lot of decisions in response to events; this code is rather insignificant.

If anything, having a continuously ticking timer is counterproductive, especially on mobile devices.  I'd rather have a flurry of activity during the brief periods when scrolling is happening, and no activity at all when idle.

I would recommend toggling the visibility of the button more indirectly, using CSS.  Add or remove an scrolled-down class on the body element depending on whether the document is scrolled down.  Let the cascading rules take care of the rest.

function noteScrollPosition() {
    if ((window.pageYOffset == 0) != (document.body.className.indexOf('scrolled-down') < 0)) {
        if (window.pageYOffset == 0) {
            document.body.className = document.body.className.replace(/ *scrolled-down/, '');
        } else {
            document.body.className += 'scrolled-down';
        }
    }
}
window.addEventListener('load', noteScrollPosition, false);
window.addEventListener('scroll', noteScrollPosition, false);

function scrollUp() {
    scrollTo(0, 0);
}
body {
 background-color: #272822;
 color: #F3F3F3;
}

#scrollbutton {
 background-color: #666664;
 border-radius: 100%;
 position: fixed;
 font-size: 1.5em;
 bottom: 0;
 right: 0;
 visibility: hidden;
}
body.scrolled-down #scrollbutton {
 visibility: visible;
}
#scrollbutton:hover {
 color: #A6E22E;
}
<!DOCTYPE html>

 <link rel="stylesheet" type="text/css" href="test.css"/>

<input type="button" value="&#8679" id="scrollbutton" onclick="scrollUp();"/>

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

 Contrary to popular belief, Lorem Ipsum is not simply random text.
    It has roots in a piece of classical Latin literature.


Buidling classes with user input and calling methods

Python has something called magic methods (sometimes also called dunder methods, but the other name is way cooler).

These methods have special names and enable custom classes to use built-in functionality. If, for example you write a custom numeric class, you would want to be able to do e.g. a + b, with at least one of them being an instance of your class (and the other one either as well or even just a plain number). In order to achieve this, you would just implement an appropriate __add__ method for your class.

Here is a good list going through all available magic methods.

In your class, we can use the __str__ method. It gets used when you call str(obj), print(obj), "{}".format(obj) (unless you also implement the __format__ method):

class User:
    def __init__(self, first_name, last_name, city, age):
        self.first_name = first_name
        self.last_name = last_name
        self.city = city
        self.age = age

    def __str__(self):
        s = ["-----",
             f"First Name : {self.first_name}",
             f"Last Name : {self.last_name}",
             f"City : {self.city}",
             f"Age : {self.age}"]
        return "\n".join(s)

Note that I made some more changes:

The empty parenthesis after the class name are not needed. You only need parenthesis if you want to inherit from some other class.
I also called the first argument of the methods self, which is the customary name for it in Python.
I did not build the string using simple addition, since that is quite slow in Python (strings are immutable objects, so each string addition involves creating a new string of the right length and copying the content of the two strings being added).
And finally, I used f-strings to make the formatting a bit easier.

In your form_complete function (which IMO should be called complete_form, since that describes an action), you could use a list comprehension:

def complete_form(n_users):
    return [User(ask_user("Enter First Name: ").title(),
                 ask_user("Enter Last Name: ").title(),
                 ask_user("Enter City: ").title(),
                 ask_user("Enter Age: ", type=int)
            for _ in range(n_users)]

Note that I moved the alls to str.title here, since it should be the responsibility of the user of your class to pass in correct values (for example, what if your user enters a name for which title() does not make sense? There are also names that start with lowercase letters. Etc...)

I also removed values and placement from the signature, since you override them right away anyways.

And finally, I added a keyword argument to ask_user, which allows you to validate that age is actually an integer:

def ask_user(message='', type=str):
    user_input = ''
    while not user_input:
        try:
            user_input = type(input(message).strip())
        except ValueError:
            continue
    return user_input

By default, this just calls the str function on whatever your user supplied. If you instead specify type=int, it will call int on the input, which raises a ValueError if it cannot parse the input it received as an int.

This has only one weakness right now: If the user wants to enter something that parses as 0, they are stuck in an infinite loop (so no users under the age of 1 allowed).

I also added a call to str.strip, so user names like  (space) and  (tab) are not allowed either.