Picking from a list of individuals based on their fitness values

You have to keep in mind that Streams are not the solution to everything. In this case for example, you need to keep track of multiple values, i.e. the current individual, and a cumulative sum (and you have to return a a value as soon as a certain condition is met). Yes, there are ways to do this with Streams, but I think in this case it is best to implement it with a simple loop like you have.

A couple of side notes:

Use the primitive type double instead of the wrapper class.
Declare variables as late as possible.
Perhaps allow the user to pass a Random instance.
I think your implementation can be simplified by subtracting, which would then mean you only have to check for < 0, e.g.:

double fitnessSum = genePool.stream()
        .mapToDouble(individual -> individual.fitnessValue)
        .sum();

double remainder = Math.random() * fitnessSum;
for (Individual gene : genePool) {
    remainder -= gene.fitnessValue;
    if (remainder <= 0.0) {
        return gene;
    }
}
return genePool.get(genePool.size() - 1);


Generic util method to convert in single map from list of array of Object generally result of JPQL/ hibernate

There is not much "generic" here, the code is as type safe as with raw types. Further, throws Exception usually isn't a good idea. Last but not least, method arguments should be written lower-case.

Here my attempt (off the top of my head, couldn't test it):

public static <K,V> Map<K, V> getMapFromObjectList(
       List<? extends Object[]> objects,
       Class<K> keyClass, Class<V> valueClass,
       int keyIndex, int valueIndex)
    {
        if (object == null) {
          return Collections.EMPTY_MAP;
        }
        Map<K, V> map = new HashMap<K,V>(objects.size());
        for (Object[] array : objects) {
            if (Math.max(keyIndex, valueIndex) > (array.length - 1)) {
                    throw new IndexOutOfBoundsException(keyIndex + " OR " + valueIndex + " out of bound for array");
            }
            if (array[keyIdex] != null) {
                map.put(keyClass.cast(array[keyIdex]),
                        valueClass.cast(array[valueIndex]);
            }
        }
        return map;
    }

Of course this code will fail if the types are not the expected ones, but at least it will fail early, and it is already inherently "dangerous" code. On the other hand, it's reasonable to expect that Hibernate doesn't mess it up out of the blue, once the types are correct.

Note that HashMap supports null keys (although IMHO this design decision is questionable).


Inserting products scraped from the web into a database

For performance questions you should really take a profiler to it and
make sure that the Python code isn't accidentally the culprit first.

The numbers you quote for this sound way too high, though of course we
can't see the actual data.

Now for the code.

Even though this is running Python 2 it should still be made compatible
with Python 3, in particular:

Use print as a function, that is, print(...), for consistency.
Avoid zip for big lists, instead use izip from itertools.
Use consistent syntax, also read
PEP8 regarding naming,
because Python names should be consistenly lower case with
underscores - since your names are at least consistent that is less of
an issue.
A program should have a if __name__ == "__main__": ... block,
assuming this not part of a bigger script where such a block is
already in place.`

Apart from that more generally:

Use more descriptive names. zz, dp, fp, mep, dat tell the
reader absolutely nothing about the meaning.
Random float literals should be named, or create a separate
Use functions to reuse functionality and to decompose the whole
program into clear steps.
Related things should be place together, e.g. the cursor call can be
moved to the end where the database functionality is located instead
of at the start of the loop.  Btw. are you sure that you acquire a new
transaction automatically?  It would help to know which particular
library is being used.

Also:

The replace call can be done in one step, "$,".replace("", "").
The XML extraction looks pretty verbose.  Unfortunately I'm not so
sure about the types, though I'd imagine this could be written a bit
more clearly with at least a helper function for two of the steps,
quantity and prime:

def empty_or_text(thing):
    return '' if thing is None else thing.text

It also makes sense to cache things instead of recomputing it all over
again, in this case that applies to the findAll calls for
"offersummary".
dat is simply zz[0:4].
Since strings are immutable the assignment of the empty string can be
done in one line, e.g. a = b = "".

And finally as has been said, it might make sense to group inserts into
larger batches unless you require the transactional behaviour for some
reason, or you can't simply rerun a batch.

Also take a look at
this Stackoverflow post
to deal with the insert statement a bit better.

That's it.  I'm afraid without a bit more information about the data
structures it's harder to infer how it should be structured instead.

At this I point I have the following for the modified code:

url = getSignedUrl(params)
resp = requests.get(url)
responseSoup = BeautifulSoup(resp.text)

def empty_or_text(thing):
    return '' if thing is None else thing.text

# EXTRACT FROM XML
offerSummaries = responseSoup.findAll("offersummary")

quantity = [empty_or_text(product.amount)
            for product in offerSummaries]

prime = [empty_or_text(product.iseligibleforprime)
         for product in responseSoup("offer")]

price = [product.lowestnewprice is None else product.lowestnewprice.formattedprice.text
         for product in offerSummaries]

from itertools import izip

# UPDATE DB
for zz in izip(asins.split(","), price, quantity, prime):
    if zz[1] == "Too low to display":
        print("Scraping...")
        zz = scrapeTooLow(zz[0])

    priceFormat = mep = dp = fp = ""
    if zz[1] != "":
        priceFormat = float(zz[1].replace("$,", ""))
        mep = round(priceFormat * 1.35, 2)
        dp = round(priceFormat * 1.38, 2)
        fp = round(priceFormat * 1.17, 2)

    dat = zz[0:4] + [mep, dp, fp]
    print(dat)
    try:
        conn.cursor().execute("INSERT INTO data VALUES (%s, %s, %s, %s, %s, %s, %s)", dat)
        conn.commit()
    except:
        conn.rollback()

print(count, i)


Lock Using “Interlocked” vs lock Statement (“Monitor”) (Followup)

void Unlock()
{
    Interlocked.CompareExchange(ref _locked, Unlocked, Locked);
}

So, if you try to unlock when the lock is not locked, nothing happens? That sounds like a recipe for well-hidden bugs. Instead, unlocking when not locked should throw an exception.

_millisecondsTimeout = millisecondsTimeout < -1 ? -1 : millisecondsTimeout;

Why are you making sure that negative values are changed to -1, when later on you just check whether the timeout is negative?

Anyway, the approach taken by .Net methods like SpinUntil() is that negative values other than -1 throw, so I think you should do that too to be consistent.

if (_millisecondsTimeout < 0) _spinMutex.Lock();
else if (!_spinMutex.Lock(_millisecondsTimeout)) throw new TimeoutException();
else _locked = true;

I don't like having the three branches on the same level here, because logically, they're not. I think this way makes more sense:

if (_millisecondsTimeout < 0)
{
    _spinMutex.Lock();
}
else
{
    if (!_spinMutex.Lock(_millisecondsTimeout)) throw new TimeoutException();
    else _locked = true;
}

Also, what's the purpose of the first if at all. Removing it will work the same:

if (!_spinMutex.Lock(_millisecondsTimeout)) throw new TimeoutException();
else _locked = true;

catch
{
    Dispose();
    _shouldDispose = false;
    throw;
}

Calling Dispose() here makes sense only if the lock gets locked (so TimeoutException wasn't thrown) but then an exception was thrown. But most of the time, such exceptions (e.g. ThreadAbortException) are catastrophic and the whole process is going to go down, so you don't need to care about them much.

_shouldDispose = false;

I don't understand this. If the constructor throws an exception, the caller never gets their hands on the created instance, so they won't be able to call Dispose(). This means that _shouldDispose = false here doesn't make much sense.

On the other hand, calling Dispose() more than once should work (“If an object's Dispose method is called more than once, the object must ignore all calls after the first one.”), but won't, so adding _shouldDispose = false directly into Dispose() would make sense.

I think that _locked should be set always when the lock is locked, not just under some circumstances. That would make understanding your code easier and it would also simplify code in both in the constructor and in Dispose().


Given a sequence of words, print all anagrams together

FiHopZz, your concept seems fine.   A few comments:

in general, don't typedef pointers. It is confusing.
your functions are not const-correct. In other words they cast const values
to non-const values.  The compiler will warn you of this if you enable
warnings.
I prefer pointers to be declared like this: char *p, not char* p.
Consider char* a, b if in doubt (b is not a pointer but looks as if it
should be).
all local functions should be declared static
print_anagrams_together should take a const word array and a size_t size
(destroy should also take size_t not int)
don't cast the return from malloc and note that malloc can fail.
sizeof(char) is 1 by definition.
use strdup to copy a word, not malloc.  strdup can also fail.
you took the length of the string twice, once in the malloc call and once
in the qsort call.
you also used strcpy on a string of which you already knew the
length. memcpy is better (but remember to copy length+1).
print_anagrams_together is arguably better broken into several
sub-functions: copy_words, sort_words, print_words.  Well done for making
destroy as function.  This  would be renamed destroy_words for symmetry.
arguably, copy_words and sort_words above could be combined.  This is how
your loop is written, with a word copied and then sorted in the same loop.
This is clearly slightly more efficient, but in some way it does not appeal
to me.  For a start what do you call it? - copy_and_sort_words is rather
ugly. But also a copy_words that just duplicates the array is easily tested;
one that duplicates it and modifies it is not.  These are perhaps not
considerations that belong to a simple program such as this, but they are
worth beaaring in mind for more complicated tasks.
comments should be useful. Yours are mainly noise.  If nothing needs
saying, say nothing.
the word array in main should be const
the size in main should be const size_t, not int
main should have a parameter list

Don't take my comments on breaking your print_anagrams_together into separate
functions too seriously. It is not a big function and it is easily understood.
Breaking it apart would probably make the program worse.  However, for bigger
or more complicated applications, having several loops in the same function
in my opinion often indicates a lack of proper subdivision.  Just my opinion
though and others may differ.

Note also that although I say that malloc/strdup can fail, they are of course
unlikely to fail in a small program like this.  You might say that it is
pointless testing for NULL pointers when you know they will probably be okay.
The only thing you can sensibly do is to print an error and exit anyway
(perror("malloc"); exit(EXIT_FAILURE);).  But it is a good discipline always
to check the return values of functions that can fail.  Just do it.


Checking all elements against each other for elements strictly worse

Disclaimer: this is not a review but an extended comment.

You surely can optimize. The problem you are trying to solve is known as finding a non-dominated set, and allows a best case of \$O(n \log n)\$ solution; worst case is of course \$O(n^2)\$. You may want to start here.


Long-to-string and string-to-long while checking characters within a xlate table

Pretty good overall, but a few things:

Don't hard-code the 37. Instead, use the translation table's size.
ll is a bad variable name. It's not descriptive at all, and it looks like 11.
Your loop in longToPlayerName can be simplified:

final int base = playerNameXlateTable.length;
while (name != 0L) {
    final long ch = name % base;
    nameCharacters[11 - i++] = playerNameXlateTable[ch];
    name /= base;
}

Be careful with inlined ++i or i++. They can be easy to overlook, and the human brain (mine anyway) doesn't parse arithmetic expressions that cause mutations very well.
I think you've overused parenthesis a bit. For example, I would just do:

if (c >= 'A' && c <= 'Z') {

playerNameToInt64 should be playerNameToLong
s is a bad parameter name. Call it something like name

Other than for loop controls, single letter variables should typically be avoided.
It should also probably be final, but it's immutable, so it doesn't really matter in this case.

Use Character.toLowerCase to eliminate one of the branches in playerNameToInt64.
It might be better to group your shifts like 1 + (c - 97) instead of how they're grouped. It doesn't matter in the current code, but if (1 + c) - 97 can in theory overflow, but 1 + (c - 97) cannot
Rather than 97/65/48, use character literals:

1 + (c - 'a')

The truncation loop is a bit troubling. For a-zA-Z0-9, there never will be any trailing 0 valued base-37 digit. This means that you're worried an invalid character will be provided. But... what if one is in the middle of the string?
If you made a reverse translation table, you could decouple your code from ASCII

no point in doing this though, as it's probably always going to be ASCII (or a superset of ASCII)

Fold the double comparison in the toLong loop into a Math.min() call and use that
Assuming this class is dedicated to player name translation and only player name translation (as it should be), playerNameXlateTable could be shortened to translationTable

In the context of a single-responsibility class, it's obvious what the table is translating
Though partly I'm just saying this because xlate makes me cry, but playerNameTranslationTable does too in all of its 26 character glory.

Will you ever have any other name encodings? If so, it might be worth-while to consider making an interface and having these methods be non-static.

It would make your code a bit more verbose, but it would allow for a bit more decoupling

Make 12 a constant

It would be nice to calculate it since maxLetters = floor(log(2^LONG_BITS) / log(37)), but there's no non-hideous way to calculate this
If it's a constant and you later expand the translation table, you'll only have to change 12 in one place instead of multiple. It's always good to reduce the chance of introducing future bugs.

Since the code is short, I gave it a go at revising it:

public class Review {

    private static char[] translationTable = buildTranslationTable();
    private static int maxLetters = 12;

    public static void main(String[] args)
    {
        System.out.println(playerNameToLong("Corbin92"));
        System.out.println(longToPlayerName(324533943486L));
    }

    public static String longToPlayerName(long name) {
        int i = 0;
        char[] nameCharacters = new char[maxLetters];
        final long base = translationTable.length;
        while (name != 0L) {
            final long ch = name % base;
            nameCharacters[maxLetters - ++i] = translationTable[(int) ch];
            name /= base;
        }
        return new String(nameCharacters, maxLetters - i, i);
    }

    public static long playerNameToLong(final String name) {
        final long base = translationTable.length;
        final int len = Math.min(name.length(), maxLetters);
        long l = 0L;
        for (int i = 0; i < len; ++i) {
            final char c = Character.toLowerCase(name.charAt(i));
            l *= base;
            if (c >= 'a' && c <= 'z') {
                l += 1 + (c - 'a');
            } else if (c >= '0' && c <= '9') {
                l += 27 + (c - '0');
            }
        }
        return l;
    }

    private static char[] buildTranslationTable()
    {
        char[] table = new char[37];
        for (char c = 'a'; c <= 'z'; ++c) {
            table[1 + c - 'a'] = c;
        }
        for (int i = 0; i < 10; ++i) {
            table[i + 27] = (char) (i + '0');
        }
        return table;
    }
}


A comment in

: get-elapsed-time  ( ud -- ud )

seems wrong. The code leaves the elapsed time on top of the otherwise unchanged stack, so the action is really (-- ud).

The way get-elapsed-time leaves a double results in very unnerving drop in hhmmss. and 24-hours-elapsed?. I strongly recommend to make it leave a single integer instead.

I also recommend to reduce stack manipulations with

: get-elapsed-time
    utime
    2over
    d- drop ;

  Is it bad style for words like move-clock-seconds-back to return flags

Yes. It makes it very hard to reuse them in other contexts. Consider (untested)

    begin key dup [char] q <> while
        case
            ....
        endcase
    repeat


Javascript FizzBuzz and Behavior-Driven Development Using Mocha and Chai

Handling invalid input
Instead of returning an array when inputs are invalid, throw exceptions and use throw to detect it in the tests.
Avoid else when previous blocks have return statements
The else can be eliminated since the block evaluated when value <= 0 has a return statement (or would throw an exception). Additionally, the switch statement can be simplified to a few if statements (for an example see this answer to a related question).
Don't forget to set scopes
While the code is in a module, it is best to set the scope of variables and functions - e.g. numbers and i in the loop within numbers should be prefixed by the keywords const and let, respectively, to avoid accidental re-assignment/confusion.
In that same vein, the first few lines of the test are setting variables:

var chai = require('chai');
    expect = chai.expect,
    fizzbuzz = require('../lib/fizzbuzz');

Perhaps you meant to add a comma instead of semi-colon after require('chai')? It would be simpler just to have each variable on its own line:
const chai = require('chai');
const expect = chai.expect;
const fizzbuzz = require('../lib/fizzbuzz');

Actually instead of importing chai just to use expect from it on a separate line, use object-destructuring:
const { expect } = require('chai');
const fizzbuzz = require('../lib/fizzbuzz');


The code is generally pretty clean, however, the major sticking point is that everything here is just shoved into main. Just breaking this up with a few functions that do one thing would be a good start:

std::vector<std::string> read_file(const std::string& path)
{
    std::ifstream file(path);

    if (!file.is_open())
    {
        std::cerr << "Unable to open file" << "\n";
        std::exit(-1);
    }

    std::vector<string> words;
    std::string token;

    while (std::getline(file, token, ','))
    {
        words.push_back(token);
    }

    return words;
}

I've also put back all the std:: namespace qualifier. Using namespace std is something that is ok for very short programs like this, but is something you shouldn't get into the habit of doing.

How about a function to sum the values in a word?

int sum_word(const std::string& word)
{
    constexpr static int ascii_to_integer = 64;
    int total = 0;
    for(auto c : word) {
        total += (c - ascii_to_integer);
    }
    return total;
}

In fact, if you want to be fancy, this can be even shorter:

int sum_word(const std::string& word)
{
    constexpr static int ascii_to_integer = 64;
    return std::accumulate(word.begin(), word.end(), 0, [](int i) { return i - ascii_to_integer; });
}

Finally, we can have a function to encompass the outer loop (processing each word in the vector):

int total_word_position(const std::vector<std::string>& v)
{
    int counter = 1;
    int total = 0;

    for(const std::string& s : v) {
        // Exclude " "
        std::string word(s.begin() + 1, s.end() - 1);
        total += (sum_word(word) * counter);
        ++counter;
    }
    return total;
}

Your main method would then become:

int main()
{
    std::vector<std::string> all_words = read_file("E:\\names.txt");
    std::sort(all_words.begin(), all_words.end());
    int grand_total = total_word_position(all_words);
}

This has a number of benefits:

Variable scope is minimized to a single smaller function, instead of a large main function.
It's generally easier to read and debug, as there is less to keep in your head.
It separates parts of the program that do very different things (reading a file vs sorting vs summing numbers).


Interestingly, I've found an answer that does not include the cost when calculating its heuristic. When trying it out, my algorithm doesn't work anymore.

Let's make sure that you understand the algorithm.  It is:

We have a queue where the entries in the queue are a possible path and an estimate of the cost of that path.
The queue keeps itself sorted by cost, lowest cost path first, highest cost path last

Basically the idea is to assume that the lowest-cost path is the one to explore first; only if that does not work out do we try the next-lowest.

So now let's talk about the cost.  The estimated cost is the sum of:

The known cost of the path so far
The estimated cost of getting to the goal from the end of the path

If you've already gone 100 squares (known) and you think you have 50 more to go (estimated), the total estimated cost is 150.

You MUST include the known cost in with the estimated cost of the remainder; if you did not then you would, say, take a path known to be at least 100 long and put it in the queue as though it had a cost of 50!

So you must compute the estimated cost in two parts: the known cost of the path, and the estimated cost of the remainder.  It is the second part that is usually called the "heuristic", because it's a guess. The known cost can be computed exactly.

  I think that I need to optimise my heuristic function. For now, I calculate candidly : the distance between the current tile and the goal if no tile were blocked, plus the current cost.

The key feature of the heuristic is that it must never overestimate. A heuristic which has this property is called admissible.

It sounds like your heuristic is admissible. If you can only move orthogonally, not diagonally, then the Manhattan distance is admissible.

Your heuristic is called the Manhattan distance because it's the distance between two points in New York City, if you're constrained to moving on the grid rather than going diagonally.

If you can move diagonally then the Manhattan distance can overestimate, and is not admissible. If diagonal movement is allowed then use the Euclidean distance: the straight-line distance between two points.

One way you can test your algorithm is to use zero as your heuristic; just say that the estimated cost is the known cost plus nothing.  That is an admissible heuristic because it always under-estimates.  A-star with a zero heuristic is also called Dijkstra's Algorithm.

You say you want to optimize your heuristic. The best way to optimize the heuristic is to make it as accurate as possible without ever overestimating, while at the same time making it fast to compute. The Manhattan distance is a great heuristic because it is very fast to compute, is often exact, and never overestimates.

The more accurate the heuristic is, the fewer paths the algorithm has to consider before finding the best one. So accuracy is important.

I would stick to using the Manhattan distance and profile your code to figure out where the performance problem is.  Likely the problem is not with your heuristic at all, but with maintaining the heap invariant in the priority queue, or with figuring out which nodes are already visited.

If you're interested in this subject you might want to read my series of articles from 2007 on implementing a-star in C#.

https://blogs.msdn.microsoft.com/ericlippert/tag/astar/


Python program that draws the Mandelbrot set fractal

The key thing to remember when working with numerical code is that the CPython interpreter is pretty slow (it trades speed for flexibility) and so you must avoid running in the interpreter whenever possible. Instead of iterating in slow Python bytecode using for x in ..., operate on whole arrays by calling the appropriate NumPy function or method, which dispatches to fast compiled code operating on fixed-size numbers.

So to speed up Fractal we must turn it inside out — instead of operating on one pixel at a time, we must operate on the whole array at once.

Let's start out by measuring the performance of the implementation in the post:

>>> from timeit import timeit
>>> timeit(Fractal, number=1)
1.4722420040052384

The constants \$c\$ are computed one at a time:

a = amin
for x in range(width):
    b = bmin
    for y in range(height):
        c = np.complex(a,b)
        # ...
        b = b + bStep
    a = a + aStep

Instead, compute a whole array of constants \$c\$ using numpy.linspace and numpy.meshgrid:

a, b = np.meshgrid(np.linspace(amin, amax, width),
                   np.linspace(bmin, bmax, height), sparse=True)
c = a + 1j * b

The IterateFractal function operates on the \$z\$ value for a single pixel at a time. Instead, we should operate on a whole array of \$z\$ values:

z = np.zeros_like(c)
iterations = np.zeros_like(c, dtype=int)
for i in range(1, iterateMax + 1):
    z = z ** 2 + c
    iterations[abs(z) <= 2] = i

Note that in this implementation, points that never escape from the set have iterations equal to iterateMax (rather than NaN as in the post). This requires a corresponding change to FractalColor:

def FractalColor(iterate, maxIt, hues):
    if iterate >= maxIt:
        return (0,0,0)
    else:
        # ...

Instead of computing histogram one pixel at a time, use numpy.bincount:

histogram = np.bincount(iterations.flatten())

This results in the revised code:

def Fractal2(width=200, height=200, amin=-1.5, amax=1.5, bmin=-1.5,
             bmax=1.5, iterateMax=100):
    a, b = np.meshgrid(np.linspace(amin, amax, width),
                       np.linspace(bmin, bmax, height), sparse=True)
    c = a + 1j * b
    z = np.zeros_like(c)
    iterations = np.zeros_like(c, dtype=int)
    for i in range(1, iterateMax + 1):
        z = z ** 2 + c
        iterations[abs(z) <= 2] = i
    histogram = np.bincount(iterations.flatten())
    return width, height, iterateMax, iterations.T, histogram

Note the iterations.T at the end there: the .T property is a shorthand for numpy.transpose. This is needed because NumPy prefers row-major ordering where a 2-dimensional array is indexed by row, column, but DrawFractal is using column-major ordering where an image is indexed by x, y.  See the Numpy documentation on "Multidimensional Array Indexing Order Issues". If you updated DrawFractal to use row-major indexing then you would avoid the need for this transpose.

This is about 40 times as fast as the original code:

>>> timeit(Fractal2, number=1)
0.03542686498258263

There are a couple of problems with the whole-array approach. First, it wastes work: once a \$z\$ value has escaped the set, we don't need to keep iterating it. Second, by continuing to iterate the \$z\$ value, we might find that it overflows the range of floating-point numbers, resulting in unwanted overflow warnings.

So what we can do is to keep track of the indexes of the pixels that have not yet escaped the set, and only operate on the corresponding values of \$z\$:

def Fractal3(width=200, height=200, amin=-1.5, amax=1.5, bmin=-1.5, bmax=1.5,
            iterateMax=100):
    a, b = np.meshgrid(np.linspace(amin, amax, width),
                       np.linspace(bmin, bmax, height), sparse=True)
    c = (a + 1j * b).flatten()
    z = np.zeros_like(c)
    ix = np.arange(len(c)) # Indexes of pixels that have not escaped.
    iterations = np.empty_like(ix)
    for i in range(iterateMax):
        zix = z[ix] = z[ix] ** 2 + c[ix]
        escaped = abs(zix) > 2
        iterations[ix[escaped]] = i
        ix = ix[~escaped]
    iterations[ix] = iterateMax
    histogram = np.bincount(iterations)
    iterations = iterations.reshape((height, width))
    return width, height, iterateMax, iterations.T, histogram

Note that when operating on a set of indexes like this, it's most convenient to work with a flattened array, so that we only need one array of indexes. (If we used a two-dimensional array, we'd need to maintain two arrays of indexes ix and iy.) So we call numpy.flatten at the start to flatten the array to a single dimension, and numpy.reshape at the end to restore it to two dimensions.

This is about 70 times as fast as the original code:

>>> timeit(Fractal3, number=1)
0.02115203905850649

Now that you've seen how to make Fractal operate on the whole array (rather than one pixel at a time), you should be able to do the same for DrawFractal. (Hint: instead of calling Image.putpixel for each pixel, call Image.putdata once.)


Using jQuery and AJAX process a form with PHP

On client-side, some small points ...

Avoid more $(selector) phrases than absolutely necessary. Inside the submit handler, you can use $(this), which will be faster.
Pass serializedSubmission formally to the subroutines rather than rely on an outer var.
The outer var responseObjcan't be reliably used except in an asynchronous context, so if you want to cache anything, cache the promise returned by $.ajax(), not the data.
Needs less obvious comments and more on things that matter, eg against lines like if (temp.search('=&') > 0 || temp.slice(-1) == '='), which I had to study to work out the validation strategy. Maybe a few words would have helped me.


Alright, this is the first time I've used Typeclasses so someone feel free to slap me with a tuna if I mess something up.
First of all, I don't understand why the use of "FlexibleInstances" is necessary, and it scares me because these kinds of warnings are usually put in place for a reason. With that out of the way, I'll go through the code.

The first thing you should realize is that in Haskell, typeclasses are basically the same thing as Java's interfaces. They define a contract of behaviour which instances of the class must obey. In this case, the typeclass I'm calling Prop promises the user three methods:

valid to check if the proposition is logically valid (true for all possible inputs)
contradiction to check if the proposition is false for all possible inputs.
lequiv to check if two propositions of the same number of arguments have an identical truth value given the same inputs.

These correspond to three questions which we could ask of any proposition which is a function of any number of propositional atoms. In case you're unfamiliar with this terminology, an 'atom' is one of the inputs to a proposition which is a function taking some number of atoms and itself evaluating to either True or False.
Typeclass Declaration
The name TF for the type class bears no meaning for me, so I changed it to Prop short for "Proposition".
-- A typeclass which different types may implement.
class Prop p where
  valid         :: p -> Bool            -- Same thing as a Tautism
  contradiction :: p -> Bool            -- False under all conditions/opposite of Tautism
  lequiv        :: p -> p -> Bool

What we're doing here is creating a new typeclass called Prop. We need the syntax Prop p because we need to define the behaviour of an instance p of the Prop class. If we don't introduce a symbol for it, then how will the compiler know what we're talking about the in the typeclass definition? For example, the line valid :: p -> Bool says that for every instance p of typeclass Prop, there must be a method called valid which maps p to a boolean value. Likewise, there must be a similar method for contradiction.
Now the line lequiv :: p -> p -> Bool may cause some confusion because p appears twice. It's important to understand that p, being an instance of a typeclass, is a type. There are no "objects" as in object-oriented languages. Remember: p is a type which satisfies the typeclass contract given by Prop. The Java equivalent would be a class p implementing an interface Prop. What we're saying here is that for type which implements/is a part of this typeclass Prop, there is a method called lequiv of comparing them. And its type is p -> p -> Bool meaning that it takes in two expressions of type p and returns a boolean indicating whether or not they're equivalent.

Boolean Instance Definition
All we've told the compiler so far are our promises: there will be methods for checking whether an instance of Prop is valid or a contradiction, and a method for comparing two propositions of the same type for equality.
To start, we implement these procedures for the most basic type of proposition: one that is just True or False.
-- This is a proposition which is simply a literal Bool!
instance Prop Bool where
  valid         = id
  contradiction = not
  lequiv b1 b2  = b1 == b2

Here, Prop Bool says that in the expression Prop p above, the type whose behaviour/implementation we're defining is the Bool type. How do we check if a Bool is valid? Well, it takes no arguments, so a proposition that is just True or False is valid if it's true, and otherwise a contradiction.

valid = id says that the function valid mapping our proposition type of Bool to whether or not it's a valid formula is the function id. (This function just returns whatever it's given).
contradiction = not says that the function contradiction mapping the proposition type Bool to whether or not it's a contradiction is the function not. Just as well, because not takes just one Bool as an argument, and returns a Bool. This is compatible with the contract we laid out earlier in the typeclass definition of Prop.
lequiv b1 b2 = (b1 == b2) says that the way of comparing two of these propositions (once again, of type Bool here) for logical equivalence is to simply invoke the already existing method ==.

Inductive Instance Definition - First Step
This is the fun part. We're using induction. Here's the full code snippet, and then I'll break down each line.
instance (Prop p) => Prop (Bool -> p) where
  valid f         = (valid (f True)) && (valid (f False))
  lequiv f g      = (lequiv (f True) (g True)) && (lequiv (f False) (g False))
  contradiction f = (contradiction $ f True) && (contradiction $ f False)

Now the first line says this: (Bool -> p) is of type Prop, as long as the constraints in what we call the context are met. Here the context is what comes before the =>, and what it says is that p, the type, is a member of the Prop typeclass. This means that we're saying that any type which maps a Bool to any type of Prop is itself an instance of Prop. Why are we doing this? Well, let's start with the simplest case.
Bool is an instance of typeclass Prop, because we defined this 'base case' explicitly. Okay, so then (Bool -> Bool) is also of typeclass prop, because we said that any type (Bool -> <something in class Prop>) is in class Prop. This gives us the functions which take in one boolean argument and return a boolean. Examples: not, id, (\a -> True), (\a -> False). (In fact, these are all such functions).
How have we defined whether to determine whether one of these functions is valid? Our definition says that
valid f = (valid (f True)) && (valid (f False))

It says that a boolean function f of one boolean is valid if and only if (f True) and (f False) are both valid. Of course, the validity of boolean is just that boolean. So in this case, valid can be thought of as being a bit simpler:
valid f = (f True) && (f False)

Alright, so f is valid if and only if it evaluates to True for both arguments! That's what we want.
Now for contradiction:
contradiction f = (contradiction $ f True) && (contradiction $ f False)

This is the key: contradiction asks the question "Is this proposition false for all possible inputs"? To test this, we split f into two parts: its first argument and the rest. If the first argument is True, then is it possible to satisfy proposition f with the remaining arguments? If not, then it's a contradiction. This is the part contradiction $ f True.
f True is itself a function of 1 Bool argument, so it is in class Prop, and so we're able to apply contradiction to it to see if it's a contradiction. We also need to be sure that it's not possible to satisfy f if the first argument is False either, which is why we && this with contradiction $ f False.
I'll leave the lequiv function as an exercise, and move on to the next inductive step.
Inductive Instance Definition - Inception
Since (Bool -> Bool) is of class Prop, then so too is Bool -> (Bool -> Bool). I could be mistake, but I'm fairly sure that Bool -> Bool -> Bool is actually just short-hand for this. So this means that a boolean function of two boolean variables is itself a proposition. How do we determine its validity? We check if both f True and f False are valid. The former means 'if f True False and f True True both evaluate to True'.
Hopefully you can see now the recursion that's going on (I haven't done a great job explaining it; sorry)-- what we're doing is recursively defining the validity of the type Bool -> Bool -> .... -> Bool so that such a function is valid if and only if it evaluates to True for all possible inputs.


Input any time, output timezones that are currently that time

in_day = [weekday for weekday in weekdays if word in weekday]
    if len(in_day) == 1:

seems odd. You make the entire list, put it in memory, take its length and then throw it away. Consider instead
n_matching = sum(1 for weekday in weekdays if word in weekday)
if n_matching == 1:

This loop:
for word in words:
    in_day = [weekday for weekday in weekdays if word in weekday]
    if len(in_day) == 1: # Make sure that the word found is a weekday name, not just something like "day"
        weekday = in_day[0]
        break

can be simplified if you use set operations; lower everything in words before this:
countries = {t.split("/", 1)[0].lower() for t in pytz.all_timezones}
try:
    country = next(iter(countries & set(words))).title()
except StopIteration:
    country = "World" # If no country name found, use "World"


cargo fmt and cargo clippy
Use cargo fmt to format your code according to the official Rust
Style Guide.
Clippy's suggestions:

collapse else { if .. } into else if ..;

change self.base = self.base - 1 to self.base -= 1;

use write_all instead of write when writing a slice of bytes,
since the latter only makes one writing attempt:

io::Write::write(_vectored) and io::Read::read(_vectored) are
not guaranteed to process the entire buffer. They return how many
bytes were processed, which might be smaller than a given buffer’s
length. If you don’t need to deal with partial-write/read, use
write_all/read_exact instead.  (source)

The interface
Instead of passing in a tuple, it is preferable to pass separate
parameters:
fn encode(decimal_number: char, base: usize) -> String {
    // ...
}

Now, we notice that the interface is fairly curious.  A better
self-explanatory interface might simply be:
fn to_roman(number: u32) -> String {
    // ...
}

which can be coded to encapsulate calls to encode while avoiding
repetitive allocation.
Grouping use declarations
It's common to group use declarations together:
use std::{
    env,
    io::{self, BufWriter, Write},
};

The Bases utility
Bases is not necessary — you can use (0..n).rev() to iterate
from n - 1 to 0.


Optimization on List key comparisons and return value with HashMap

public static List<DataSt> compO(List<DataSt> curR, List<DataSt> prevR) {

    Map<String,DataSt> cur = new HashMap<>();Map<String,DataSt> prev= new HashMap<>();
   curR.parallelStream().forEach(entry -> cur.put(entry.key,new DataSt (entry.time,entry.memory)));
   prevR.parallelStream().forEach(entry -> prev.put(entry.key,new DataSt (entry.time,entry.memory)));

    List<DataSt> comp = new ArrayList<DataSt>();
    for (Entry < String, DataSt > abc: cur.entrySet()) {
        final String key = abc.getKey();
        if (prev.containsKey(key)) {
            saveIt(abc.getValue(), prev.get(key), key, comp);
        } else {
            saveIt(key, comp);
        }
    }

    for (Entry<String, DataSt> abc: prev.entrySet()) {
        final String key = abc.getKey();
        if (!(cur.containsKey(key))) {
            saveIt(key, comp);
        }
    }
    return comp;
}

Also you can try to use parallel stream on map, but it should not be HashMap, and I'm not sure that it will be faster.


Search key in a rotated sorted array without repetition of elements

Generally speaking, well-designed algorithms in C++ work with iterators, not with arrays and size or with full collections. By using iterators, you can make your algorithm work with any standard collection. Since you heavily rely on the indices and make math with them, I guess that you algorithm is only meant to work with random-access iterators, but we can still generalize it with iterators to make it work with arrays, std::array, std::vector and std::deque with trivial changes.

Make it work with any random-access iterator

First, let's change the signature:

template<typename RandomAccessIt>
int search(RandomAccessIt begin, RandomAccessIt end, int key);

We don't have the size N anymore, but we can still compute last_index with the iterators:

int last_index = std::distance(begin, end) - 1;

Now, all you have to do is replace array by begin everywhere and change your main:

int main()
{
    int array[] = { 2, 4, 5, 6, 7, 0, 1 };
    int index = search(std::begin(array), std::end(array), 0);

    std::cout<<"index :"<<index;
}

Return the iterator, not the offset

Searching algorithms in the standard library tend to return the iterator where the value was found - if it was found -, and the end iterator otherwise. Once again, you can implement that with only a few changes:

Change the return type to RandomAccessIt:

template<typename RandomAccessIt>
RandomAccessIt search(RandomAccessIt begin, RandomAccessIt end, int key);

Instead of returning middle_index, return the corresponding iterator:

return std::next(begin, middle_index);

Instead of returning -1 when the value has not been found, return the end iterator:

// The key was not found
return end;

Make it fully iterator-based

By using the functions in <iterator>, you can make your algorithm have a more "iterator-oriented" feel. I almost converted it to work with bidirectional iterators (with the additional cost than std::distance is \$O(n)\$ instead of \$O(1)\$ for bidirectional iterators) but stopped myself since I would have to alter a bit the logic of your algorithm and comparing the original and the new versions would have been trickier. Let's say that the final steps are left as an exercise to the reader :p

template<typename RandomAccessIt>
RandomAccessIt search(RandomAccessIt begin, RandomAccessIt end, int key)
{
    RandomAccessIt last = std::prev(end);

    while ( last >= begin )
    {
        RandomAccessIt middle = std::next(begin, std::distance(begin, last) / 2);

        if( *middle == key )
           // The key was found
           return middle;

        if ( *begin < *middle )
        {
            if( key >= *begin && key < *middle )
                last = std::prev(middle);
            else
                begin = std::next(middle);
        }
        else
        {
            if( key > *middle && key <= *last )
                begin = std::next(middle);
            else
                last = std::prev(middle);
        }
    }
    // The key was not found
    return end;
}

Make it work for any comparable type

Turning this index-based algorithm to an iterator-based algorithm made me realize that there weren't any tricky things making use of the value of key to be more efficient and that the key was only used for comparison. Therefore, you can also make the searched type generic instead of restricting it to int. Actually, it is as simple as merely changing its signature and it works with any LessThanComparable type:

template<typename RandomAccessIt, typename LessThanComparable>
RandomAccessIt search(RandomAccessIt begin, RandomAccessIt end, LessThanComparable key);


Yes, this doesn't look pretty. Consider converting the list to sets or using RegEx.

ArrayList<String> A = new ArrayList<String>();
A.add("Z");
A.add("Z");
A.add("C");
A.add("X");
A.add("Z");

Set<String> set = new HashSet<String>(A);

for(String temp:set)
    System.out.println(temp);

Sublists:

List<String> subList = alist.subList(2, 4);

Use retainAll to get intersections:

listOne.retainAll(listTwo) ;
boolean areEqualNotSamePosition = listeOne.size();


My implementation of a memmem() like function

I'm trying to rewrite it from scratch. How does this look?

Mis-matched function signature
OP code uses
void *MemContainsMem(const void *StrStart, register unsigned long StrLen,
    const char *Substr, register const unsigned char SubstrLen);

The referenced code uses
void *memmem(const void *haystack, size_t haystacklen,
    const void *needle, size_t needlelen);

Recommend to use the same function signature.  Unclear why OP changed from size_t to unsigned long and changed pointer type.
Use of Str... hints at a string, yet this function does not operate on strings.  Maybe Mem...?  Hard to beat the names needle/haystack.
Invalid access in corner case
The first *Substr in memchr(StrStart, *Substr, StrLen); is UB when SubstrLen is 0.
Code should gracefully and correctly  handle SubstrLen == 0 and SubLen == 0 cases.
register
register is a good keyword to use when the rare programmer better understands the compilation situation better than the compiler.  For the other 99.99% of us, drop register and let the compiler do its job.  Do not tie the hands of the compiler.
0 vs. NULL
Minor: Since the return type is a pointer, consider returning NULL rather than 0 as being more idiomatic.  Either works.
Unneeded code
The first if (StrLen < SubstrLen) { return 0;  appears unnecessary as that case is detected in later code.
Redundant test
} while (Str); can be replaced with } while (1);.  Alternatively make loop a while()
//register const unsigned char *Str = memchr(StrStart, *Substr, StrLen);
//do {
//    if (!Str || StrLen < SubstrLen) {
//        return 0;
//    }

const unsigned char *Str;
while ((Str = memchr(StrStart, *Substr, StrLen)) != NULL && (StrLen >= SubstrLen)) {

Invalid pointer subtraction
Not portable to subtract void * in NewStr-Str.  Use unsigned char *NewStr instead.
Array or string
The define treats Substr as an array and not a string.
Good macro practice uses a () arround each parmeter.
// #define MemContainsStr(Str, StrLen, Substr) \
//    MemContainsMem(Str, StrLen, SubStr, sizeof(SubStr))

#define MemContainsStr(Str, StrLen, Substr) \
    MemContainsMem((Str), (StrLen), (SubStr), strlen(SubStr))

Be wary now of double evaluation of SubStr

Are there register variables that shouldn't be, how can I further optimize this code?

I recommend to drop all register usages and simple enable greater compiler optimizations levels.
A fundamental weakness to this code is that it is O(m*n) where m, n are the lengths of the needle and haystack.
Better algorithms are O(m+n) and oblige significant code changes.

ToDo
Bug??
Str+1 is suspicious in NewStr = memchr(Str+1, *Substr, StrLen); as it is not clear that StrLen > 0 always at this point.  e.g. StrLen, SubstrLen both are 0.
Hmmm


Project Euler #10 in Ruby - summation of primes

Instead of checking whether each number from 2 until n is prime, you could generate all the primes that are less or equal to n using an algorithm like the Sieve of Eratosthenes.

A trivial implementation of the sieve in ruby is:

def sieve(n)
  sieve = []
  root = Math.sqrt(n)
  (3..root).step(2) do |i|
    if !sieve[i]
      (i**2..n).step(i) do |j|
        sieve[j] = true
      end
    end
  end
  [2] + (3..n).step(2).select{ |i| !sieve[i] }
end

Thus, your code could be rewritten as:

class NewSumprime
  attr_accessor :number

  def initialize(number)
    self.number = number
  end

  def sieve(n)
    sieve = []
    root = Math.sqrt(n)
    (3..root).step(2) do |i|
      if !sieve[i]
        (i**2..n).step(i) do |j|
          sieve[j] = true
        end
      end
    end
    [2] + (3..n).step(2).select{ |i| !sieve[i] }
  end

  def prime_serie
    sieve(number).inject(&:+)
  end
end

A simple benchmark on my PC gives:

ts = Time.now.to_f ; Sumprime.new(1000000).prime_serie ; Time.now.to_f - ts
=> 11.137484788894653
ts = Time.now.to_f ; NewSumprime.new(1000000).prime_serie ; Time.now.to_f - ts
=> 0.493511438369751


Asking for player name and age using OOP

The methods in this class are not really Player methods. They are a combination of game flow, user input and value verification methods.   I'd organize it more like this.
class Game:
  def __init__(self):
    io.show("If ready, let's begin")
    name = self.get_valid_name()
    age = self.get_valid_age()
    self.player = Player(name, age)
    io.show("Hello {}, prepare for battle".format(self.player.get_name()))

The Game object owns the flow of control.  The I/O is encapsulated in an object which can be a simple stdio wrapper for now, but may eventually include non-blocking input or html output or whatever - don't tie the game logic to the display method.  The Player object contains player state.
The get_valid_x methods can basically be what you have now. If you are using that pattern over and over, you could get fancy and write a parameterized validator:
def get_valid_input(prompt, validation_func):
  while True:
    input = io.prompt(prompt)
    guidance = validation_func(input)
    if not guidance:
      return input
    io.show(guidance)

def validate_name(str):
  if not str.istitle():
    return "Please enter name beginning with capital Letter"
  return None

 ...

 name = get_valid_input("What is your name?", validate_name)


Simple neural-network simulation in C++ (Round 4)

get_I_syn() currently always returns 0
I'm not sure if you are aware of this, but because I_syn_bar is a constant 0, this makes get_I_syn() always return 0.  This means you can just get rid of all calls to get_I_syn(), which is where 100% of your time is being spent.
However, assuming that there is some mixup here and I_syn_bar is supposed to be non-zero, I will explain how you can speed your program up by a factor of 50+.
Caching return values of get_f()
If you look at the get_f() function, everything is a constant except for t, which is passed in as t - spike_times[i] from get_I_syn().  If you look closely at what t and spike_times[i] are, they are all multiples of Delta_t.  In fact, t - spike_times[i] can only take on one of 10000 values, which are the first 10000 multiples of Delta_t.
Knowing this, you can precompute the 10000 possible values of get_f().  Then inside get_I_syn(), you can look up the precomputed values instead of doing the expensive computation.
I modified your program to do this and the program sped up by more than 50x.
Modified program
Here is the modified program.  I copied the header contents directly into the c++ file for my own convenience.  As you can see, I increased the number of iterations from 10000 to 300000 because otherwise the program ran too fast.
#include <deque>
#include <math.h>

const double get_T(const double tau, const double g_l, const double I_0,
                   const double theta, const double V_l)
{
  return -tau * log(1 - g_l / I_0 * (theta - V_l));
}

double set_initial_V(const double tau, const double g_l, const double I_0,
                     const double theta, const double V_l, const double c,
                     const double N)
{
  const double T = get_T(tau, g_l, I_0, theta, V_l);
  const double i = 1;
  return V_l + I_0 / g_l * (1 - exp(-c * (i - 1) / N * T / tau));
}

double get_dV_dt(const double g_l, const double V, const double V_l,
                 const double I_syn, const double I_0, const double C)
{
  return (-g_l * (V - V_l) + I_syn + I_0) / C;
}

double get_f(const double tau_1, const double tau_2, const double t)
{
  return 1 / (tau_1 - tau_2) * (exp(-t / tau_1) - exp(-t / tau_2));
}

double get_I_syn(const double I_syn_bar, const double N, const double *f_cache,
                 const int t_index, const int *spike_times, int n_spikes)
{
    double sum_f = 0;
    for (int i = 0; i < n_spikes; i++)
        sum_f += f_cache[t_index - spike_times[i]];
    return I_syn_bar / N * sum_f;
}

#define ITERATIONS        300000

// Declare in global scope to not overflow the stack.
static double f_cache[ITERATIONS];
static int spike_times[ITERATIONS];

int main()
{
    // Parameters.
    const double tau = 10;
    const double g_l = 0.1;
    const double I_0 = 2.3;
    const double theta = -40;
    const double V_l = -60;
    const double c = 0.5;
    const double N = 128;
    const double I_syn_bar = 2;
    const double tau_1 = 3;
    const double tau_2 = 1;
    const double C = 1;
    const double Delta_t = 0.25;
    int    i = 0;
    double t = 0;

    // Simulation.
    int numSpikes = 0;
    double V = set_initial_V(tau, g_l, I_0, theta, V_l, c, N);

    // Precompute all the possible values returned by get_f().
    for (i = 0, t = 0; i < ITERATIONS; i++, t += Delta_t)
        f_cache[i] = get_f(tau_1, tau_2, t);

    for (i = 0; i < ITERATIONS; i++)
    {
        double I_syn = get_I_syn(I_syn_bar, N, f_cache, i, spike_times,
                numSpikes);
        double dV_dt = get_dV_dt(g_l, V, V_l, I_syn, I_0, C);
        V += Delta_t * dV_dt;
        if (V > theta)
        {
            V = V_l;
            spike_times[numSpikes++] = i + 1;
        }
    }
}


Search for a symmetrical inner portion of a list

The code in the question is not working as intended.

  Symmetry occurs if the value of the ith element at the start of the list is equal to the value of the
  ith element at the end of the list

Meaning for any list l the symmetry occurs when l[i] == l[~i].

>>> symmetrical_sum([1, 2, 1, 3, 4])
([1, 2, 1], 4)
>>> symmetrical_sum([0, 1, 2, 1, 3, 4])
([1, 2, 1], 4)

This says that the midpoint is the same distance from the end of the list as the starting value. And it says 1 and -3 are the same distance.
No where does it say the input will only have one duplicate.

>>> symmetrical_sum([1, 2, 3, 4, 2, 1])
ValueError: 21 is not in list
>>> symmetrical_sum([1, 2, 3, 4, 1, 2])
ValueError: 12 is not in list
>>> symmetrical_sum([1, 2, 3, 1, 4, 2])
ValueError: 12 is not in list

The output returns different amount of values when the size of the input are different multiples of two.

>>> symmetrical_sum([1, 2])
([1], 1)
>>> symmetrical_sum([1, 2, 3, 4])
([2, 3], 2)
>>> symmetrical_sum([1, 2, 3, 4, 5, 6])
([3], 3)
>>> symmetrical_sum([1, 2, 3, 4, 5, 6, 7, 8])
([4, 5], 4)
>>> symmetrical_sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
([5], 5)


Convert total minutes into "Hours:minute:seconds" for marathon data

Use do...end for multiline blocks. You're already doing it for the innermost block, but not the File.open block for some reason
CSV.foreach accepts a hash of options. One of them is :headers which you can set to true or :first_row. This will

skip the header row when iterating (so you can skip skip and the if..else-branching), and
let you refer to a column by its header text instead of an opaque numerical index.

For the time-formatting you can use #divmod to get both quotient and remainder of a division in one go. Add some array destructuring, and you get this:

hours, remainder = total_seconds.divmod(60**2)
minutes, seconds = remainder.divmod(60)

Pretty clean, I think.

Alternatively, here's a hacky(!) idea. You could just treat the seconds as a regular unix timestamp, and do something like

Time.at(total_seconds).strftime("%k:%M:%S")

The assumption here is of course that no one took more than 24 hours to complete the marathon. If they did, the hour would of course roll over. It seems like an ok assumption in this particular case, but it's obviously not something that'd work for any context. It's kinda clever, but it's definitely a hack.


Finding suggested flight destinations from database in Golang

... this code just smells very bad. But, cannot figure out better way
  to do this.

Let's look at a more complete, more fragrant implementation.

For data, you are using PostgreSQL: db.Query(selectFlightsSQL, pq.Array(codes), ...). Therefore, define data using the SQL Data Definition Language (DDL). For example,

CREATE TABLE airlines (
    airlinecode char(3) NOT NULL,
    airlinename varchar(64) NOT NULL,
    PRIMARY KEY (airlinecode),
    UNIQUE (airlinename)
);

CREATE TABLE airports (
    airportcode char(3) NOT NULL,
    airportname varchar(64) NOT NULL,
    timezonename varchar(64) NOT NULL,
    PRIMARY KEY (airportcode),
    UNIQUE (airportname)
);

CREATE TABLE flights (
    airlinecode char(3) NOT NULL,
    flightno integer NOT NULL,
    departtime timestamptz NOT NULL, -- local time
    origincode char(3) NOT NULL,
    arrivetime timestamptz NOT NULL, -- local time
    destinationcode char(3) NOT NULL,
    PRIMARY KEY (airlinecode, flightno, departtime),
    FOREIGN KEY (airlinecode) REFERENCES airlines,
    FOREIGN KEY (origincode) REFERENCES airports,
    FOREIGN KEY (destinationcode) REFERENCES airports
);

Access the data using the SQL Data Manipulation Language (DML). For example,

    -- $1  origincode list
    -- $2  origincode list length
    -- $3  earliest arrivaltime
    -- $4  latest arrivaltime
    SELECT destinationcode, airportd.airportname AS destinationname, arrivetime, airportd.timezonename AS arrivezone,
        origincode, airporto.airportname AS originname, departtime, airporto.timezonename AS departzone,
        destinations.airlinecode, airlines.airlinename, flightno

    FROM (

        SELECT destinationcode, origincode, airlinecode, flightno, departtime, arrivetime,
            count(origincode) OVER (PARTITION BY destinationcode) AS origins
        FROM flights
        WHERE arrivetime >= $3 AND arrivetime <= $4
            AND origincode = ANY($1)
            AND destinationcode != ANY($1)

    ) AS destinations
    LEFT JOIN airlines ON airlines.airlinecode = destinations.airlinecode
    LEFT JOIN airports AS airportd ON airportd.airportcode = destinationcode
    LEFT JOIN airports AS airporto ON airporto.airportcode = origincode

    WHERE origins = $2

    ORDER BY destinationcode, arrivetime, airlinecode, flightno, departtime
    ;

Consider optimizations such as indices.

Data access is implemented in SQL for any programming language that implements an interface to PostgreSQL (and other relational DBMS`s), not just Go.

In Go, the remaining algorithmic, procedural task is simple: convert the SQL rows to a Go hash map indexed by destination code. For example,

package main

import (
    "database/sql"
    "time"

    "github.com/lib/pq"
    _ "github.com/lib/pq"
)

type Flight struct {
    DestinationCode string
    DestinationName string
    ArriveTime      time.Time
    ArriveZone      string
    OriginCode      string
    OriginName      string
    DepartTime      time.Time
    DepartZone      string
    AirlineCode     string
    AirlineName     string
    FlightNo        int
}

func destinations(db *sql.DB, origins []string, earliest, latest time.Time) (map[string][]Flight, error) {
    query := `
        -- $1  origincode list
        -- $2  origincode list length
        -- $3  earliest arrivaltime
        -- $4  latest arrivaltime
       SELECT destinationcode, airportd.airportname AS destinationname, arrivetime, airportd.timezonename AS arrivezone,
            origincode, airporto.airportname AS originname, departtime, airporto.timezonename AS departzone,
            destinations.airlinecode, airlines.airlinename, flightno

        FROM (

            SELECT destinationcode, origincode, airlinecode, flightno, departtime, arrivetime,
                count(origincode) OVER (PARTITION BY destinationcode) AS origins
            FROM flights
            WHERE arrivetime >= $3 AND arrivetime <= $4
                AND origincode = ANY($1)
                AND destinationcode != ANY($1)

        ) AS destinations
        LEFT JOIN airlines ON airlines.airlinecode = destinations.airlinecode
        LEFT JOIN airports AS airportd ON airportd.airportcode = destinationcode
        LEFT JOIN airports AS airporto ON airporto.airportcode = origincode

        WHERE origins = $2

        ORDER BY destinationcode, arrivetime, airlinecode, flightno, departtime
        ;
        `

    dst := make(map[string][]Flight)
    rows, err := db.Query(query, pq.Array(origins), len(origins), earliest, latest)
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    for rows.Next() {
        var flt Flight
        err := rows.Scan(
            &flt.DestinationCode,
            &flt.DestinationName,
            &flt.ArriveTime,
            &flt.ArriveZone,
            &flt.OriginCode,
            &flt.OriginName,
            &flt.DepartTime,
            &flt.DepartZone,
            &flt.AirlineCode,
            &flt.AirlineName,
            &flt.FlightNo,
        )
        if err != nil {
            return nil, err
        }
        dst[flt.DestinationCode] = append(dst[flt.DestinationCode], flt)
    }
    err = rows.Err()
    if err != nil {
        return nil, err
    }
    return dst, nil
}

func main() {}

The XY problem is asking about your attempted solution rather than your actual problem: The XY Problem. Therefore, without a problem, we have no way of knowing whether a solution is correct. There are no use cases or examples.

TODO: Domain knowledge is important. Airline arrival and departure times are local times. Any solution needs to be verified and tested across time zones and for standard and daylight saving times.


Getting enum values of Pseudo-Enum classes

Let's look for scenarios that this code could cover.

Next 143296.ps1 script, using Get-Type function - Get exported types in the current session

Exports all types from all namespaces in the current session to $allTypes, then
Selects those with non-empty (pseudo)enumeration to auxiliary Hashtable $ppp and $subTypes.

Script 143296.ps1:

$allTypes = Get-Type -Namespace * -ErrorAction SilentlyContinue
$allTypes.Count
$ppp=@{}              ### auxiliary Hashtable object, could be useful though
$allTypes |
    ForEach-Object {
        $aux = $_ | Get-EnumValue -AsFlags
        if ( $aux.Count -ne 0 ) { $ppp.add( $_.FullName, $_.BaseType) }
    }
$ppp.Count
$subTypes = $allTypes | Where-Object { $ppp.ContainsKey($_.FullName)}
$subTypes.Count
$subGrups = $subtypes | Group-Object -Property BaseType
$subGrups.Count
### make public the most frequent items:
$subGrups | Sort-Object -Property Count -Descending | Select-Object -First 15

<# ### another approach to make public results:
$allBases = $ppp.Keys | %{ "{0,15} {1}" -f ($ppp[$_] | Select -ExpandProperty name), $_ } | sort
$allBases.Count
$subBases = $ppp.Keys | %{ ($ppp[$_] | Select -ExpandProperty name)} | sort -Unique
$subBases.Count
#>

Output:

PS D:\PShell> D:\PShell\CR\143296.ps1
12413
2490
2490
182

Count Name                      Group
----- ----                      -----
 1710 System.Enum               {System.StringSplitOptions, System.StringComparison, System....
  201 System.Object             {System.String, System.EventArgs, System.BitConverter, Syste...
   58 System.ValueType          {System.DateTime, System.DateTimeOffset, System.Boolean, Sys...
   53 System.Attribute          {System.ComponentModel.BindableAttribute, System.ComponentMo...
   28 System.Windows.Freezable  {System.Windows.Media.Animation.ThicknessKeyFrame, System.Wi...
   24 System.Windows.Framewo... {System.Windows.Shapes.Shape, System.Windows.Controls.Panel,...
   22 System.Windows.Control... {Microsoft.VisualStudio.Text.Editor.OutliningMarginHeaderCon...
   15 System.Windows.Media.A... {System.Windows.TextDecoration, System.Windows.Media.Animati...
   11 System.Windows.Control... {System.Windows.Window, System.Windows.Controls.Primitives.B...
    9 System.Windows.Depende... {System.Windows.Navigation.JournalEntry, System.Windows.Cont...
    8 System.Globalization.C... {System.Globalization.GregorianCalendar, System.Globalizatio...
    8 System.Windows.Control... {System.Windows.Controls.Canvas, System.Windows.Controls.Vir...
    7 System.Windows.Media.P... {System.Windows.Media.ArcSegment, System.Windows.Media.Bezie...
    7 System.Windows.Control... {System.Windows.Controls.Border, System.Windows.Controls.Ink...
    7 System.Windows.Media.G... {System.Windows.Media.CombinedGeometry, System.Windows.Media...

The Get-EnumValue function is explained using Comment-Based Help (CBH):

Set-StrictMode -Version latest
function Get-EnumValue {
    <#
    .SYNOPSIS
        Return names (and values) for an enumeration or enumeration-like object.

    .DESCRIPTION
        With -AsFlags or no switch: return Ordered Dictionary of names and values
                                    for an enumeration (or enumeration-like) object.
        With -NoValues switch: return an array of names for such object.

    .PARAMETER Type
        Pass in an actual type, or a string for the type name.

    .PARAMETER NoValues
        If True, then output would be [string[]] array of names;
           otherwise, [OrderedDictionary] type type.
        If True, then -AsFlags parameter is ignored.

    .PARAMETER AsFlags
        If True *and* specified <type> is attributed 'FlagsAttribute' (some [Enum] types)
           then output values would be hexadecimal-like strings (8+ hexadecimal ciphers);
           otherwise, output values would follow <type> type.
        Applies only if -NoValues parameter evaluates to False.

    .INPUTS
        Valid [type], or a string for the type name.

    .OUTPUTS
        Always returns [OrderedDictionary] or [system.array] object (see switches).
        Never outputs Null; returns an empty (.Count -eq 0) object instead.

    .NOTES
        If -NoValues evaluates to True, then -AsFlags is ignored.

    .EXAMPLE
        # Enum, flag enumeration (FlagsAttribute present on object supplied)
        [System.AttributeTargets]|Get-EnumValue -AsFlags -Verbose
    .EXAMPLE
        # Enum, value enumeration (no FlagsAttribute on object supplied)
        [System.Runtime.InteropServices.VarEnum]|Get-EnumValue -AsFlags -Verbose
    .EXAMPLE
        # Struct (not Enum)
        [System.Double]|Get-EnumValue -Verbose
    .EXAMPLE
        # Class (not Enum): useful or at least interesting output
        [System.Security.Claims.ClaimValueTypes]|Get-EnumValue -AsFlags | ft -a -Wrap

    .REMARKS
        Based on 'Get-EnumValues' function and used in answer to:
        http://codereview.stackexchange.com/questions/143296/getting-enum-values-of-pseudo-enum-classes
        Useful related article: 'Get-Type' - Get exported types in the current session
        https://gallery.technet.microsoft.com/scriptcenter/Get-Type-Get-exported-fee19cf7

    .FUNCTIONALITY
        Tested: Windows 8.1/64bit, Powershell 4
    #>
    [CmdletBinding(PositionalBinding=$false)]
    param (
        [Parameter(Mandatory,ValueFromPipeline,Position=0)]$Type,
        [parameter(Mandatory=$false)][Switch][bool]$NoValues,
        [parameter(Mandatory=$false)][Switch][bool]$AsFlags
          )
    begin {

        Function EnumNoEnum ([type]$noEnumClass) {
            $enumFlagsHash = [ordered]@{}
            $noEnumClass.GetFields() |
                Where-Object {$_.IsStatic -and $_.IsPublic} |
                    Select-Object -ExpandProperty Name |
                        ForEach-Object {
                            $enumFlagsHash.ADD( $_, $noEnumClass::$_)
                        }
            return $enumFlagsHash
        }

        Function EnumFlags ([type]$enumClass, [bool]$enumFlags) {
            $enumFlagsHash = [ordered]@{}
            [System.Enum]::GetNames($enumClass) |
                ForEach-Object {
                    if ($enumFlags) {
                        $enumFlagsHash.ADD( $_, "0x{0:x8}" -F $($enumClass::$_.value__))
                    } else {
                        $enumFlagsHash.ADD( $_, $($enumClass::$_.value__))
                    }
                }
            return $enumFlagsHash
        }
    }

    process {
        Try { $Type = [type]$Type} Catch { $Type = $null }
        if ( $Type) {
            Write-Verbose ("Type:   {0}" -f $Type.ToString())
            ### ToDo: find out $enumFlagsAttribute in a more efficient way
            $enumFlagsAttribute = ''
            if ($Type.CustomAttributes |
                Where-Object {$_.AttributeType.Name -eq 'FlagsAttribute'})
                    { $enumFlagsAttribute = 'FlagsAttribute'}
            Write-Verbose ("IsEnum? {0,-20} {1}" -f
                $Type.IsEnum.ToString(), $enumFlagsAttribute)

            if ($Type.IsEnum) {
                if (-not $NoValues) {
                    if ( $AsFlags -and $enumFlagsAttribute) {
                        #   flags enumeration
                        $TypeOut = . EnumFlags $Type $AsFlags
                    } else {
                        #   value enumeration
                        $TypeOut = . EnumFlags $Type $False
                    }
                } else {
                    $TypeOut = [System.Enum]::GetNames($Type)
                }
            } else {
                # handle pseudo-enums i.e. for cases where this trick's been used
                #                      http://stackoverflow.com/a/15713789/361842
                if (-not $NoValues) {
                    $TypeOut = . EnumNoEnum $Type
                } else {
                    $TypeOut = $Type.GetFields() |
                        Where-Object {$_.IsStatic -and $_.IsPublic} |
                            Select-Object -ExpandProperty Name
                }
            }
            if ( $TypeOut ) { $TypeOut } else { ,@() }
        } else {
            Write-Verbose ("Null or invalid TypeName")
            if ( $NoValues ) { ,@() } else { [ordered]@{} }
        }
    }
}

I think that information about FlagsAttribute on a particular enum type could matter (added to verbosed output), see FlagsAttribute class.

See also the AsFlags parameter in the above function: it causes that values of the FlagsAttribute enum have a hexadecimal look (fake, however sometimes useful).


Interesting question,

as mentioned in the comments, privacy support can be (better) achieved with modules, or with IFFE's.

On the whole your design is not sound, your GUID creation code is so weak in generating unique id's that you will have overlapping GUID's and (hard to reproduce) bugs.

Furthermore, the variables are not exactly private if you can iterate over privates and see all the values stored in there..

Finally, I think you might have a pretty good case for a double assignment here, this

var MyClass = (function() {
    var privates = {};
    var getPrivates = function(obj) {
        return privates[ obj.getGUID() ];
    };

    function MyClass(a, b) {
        var guid = util.guid();
        privates[guid] = {};
        this.getGUID = function() {
            return guid;
        };

        var private = getPrivates(this);
        private.a = a;
        this.b = b;
    };

    return MyClass;
})();

could be

var MyClass = (function() {
    var privates = {};

    function MyClass(a, b) {
        var private = privates[util.guid()] = {};
        private.a = a;
        this.b = b;
    };

    return MyClass;
})();

From a lint/hint perspective you have some semicolon trouble, but nothing too bad.


I think the biggest thing you have to take into account is Separation of Concerns. You should definitely separate page and element definitions from the actual logic of the test. Put your element locators into Page Objects and reference page object attributes in your tests. You can, for instance, have a Search page, a Search Results page, a Booking page on a high level which, in turn, may consist of inner page objects defining blocks/parts of a page.

Another way to abstract things away is Behavior Driven Development which would, at least, make you think of the actions and conditions on the target site pages and describe them in a natural language. There are a few Python packages for BDD, in particular - behave which can be, of course, used with selenium: Using the behave Framework for Selenium BDD Testing: A Tutorial


Query column names and then using them in statements

There is no need for loop/temporary table at all. You could use GROUP_CONCAT equivalent in SQL Server(STUFF + XML) trick:

DECLARE @col NVARCHAR(MAX) = STUFF((SELECT  ',' + QUOTENAME(COLUMN_NAME)
                                    FROM INFORMATION_SCHEMA.COLUMNS
                                    WHERE TABLE_NAME = N'it_master'
                                      AND TABLE_SCHEMA = 'dbo'
                                      AND COLUMN_NAME LIKE 'EQP_%'
                                    ORDER BY COLUMN_NAME
                                    FOR XML PATH(''))
                                   ,1,1,'');

DECLARE @query NVARCHAR(MAX) = N'SELECT <placeholder> FROM it_master;';
SET @query = REPLACE(@query,'<placeholder>', @col);

EXEC [dbo].[sp_executesql] @query;

LiveDemo

Notes:

It is a good practice to filter from INFORMATION_SCHEMA.COLUMNS with table name and schema_name (tables with the same name could exist in many schemas)
Concatenating main query with + is not readable. You could use REPLACE or printf equivalent

SQL Server 2012+:

DECLARE @query NVARCHAR(MAX) = FORMATMESSAGE('SELECT %s FROM it_master;', @col);

LiveDemo2

Another way is to use SQL Server Management Studio:

Object Explorer -> Database_Name -> Tables -> Table_Name -> Columns -> (Click Filter and type EQP optional)

Highlight all needed columns with SHIFT and drag and drop to query pane.


Python program for testing the Collatz Conjecture

"Oh, my god!" will only be reached if the number is neither odd nor even, which will never be the case for any integer.

For a number that will never reach 1 and thus disprove the conjecture, your program would run forever (yet still never reach "Oh, my god!"). Welcome to the halting problem.

But as computer resources are limited, you will run into a stack overflow with the depth of your recursive function calls, whether the number would reach 1 eventually or not. For very large numbers, your program will simply crash, which won't tell you anything about the conjecture.

One way to solve that would be to not use recursion. To do so, return the result y from your function instead of calling the function again. Then call your function in a while loop that stops at 1, feeding the output of a previous call to your function to the next one.

This is still the halting problem, though. Does the computation just take very long or does it never finish (the latter would disprove the conjecture)? You never know.

To solve that too, you'd have to check if your program is trapped in a cycle of numbers (that does not contain 1)


I note that your functions are not doing what they say they're doing. For example, you don't convert a date to a hexadecimal word, you convert to an integer value, a value that also happens to disregard the century and the time component entirely. In getting the date back, you also perform some business rules against the date, by treating certain years as last century, other years as current century.

What I would expect when seeing these functions is that I would certainly get the same date I passed into one function as the output from the other. That is not necessarily going to be the case.

You also have issues with a blanket catch that swallows any exception. If you are going to catch an exception, be specific and catch what you truly can handle, something you might expect. Work towards eliminating those exceptions entirely, so instead of catching them, you are preventing them by validating against their causes beforehand, if possible.

You have an if/else chain where an else if and else have the exact some code in their code blocks. Eliminate the redundancy.

There are issues with shifts and masks not being consistent, in terms of where they are defined and the methodology being used. If you change something in one place, you have to change it in another. More than that, you have to change it in a different way.

To be blunt, it's basically not clear what the code is doing at an initial glance, nor is it necessarily clear why it is doing it.

I don't know what your business case is, but if I was writing a class to convert a date to a "hexadecimal word" and then back again, I would probably expect to write something that takes a date and returns a string, and then takes a string and returns a date. The quick, not completely tested version might be something simple like this

public class DateConverter
{
    public string ConvertToHexString(DateTime date)
    {
        return date.Ticks.ToString("X2");
    }

    public DateTime ConvertFromHexString(string hexInput)
    {
        long ticks = Convert.ToInt64(hexInput, 16);
        return new DateTime(ticks);
    }
}

Which you could validate with

DateTime originalDate = new DateTime(1955, 11, 11, 22, 4, 0);
DateConverter converter = new DateConverter();

string hexValue = converter.ConvertToHexString(originalDate);
DateTime returnedDate = converter.ConvertFromHexString(hexValue);

Debug.Assert(originalDate == returnedDate);


Divide an alphanumeric string into a map of numbers and strings

You can use this regex (\d+)(\D+) which will match two groups, one is to match the number and the second to match the non digit part, beside If you are using Java 9+ Pattern, you can use simply :

String input = "1abcdef2xyz9aaa6xxx";
String regex = "(\\d+)(\\D+)";

Map<Integer, String> map = Pattern.compile(regex)
        .matcher(input)
        .results()
        .collect(Collectors.toMap(
                m -> Integer.parseInt(m.group(1)), m -> m.group(2)
        ));

System.out.println(map);

Result

{1=abcdef, 2=xyz, 9=aaa, 6=xxx}

If you are using Java 8 or lower, you can use :

String alphaNumericStr = "1abcdef2xyz9aaa6xxx";
String regex = "(\\d+)(\\D+)";
Matcher matcher = Pattern.compile(regex).matcher(alphaNumericStr);

Map<Integer, String> map = new HashMap<>();
while (matcher.find()) {
    map.put(Integer.parseInt(matcher.group(1)), matcher.group(2));
}
System.out.println(map);

But you will lose some information if the input contain the same number, in this case I would like to create a class which hold a number and a String and use a list in this case instead.


Efficiency of a linked list partitioning algorithm

Yeah, you're missing brackets, but I think I get what you're trying to do. If I'm wrong, ignore this obviously.

printList can just use a for-loop:

void printList(Node *list)
{

 for(Node *temp = list; temp != NULL; temp = temp->next;)
 {
    cout<<temp->data<<" ";
 }
}

Now for the partition function, you're always returning -1 if startPtr == NULL or endPtr == NULL. But you say that those point to what list points to (at the start of the function). In that case, just check if list is null first. Your function won't do anything if it is anyway:

if(list == NULL)
   return -1;

Now in those for-loops, all you have to do is check if startPtr->next and endPtr->next == NULL.

In your while loop, you have this code:

if(temp2->data < pivot)
{
    if(temp != NULL)
        temp = temp->next;
    else
        temp = startPtr;

    swap(temp->data, temp2->data);
}

But what if, for example, temp == NULL and temp2 == startPtr? Assuming swap() does what it says it does, you're unnecessarily swapping values. It might be expensive, and it might not be. I dunno. The function might also do something weird if you try to swap the same exact values. (As a side note,  you're just passing the value of data. If swap doesn't take values by reference, you won't actually be doing anything to temp->data and temp2->data).

Also, in the declaration of your while loop, you're not checking for if temp2 == NULL.

while(temp2->next != endPtr) //This is will throw a Null Pointer Access Violation exception if temp2 == NULL

This could happen, because you aren't checking if temp2->next == NULL before you say temp2 = temp2->next. If it ever is, your loop will crash the program. I don't know if it's possible for temp2 to reach the end of the list, but if it is, you should just add a conditional.

After your while-loop, you have:

temp = temp->next;
swap(temp->data, endPtr->data);

That could potentially cause the same problems I described before.

Anyway, these are just suggestions. I didn't check thoroughly to see if there were variables you could remove, though.


Pretty nice script, I have mostly minor suggestions.

Always double-quote variables used in command arguments

The parameters in these command should be double-quoted to protect from word splitting and globbing:

rsync -ah --progress $firefox_path /opt/$firefox_file
...
rm $firefox_link
...
tar -jxvf $firefox_file
...
rm $firefox_file

Avoid changing the working directory in scripts

Changing working directories is usually error-prone and confusing,
look for ways to do what you need without changing the working directory.

if cd /opt; then
    tar -jxvf $firefox_file
else
    error_exit "Could not change directory! Aborting."
fi

Another way to write this without changing the directory (and correct quoting):

tar -jxvf "/opt/$firefox_file" -C /opt

It's very good that you check the exit codes of commands,
and this writing style will actually help you do that,
by simplifying near the end:

if ! tar -jxvf "/opt/$firefox_file" -C /opt; then
    error_exit "Could not extract file! Aborting."
fi

chmod 755 /opt/firefox
ln -s /opt/firefox/firefox /usr/bin/firefox-quantum
rm "/opt/$firefox_file"

Declare constants at the top of the file

There are some constant values that are very important for the program's behavior, but they are buried within the code.
It would be better to move these to somewhere near the top of the file,
where they are easy to see and to change.

firefox_bin="/opt/firefox"
firefox_link="/usr/bin/firefox-quantum"

There are some other values that are not in variables,
and it would be good to define variables for them,
for example the ones in this command:

ln -s /opt/firefox/firefox /usr/bin/firefox-quantum

Technique

Here, the else branch is not necessary,
because if the condition is true,
the script will exit anyway.
I suggest to just drop the else,
simply move its body after the conditional (just like you did in other places).

if [ $# -ne 1 ]; then
    error_exit "usage: $0 firefox_quantum_path"
else
    firefox_path="$1"
    firefox_file="${firefox_path##*/}"
fi

To set a variable empty, you can simply write like this:

firefox_path=
firefox_file=

It's usually not a good idea to exit 0 at the end of a script.
This forces exit code 0 (success).
The exit code of a script is the exit code of the last command.
By forcing it to 0,
the failure of the last command will get incorrectly covered up.


In some sense, you haven't really completed the task, which is to find the most prolific commenter.  Your get_email() function requires you to know the names before you call the function, and to know what those names are, you would have to read the mailbox!

Furthermore, your user dictionary is kind of pointless.  It's only ever used as a write-only variable user['email'].  And since only one key is used, there is no advantage to using a dictionary rather than just a regular variable.

To do the job properly, you should make one pass through the file, keeping track of the counts of all of the users as you go.  Using a dictionary to accomplish that is the point of the exercise.


Is this a thread safe way to control access to a reusable resource? Is there a better way?

I'm not sure to be honest, the contained resource would be specific per thread and created upon first read so volatile may be unnecessary as I believe that's for multiple threads reading and writing to the same field.
It looks like you are trying to make a singleton version of the ThreadLocal class, unless you have a good reason I would suggest that you just use that instead.
The ThreadLocal class allows for a factory method (as a Func<T>) to be supplied to create a more complex object.
It depends on the type of resource you want to use in this manner, if it is a service or resource then yes an IOC may be a better option as most containers allow an instance per thread. However if you just need per thread storage of a field, then ThreadLocal is a better option. It also allows the resource to be properly disposed if required too.


Remove duplicates from unsorted linked list

I see a number of things that may help you improve your code.

Make sure you have all required #includes

The code uses getchar but doesn't #include <cstdio>.  Also, carefully consider which #includes are part of the interface (and belong in the .h file) and which are part of the implementation.

Avoid raw pointers

In modern C++, we tend not to use raw pointers very often.  In this case, It would probably be better to have two different classes, one would be a LinkedList class and the other would be a Node class.  That way, instead of starting with a pointer, you can start with an object.

Use nullptr rather than NULL

Modern C++ uses nullptr rather than NULL.  See this answer for why and how it's useful.

Match new with delete

If you allocate memory using new, you must also free it using delete or your program will leak memory.  Since you use new in insert(), you should use delete in the LinkedList destructor which you have not yet written.

Don't abuse using namespace std

Putting using namespace std within your program is generally a bad habit that you'd do well to avoid.

Use more descriptive names

The code's traverse function actually prints the nodes.  For that reason it should probably be named something like print().  Even better would be to have such a function take a std::ostream& argument so it would be possible to print to something other than std::cout.

Omit return 0

If your program completes successfully, the return 0 at the end of main() will be generated automatically, so it's not needed in C++ programs.


Print the elements of an array into a table

If the array bounds are fixed, then there's no need for the count variable, since its value will always be the same. There's also no need to run a separate loop for the summation. You can do this at the same time as you're gathering the input. And since your output shows that you want to show the averages by region, you'll need to have somewhere to store those values, too.

Also, try using more descriptive prompts for the user so they know how many inputs are expected.

So the first part of your function becomes

//could also define these as constants
int regions = 2;
int months = 3;
int count = regions * months;

double[][]rainfall = new double[regions][months];
double[] avgByRegion = new double[regions];
double sum = 0;
double average = 0;

Scanner in = new Scanner (System.in);

//Create For loop to read in data
for(int i=0; i < regions; i++){
  double sumByRegion = 0;
  for(int j=0; j < months; j++){
    System.out.printf("Enter rainfall for Region %d, Month %d:: ", i+1,j+1);
    rainfall[i][j]=in.nextDouble();
    sumByRegion += rainfall[i][j];
  }
  avgByRegion[i] = sumByRegion/months;
  sum += sumByRegion;
}

//calculate average
average = sum/count;

Then you can format your output with another set of loops:

for(int i=0; i < regions; i++){
  System.out.printf("Region %d\t  Jan\t  Feb\t  Mar\t  Avg Rainfall%n", i+1);
  for(int j=0; j < months; j++){
    System.out.printf("\t%2.1f",rainfall[i][j]);
  }
  System.out.printf("\t%2.1f%n", avgByRegion[i]);
}
System.out.println("The overall average rainfall is: " + average);


Not a finite state machine

The state machine in the posted code has infinite states.
This is caused by the recursive calls of get_coin and error.
Consider for example these states:

zero-pence with nothing entered yet
zero-pence, after zero-pence and an invalid input
zero-pence, after zero-pence and an invalid input twice
...

And so on. You can see these are different states,
because the content of the stack is different.

There are theoretically infinite zero-pence, five-pence, etc, states.
Practically there are finite, because after enough invalid inputs,
the stack will eventually overflow.

There should be precisely one zero-pence, five-pence, etc, states.

This is easy to fix by replacing the error function with a loop inside get_coin.

There are too many states

Even after making the states finite,
there will still be more states than required by the exercise.

Why, again, because of the stack.
For example, there are two ways to reach 10 pence:

0 -> 5 -> 5
0 -> 10

At this point, the machine should be in the 10 pence state,
but these two states are not the same,
because the stack stores two different histories.

If you want truly identical ten-pence, fifteen-pence, etc, states,
you have to eliminate history, you have to eliminate stack,
you have to eliminate function calls.

This is easy to fix by implementing state transitions in a loop,
instead of through function calls.

Don't use varargs if you don't need it

The get_coin function takes a variable number of functions as arguments.
But in fact it will only ever use 3,
and in fact it's only ever called with 3.
Therefore, it would be more natural to give those parameters dedicated, descriptive names.

Why convert input to int?

The get_coin function converts input to int,
but doesn't actually perform any numeric operations with it.

Use a more portable shebang

Not all systems have Python 3 installed in /usr/bin/python3.
A more robust, portable shebang would be:

#!/usr/bin/env python3


Please pay attention to formatting.
The code as you posted is hard to read,
and not pleasant to review.

Most notably, the indentation is inconsistent or sometimes random,
and you have very long horizontal lines forcing readers to scroll.
For example this one:

if(emailtext.getText().toString().trim().length() > 0 &&   passtext.getText().toString().trim().length() > 0 && confirmpass.getText().toString().trim().length() > 0 && username.getText().toString().trim().length() > 0 && firstname.getText().toString().trim().length() > 0 && lastname.getText().toString().trim().length() > 0 && isSetDay==true && isSetMonth==true &&    isSetYear==true && isSetPro==true)

Broken up to multiple lines it becomes a lot easier to read:

    if (emailtext.getText().toString().trim().length() > 0
            && passtext.getText().toString().trim().length() > 0
            && confirmpass.getText().toString().trim().length() > 0
            && username.getText().toString().trim().length() > 0
            && firstname.getText().toString().trim().length() > 0
            && lastname.getText().toString().trim().length() > 0
            && isSetDay == true
            && isSetMonth == true
            && isSetYear == true
            && isSetPro == true)

Note that using == true with boolean expressions is really pointless,
as you could use the expressions directly:
if (something) { ... } is exactly the same as
if (something == true) { ... }.
So you could drop all the == true from the above.

When checking if a string is empty, instead of str.length() > 0,
a better way is !str.isEmpty().

To avoid code duplication of .getText().toString().trim().isEmpty() it would be a good idea to add a helper function:

private boolean notEmpty(EditText input) {
    return !input.getText().toString().trim().isEmpty();
}

So that you can rewrite the condition in the if like this:

    if (notEmpty(emailtext)
            && notEmpty(passtext)
            && notEmpty(confirmpass)
            && notEmpty(username)
            && notEmpty(firstname)
            && notEmpty(lastname)
            && isSetDay
            && isSetMonth
            && isSetYear
            && isSetPro)

Even better, as @hkj suggested,
the notEmpty method could take varargs:

private boolean notEmpty(EditText ... args) {
    for (EditText input : args) {
        if (input.getText().toString().trim().isEmpty()) {
            return false;
        }
    }
    return true;
}

which will allow you to shorten the condition even more:

    if (notEmpty(emailtext, passtext, confirmpass, username, firstname, lastname)
            && isSetDay
            && isSetMonth
            && isSetYear
            && isSetPro)

This line is also too long, and also error-prone to type it:

final String[] items = new String[] {"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};

It would be better to fill this array programmatically, for example:

    final String[] items = new String[31];
    for (int i = 0; i < items.length; ++i) {
        items[i] = String.format("%02d", i + 1);
    }


var that = this; Keeping a class in scope of nested functions

Your code is fine (assuming your nested functions are merely proxies to the class methods), I would suggest if the only thing you are doing in the anonymous functions is calling the callbacks then you should just pass them in:
$.post(this.getRequest(), this.getUrl()).success(callback_one).error(callback_two);

There is nothing wrong with the use of that in this code.
Edit (after reading Esailija's answer)
You could also do the proxies mentioned in the Esailija's answer inline like so:
myClass.prototype.myMethod = function () {
    $.post(this.getRequest(), this.getUrl())
        .success($.proxy(this.myOtherMethod, this))
        .error($.proxy(this.myErrorMethod, this));
}

Essentially that is what you were doing with the nested functions; this just tightens the code by moving the proxy creation into a utility method.


You can use standard copy functions instead of manually copying:
from copy import copy

def make_pizza(*toppings, **pizza_info):
    pizza = pizza_info.copy()
    pizza['toppings'] = copy(toppings)
    return pizza

And maybe use a dict-comprehension for merging information, instead of mutating the pizza:
def make_pizza(*toppings, **pizza_info):
    return {
        **pizza_info,
        'toppings': copy(toppings)
    }

For printing, use f-strings for easier formatting:
print(f"You've ordered {pizza['size']} inches size {pizza[
    'crust'].title()} crust pizza with the toppings of:")