Fastest way to cut an array into two arrays at a particular index

I am pretty sure you can use copyOfRange(double[] original, int from, int to) from java.util.Arrays. @Rolfl said, and I quote : It is recommended practice to use Arrays.copyOf instead of System.arraycopy().

If you need to cut up the million+ array for parallel processing, then I would suggest you chunk the data while reading it, this should save you a processing step.

Edit: Internally, Arrays.copyOf() uses System.arraycopy() to do the hard work of duplicating the Array data in the new copy, and it will make your code look like this simple 1-liner:

double[] firstArray = Arrays.copyOf(arrayToCut, 50);
double[] secondArray = Arrays.copyOfRange(arrayToCut, 50, 100);

While using System.arraycopy() may seem like the fastest alternative, whenever you copy an array you have to:

first create the destination for the data to be copied to. This step requires initializing all the destination array points to their initialization values, which is a linear operation, but done in native code, so is fast.
then call the System.arraycopy() for the actual data re-write.

There are many ways that people may want to do this operation, and the various Arrays.copy*() methods are designed to make the relatively mundane, yet still rather complicated and bug-prone process a lot simpler, and less buggy.

Whenever you have a use case where you are copying data from one array to a new array, you should by default use the Arrays.copy*() methods. Only when you have a use case where you are overwriting data in to an existing array (or relocating data inside an array) should you use System.arraycopy(). As for the performance aspect, it appears that the performance of most native mechanisms are similar.

Arrays.copy* methods lead to better, more maintainable, and less buggy code, and, there is essentially no performance penalty because it is just doing the work you were going to do anyway.


Cons of declaring derived class type member in another derived class (both of which share the same base class)

The code itself
I have little to say about the code itself, other than to address your concerns with the vector<Moon> in your Planet class. If you have a C++11 compiler, you might want to add a move constructor and/or provide methods that exploit the move semantics as much as possible. Something like:

class Planet : public CelestialObj
{
    public:
        Planet & add_moons  (vector<Moon>&& vMoon){};
        Planet & add_moon  (Moon&& moon){};//copy push_back
};

The rest of this answer is more about the limitations of your model, and some little niggles I have with a couple of things you mentioned.

At first glance, I don't see any glaring omissions or down-right dangerous code. However, I am a bit of a space-geek at times, and I find the name of your base class a tad risky/counter intuitive.
To me a CelestialObj could be anything ranging from a Planet, a Moon, some Asteroid, Meteorite Planetoids and DwarfPlanets, all the way through to a Star, Nebula, BlackHole, and even things like Galaxy or a Constellation could be considered a celestial object.

Because I don't know what you are going to use these classes for, and not knowing how detailed you want to go, I'm just going to point out a couple of things that you might want to keep in the back of your head.
It's easier to change your approach in the earlier stages, than it will be further down the line.

Of course, a Galaxy is but a CelestialObj that contains a vector<CelestialObj>, mainly Star instances. Each Star can contain a similar vector, representing solar systems and so on.
A Planetoid could be implemented as a specific type of Asteroid, just like a DwarfPlanet is a variation on the Planet class. Great, all this can be made to fit your current hierarchy perfectly, but I would change one thing:

Currently, your Planet class has a vector<Moon> property. Given that there can be objects in orbit around moons, planets can have other objects in its orbit (ie Saturn's rings etc), and that, well, basically: anything can revolve around anything, I'd move the vector up to the CelestialObj class, and make it more generic (vector<CelestialObj> satellites;).

This should allow you to fit more into your current model, but the moment you add bigger objects, or you want to create more complex systems, you'll find it simply can't cope with the added complexities.

When you add nebula's and black holes to the mix, then things become quite tricky, of course, as things like luminescense aren't simple properties.
Forgive my geeky-ness here, but computing the brightness and luminosity of stars is fairly simple, but a galaxy, well: the sum of all celestial bodies isn't quite enough. There's reflection to take into consideration, and black holes trap light in its orbit, aswell as bend the light or even absorb it.

Note:
Now I know you didn't want to discuss minor things, but if ever you extend the CelestialObj class to create a Star, you'll find that a const int size and const int mass is as pointless as a broken pencil. Either way, in terms of celestial bodies: I'd consider it acceptable to use a bigger datatype than a mere int: I'd use a double.
To fix this, you might choose to create a class like this:

class Star : public CelestialObj
{};
class DyingStar : public Star
{
    public://assume double size;
        DyingStar (Star &dead_star_shining, long ttl){};
        Star &pass_time ( long time ){};//heat up planets, swallow closest, alter size_factor
        double getSize( void ) { return size * size_factor; };
    protected:
        double size_factor;
}

Other things that I'm not even going to touch on include neutron stars, wormholes, binary star systems, the list is endless...

Again, this isn't as much a critique of your actual code. This "review" is meant more as a sort of "consider this, how would you fit it into your current model?" type of deal.

In response to comments:
You probably realized that you've chosen a hideously complex thing to try and represent in a relatively simple hierarchical structure. I would, however advise you to not try and use the CelestialObj base class as the only base-class, to extend on to represent well, the entire universe basically.
If you did that, then the only suitable class name would be class BigBang, which, by definition, would have to use multiple inheritance, inheriting both from the Quantum, Matter, DarkMatter, Space and tons of other classes, and would have to implement the Chaos interface. Depending on who you ask, you'd probably have to use the God template, too. Save yourself the trouble, and just use a set of base classes:

CelestialObj is fine, and can be split up into 2 main groups: ReflectingObj (ie: bodies that don't emit light: planets, moons, asteroids) and FusionObj (suns in various stages, including dying suns, neutron stars, pulsars and... The core of a black hole. Everything that is either the remains of a star or that consumes light/celestial bodies).
Cluster: A base class that is either vector-like or doubly linked-list like you can feed CelestialObj instances to, to form SolarSystems, Galaxy's and the actual BlackHole class (because black holes can have light in orbit around it. Light has dual properties (energy and matter, so if you want: create a separate class for this tricky little bugger)
Special cases of Clusters include, for example, Constellations, as they can be a group of stars, combined with galaxies (ie the constellation Orion). The members of a constellation might be too far apart for any of its members to influence the other, so this cluster doesn't have to provide methods for member-interaction, but it should be able to group instaces of CelestialObj alongside Cluster isntances.


Is wrapping the service layer worthwhile?

The drawback is that you are limiting the functionality of your service to perform one query per connection and you have no "batch mode"

But maybe you can implement a query batching method!

For this reason, the user of the database service perhaps should have the power to open and close the connection. Your SQLService could expose Open, Close, and Dispose.


Refactoring Logger interface to open and close logs

NullLogger wouldn't really need any parameters passed to
  openLog() where as SysLogLogger would probably need some
  parameters passed. How would I accomplish this?

Pass these parameters to the constructor, store in a private field and use it in the openLog (or any other) function.

If you use func_get_args() you wouldn't be able to replace the logging system without modifying the client code.

SLF4J is a great example for a logging framework. Check it's Logger interface. It contains some methods but none of them depend on any implementation. Logback, Log4j, JCL and other implementations implements this simple interface and their external configuration determines the details.

A note: maybe timestamp shouldn't be passed to the log function, it should be the internal of the logger implementation.


Updating NamedTuple members based on a function and previous value

I decided that since I'll likely never need to associate the same function with multiple keys, I might as well just associate the keys with a function directly:

def update3(self, **kwargs: Callable[[T], T]) -> GameSettings:
    return self._replace(**{k: f(getattr(self, k)) for k, f in kwargs.items()})

>>> sett = GameSettings(fps=30, is_running=True)

>>> sett.update3(is_running=lambda x: not x)
GameSettings(fps=30, is_running=False)

The code still isn't beautiful, but it makes a lot more sense when calling now.


Design for C++ class methods taking input from different sources

Why not just insert() and iterator like most containers in the STL.

 std::vector<int>   data;
 std::ifstream      file("Plop");

 data.insert(data.end(), std::istream_iterator<int>(file),
                         std::istream_iterator<int>());

 char  buffer[] = "1 2 3 4 5 6 6 7 8 9 10 11 12 13 14 15 16 17 18 19";
 std::stringstream   bufferStream(buffer);

 data.insert(data.end(), std::istream_iterator<int>(bufferStream),
                          std::istream_iterator<int>());

 std::vector<int>    anotherBuffer = LoadBuffer();
 data.insert(data.end(), std::begin(anotherBuffer), std::end(anotherBuffer));


Using OLEDB to connect to a MS Access 2007 file

Unless I misunderstand, you are using unfiltered user input from txtEntryID.
Never trust user input.

What if the user fills txtEntryID with 123 OR 1=1?
The query will delete everything:

DELETE FROM PersonalData WHERE DataID = 123 OR 1=1

What if, then, the user inputs 123; UPDATE Account SET credit = 1000 WHERE userId = me:

DELETE FROM PersonalData WHERE DataID = 123; UPDATE Account SET credit = 1000 WHERE userId = me


UPDATE SQL with prepared stmt using only 1 variable

As it stands right now, you are wide open to sql injection injection attacks because you are copying posted data directly into your sql update statement.  All kinds of nasty things could be injected.

I started to rewrite it but it became a pain since mysqli requires you to bind each parameter individually.  Way too much work.  I'd suggest shifting to PDO which supports binding by arrays as well as named parameters.  Not to mention exceptions.

Something like:

// Some test data
$_POST   = array('name' => 'New Name', 'email' => 'New Email', 'something' => 'nothing', 'userId' => 1);

$allowed = array("name","surname","email","rank");

$params = array();
$items = null;

foreach($_POST as $key => $value) {
    if (in_array($key , $allowed)) {
        if ($items) $items .= ', ';
        $items .= "$key=:$key";
        $params[$key] = $value;
    }
}
if (!$items) die("Nothing to update");
echo $items . "\n"; // name=:name, email=:email

$sql = sprintf('UPDATE %s SET %s WHERE ID = :userId','users',$items);

echo $sql . "\n"; // UPDATE users SET name=:name, email=:email WHERE ID = :userId

$params['userId'] = $_POST['userId'];

$stmt = $pdo->prepare($sql);
$stmt->execute($params); // This is reason enough to shift to PDO


Using POST data to call a function from a specified class

Well, I'm going to post it as an answer, simply because comments aren't the right place for this:

  See edit for justification

You can't justify using $_POST data to call functions or methods in a script. never trust the network, POST data is coming from the network, never trust it. Full stop.
It's a piece of cake to send something like __toString, __invoke, __sleep and other magic-methods. They might exist, so they might pass the method_exist check you do. However, what they do is something different entirely.

You're basically calling a method on an object. That implies a finite list of methods that exist and are callable (there's a function called is_callable to chekc just that, BTW).
A safer way might be to have a property (array) containing a white-list of methods that can be invoked through JS requests:

$psMethods = array(
    'ajaxMethod1',
    'ajaxMethod2'
);

As an added bonus, you could use the method names as keys, and assign those keys a couple of arguments that the method might require.
The downside of this (a static array) is that you'll have to add and remove items from this array as you write your code. Don't worry however, help is at hand thanks to get_class_methods:

private $SP = null;
private $spMethods = array();//empty
//in constructor, or wherever you assign $this->SP
public function __construct(SPClass $sp)
{
    $this->SP = $sp;
    $methods = get_class_methods($sp);
    foreach($methods as $method)
    {
        if (substr($method, 0, 5) === 'ajax_')
        {
            $this->spMethods[] = substr($method,5);
        }
    }
}

Here, any method that has to be callable through an ajax request has to be given an arbitrary prefix (ajax_ in this case). That's how you can determine what methods are valid.
Then, when you receive your data:

if (in_array($_POST['function'], $this->spMethods)) //valid post data
    return $this->SP->{'ajax_'.$_POST['function']}();
else

What to do in the else cases? the choice is yours, really: either provide a default, fallback method in $this->SP:

public function ajax_fallback(array $post = null)
{
    return array('invalid/unknown request action', $post);
}

throw an exception or return a valid json encoded string (json_encode should be passed at least an array, strings needn't be encoded)

Resist the temptation to guess what $_POST['function'] should've been. If its contents is invalid, that can only mean one of the following things:

there's an error in either your PHP or JS code, in which case: fix it
clients trying to exploit your ajax call, in which case, don't try to help them by guessing, throw an exception. Amateur hackers aren't worth the code that'll only end up making it easier for them to actually achieve something
connection problems (unlikely), trying to work your way around those is pointless, so don't

Other considerations:
If you are going to post (part of) a function name to your server, don't call that parameter function. Everybody knows what a function is, so it doesn't take long for some spotty teen to realize which post param is worth trying to exploit!
Sending data over ajax isn't secure anyway, I'd not send a function name, but given the info you've provided, I can't tell which is the better way to go. It might be worth while to hash the function names, and compare the hash value to an array of hashes. The chances someone guesses a hash of (part of) a function name, especially when you add salt are very low indeed:

    $this->SP = $sp;
    $methods = get_class_methods($sp);
    foreach($methods as $method)
    {
        if (substr($method, 0, 5) === 'ajax_')
        {
            $this->spMethods[] = sha1(
                'YOUR_sup3rh3r03-0F=çH01ce'.substr($method,5);
            );
        }
    }

and just hard-code, or send these hashes over through a predefined ajax request.
Those teen-would-be-hackers are easily discouraged when they realize they have to use strings like "ff45204b9bbf938f7c10a734ed4e05434203790d", without knowing what they are :-)


Migrating data using entity framework, linq and recursion

The following code is O(n^2). More precisely, it's Theta(n^2) because it'll always be exactly n.

foreach (var personalWebsite in personalWebsites)
{
    // You can use a HashSet to eliminate the need for the inner loops, which
    // would reduce your computational complexity from Theta(n^2) to Theta(n) - see below
    foreach (var socialNetwork in socialNetworksStr)
    {
        // You could "convert" both of these to some kind of "normal form" (see below) to eliminate the need for the relatively inefficient "Contains" and enable the use of a HashSet
        if (personalWebsite.Url.Contains(socialNetwork))
        {
            socialNetworks.Add(new UserSocialNetworkDTO() { SocialNetworkId = (short)(Array.IndexOf(socialNetworksStr, socialNetwork) + 1), Account = personalWebsite.Url });
            personalWebsitesRemoved.Add(personalWebsite);

            // If you do stick with a loop here, presumably each personal web site only
            // matches one social media site, so you can break out of the loop here to
            // improve your computational complexity for this bit from Theta(n) to O(n)
        }
    }

    // Same comments as above
    foreach (var customSocialNetwork in customSocialNetworksStr)
    {
        if (personalWebsite.Url.Contains(customSocialNetwork))
        {
            customSocialNetworks.Add(personalWebsite);
            personalWebsitesRemoved.Add(personalWebsite);
        }
    }

You can reduce this to O(n) by reducing the URLs to some kind of "normal form" (e.g. http://www.linkedin.com/in/some.person would just be "normalized" to "linkedin.com") and building a Dictionary (hash table) or HashSet. This would reduce the computational complexity from Theta(n^2) to Theta(n).

Also, even if you do stick with the "inner" foreach loops, there's no need to iterate over all of the social network sites every single time; I assume that each personal web site can only match one social media site, so if you find one that it matches it reduces the computational complexity from Theta(n^2) to O(n^2).


Crypt-arithmetic solver (Brute force) in Python

1. Review

In Python it is helpful to write a docstring for each function or class that you define, explaining what it does, what arguments it takes, and what it returns. Docstrings can be accessed from the interactive interpreter using the built-in help function. For getNumberFromStringAndMappingInfo there is a comment which could be used as the basis for a docstring.
solveCryptarithmeticBruteForce does nothing if the puzzle has no solution. This would be easy to miss in a long list of solutions. It would be better to print something like "no solution".
Python programmers generally follow the Python style guide when choosing names. According to this guide, functions and variables should have names using lower_case_with_underscores (and not mixedCase as in the code in the post). You're not obliged to follow this convention but if you do then it will make it easier to collaborate with other Python programmers.
In Python we don't use "Hungarian" naming, in which a name indicates the type of the object named. That's because Python is a "duck-typed" in which the type of an object is not as important as the set of methods it supports. In general we find that code is clearer if names are chosen to be simple and readable rather than cluttered with details.
In Python we don't need to indicate for each argument to a function whether it is used for input or output. That's because functions can easily return a tuple of results, so there is no need for functions to modify their arguments in order to return multiple results.
inPossibleNumsAsStr is built into Python as string.digits.
The puzzles are represented by two lists, one of which gives the addends for each puzzle, and the other gives the results for each puzzle in the same order:

inListNumsAsStringArray = [ ['BASE', 'BALL'],
                            ['SEND', 'MORE'] ]
inResultsArray = [ 'GAMES',
                'MONEY' ]

This kind of data organization is hard to follow and error-prone. It's just about ok here where you only have two puzzles, but imagine having a hundred puzzles — how would you check that puzzle 57 had been entered correctly and not accidentally mixed up with puzzles 56 and 58?

The approach I would take would be to represent the puzzles like this:

PUZZLES = '''
BASE + BALL = GAMES
SEND + MORE = MONEY
'''

The advantages of this representation are that it is clear what it means (no need for complex documentation) and it keeps each puzzle on one line, so that adding and removing puzzles is easy. The data structure can easily be processed by splitting each line into its constituent pieces, like this:

for puzzle in PUZZLES.strip().splitlines():
    addition, result = puzzle.split(' = ')
    addends = addition.split(' + ')
    solveCryptarithmeticBruteForce(addends, result, string.digits)

The initial letters (that must be non-zero) might include duplicates. So it would make sense to remove duplicates in the same way as you do with uniqueStrs.
The function getNumberFromStringAndMappingInfo translates a string by mapping each character through a dictionary. But this can be done using the built-in str.translate method. The way you use this is to call str.maketrans to make the translation table. So instead of:

for tup in itertools.permutations(inPossibleNumsAsStr, len(uniqueStrs)):
    dictCharAndDigit = {}
    for i in range(len(uniqueStrs)):
        dictCharAndDigit[uniqueStrs[i]] = tup[i]

I would write:

for perm in itertools.permutations(inPossibleNumsAsStr, len(uniqueStrs)):
    decipher_table = str.maketrans(uniqueStrs, ''.join(perm))
    def decipher(s):
        return s.translate(decipher_table)

and then instead of:

result = getNumberFromStringAndMappingInfo(inResultStr, dictCharAndDigit)

I would write:

result = int(decipher(inResultStr))

This would avoid the need for the getNumberFromStringAndMappingInfo function.
Instead of building a string strFromStrList that concatentates the addends and result, and then turning this into a set in order to eliminate duplicates, build the set directly. That is, instead of:

strFromStrList = ''
for numStr in inListNumsAsString:
    strFromStrList = strFromStrList + numStr
strFromStrList = strFromStrList + inResultStr

I would write:

letters = set(result)
for addend in addends:
    letters.update(addend)
letters = ''.join(letters)

And this could be made even shorter using itertools.chain:

letters = ''.join(chain(result, *addends))

Similarly, nonZeroLetters could be constructed like this:

initial_letters = ''.join(set(chain(result[0], (a[0] for a in addends))))

The sum of the deciphered addends can be computed using the built-in function sum. Instead of:

testResult = 0
for numStr in inListNumsAsString:
    testResult = testResult + getNumberFromStringAndMappingInfo(numStr, dictCharAndDigit)

I would write:

deciphered_sum = sum(int(decipher(addend)) for addend in addends)

2. Revised code

from itertools import chain, permutations
from string import digits

def solve_cryptarithm(addends, result):
    """Print a solution to the cryptarithm, if any exists.
    Arguments are the list of addends and the result of the sum.
    For example:

    >>> solve_cryptarithm(['SEND', 'MORE'], 'MONEY')
    SEND(9567) + MORE(1085) = MONEY(10652)

    """
    letters = ''.join(set(chain(result, *addends)))
    initial_letters = ''.join(set(chain(result[0], (a[0] for a in addends))))
    for perm in permutations(digits, len(letters)):
        decipher_table = str.maketrans(letters, ''.join(perm))
        def decipher(s):
            return s.translate(decipher_table)
        if '0' in decipher(initial_letters):
            continue # leading zeros not allowed
        deciphered_sum = sum(int(decipher(addend)) for addend in addends)
        if deciphered_sum == int(decipher(result)):
            def fmt(s):
                return f"{s}({decipher(s)})"
            print(" + ".join(map(fmt, addends)), "=", fmt(result))
            break
    else:
        print(" + ".join(addends), "=", result, " : no solution")


Why reinvent the wheel when you can just use password_hash? Your code could be replaced by this:

$hash = password_hash($password);

password_verify($password, $hash);

It uses bcrypt (which uses blowfish internally), and it even manages salts for you.

This should also answer your additional questions: You don't really need any of the functions.

Misc

Blowfish is an encryption algorithm, but when used with crypt, what you do is still hashing, not encryption. So your function should be called password_hash.
=== isn't timing safe. This is more of a theoretical problem, but it's still better to use a timing safe function here.
if (cond) {return true;} else {return false;} can be written as return cond;
Contrary to your comments, generated salts may contain =.
You should document that your salt generation function can only generate salts with a max length of 44, in case it's reused in a different context.
One-time variables can be nice to give something a name, thus resulting in easier to read code (eg in your first two functions). But sometimes they are not really needed. In your second function, I would simply write return crypt($password, $existing_hash) === $existing_hash, it's shorter and I don't think you loose any readability.


Refactor jaccard similarity the "Scala way"

Idiomatic Scala Style

When defining a val, var, or a function use camelCase.

    // :)
    val aCounts = ...

    // :(
    val a_counts = ...

When using an infix operator add a space on both sides of it.

    // :)
    x => x
    i -> j
    foo * boo

    // :(
    x=>x
    i->j
    foo*boo

Code

Here is your code with all of the changes I would make included (explanation follows):

    import Math.min

    def calculateBags(a: List[Int], b: List[Int]): Double = {
        val countsByElem =
            (xs: List[Int]) =>
                xs.groupBy(elem => elem).map { case (e, xss) => e -> xss.length }

        val aCounts = countsByElem(a)
        val bCounts = countsByElem(b)

        def addMin(count: Int, x: (Int, Int)): Int = {
            val (k, t) = x
            val v = bCounts getOrElse(k, 0)
            count + min(v, t)
        }

        val len = (a.length + b.length).toDouble

        (0 /: aCounts)(addMin) / len
    }

The first thing I did was define a function literal, countsByElem. I mostly did this to show you that such expressions are possible and sometimes very useful. The advantage in this case is that instead of duplicating the same logic in multiple places, we just define a function and call it as necessary. If we then need to make a change to the logic we can do so in one place. Another advantage is that a future reader of your code can instantly tell aCounts and bCounts are calculated with the same set of operations (though with different lists). A disadvantage is that defining this function literal adds more lines of code to your function overall. But we will make up for that later :)
Next, I've defined a function which for lack of a better name I've called addMin. The parameters have the same names as you used in your original code: count is the accumulator and x is the ith  element of aCounts. The notable features of this function are:

In the first line we unpack the tuple value x with some syntactic sugar
The next line (starting val v = ...) attempts to retrieve a value from the bCounts map based on the key k. If there is no value associated with k in bCounts the integer value 0 is returned instead.

Lastly we utilize a foldLeft which in the code is designated by the /:. It is a bit hard to concisely explain the set of fold methods that Scala offers. But a nice tutorial on them can be found here. Brief explanation: we pass each element in aCounts along with an accumulator to addMin. If we were to 'unroll' some arbitrary fold-left it might look something like this:

// Scala-esque psuedocode to explain a fold ...
val foldResult = {
    val res0 = func(0,    xs(0))
    val res1 = func(res0, xs(1))
    val res2 = func(res1, xs(2))
    // ...
    func(penultimateResult, xs.last)
}

Anyway, hope this helps!


Convert scalar arguments to arrays, and check that lengths are equal

np.atleast_1d handles the conversion in one step.  It's doc reads:

  Scalar inputs are converted to 1-dimensional arrays, whilst
  higher-dimensional inputs are preserved.

In [217]: np.atleast_1d(1)
Out[217]: array([1])
In [218]: np.atleast_1d([1,2,3])
Out[218]: array([1, 2, 3])

So your code simplifies to:

lat = np.atleast_1d(lat)
lon = np.atleast_1d(lon)
if lat.shape != lon.shape:
    <raise error>

Look at the code for atleast_1d; it's instructive.  Bascially it does:

lat = np.array(lat)
if len(lat.shape)==0:
   lat = lat.reshape(1)

Check for yourself what np.array(1) produces.

I could simplify it further with just one call to atleast_1d, since it takes multiple inputs:

lat, lon = np.atleast_1d(lat, lon)


Readability

Naming
So, the first thing I would note is the poor naming. The way things are named right now makes it difficult to understand the code. So, to start, replace ws1 and ws2 with more meaningful names. The range variables are a little better, but could still use some improvement. I would also note that variables should be camelCased. These things simply make it easier to read the code.

ws1 >> sourceSheet
ws2 >> destSheet
rngtocopy >> rngToCopy >> sourceRange
rngFinal >> destRange
LastRow >> lastRow

The next thing to note is the abundance of single letter variable names. These are problematic. The only time you should use single letter variable names is for a loop counter. That's it. No exceptions. It is extremely difficult to map these letters to meanings while we're trying to understand logic. Will you remember what z is 6 months from now? I doubt it.

j >> lastSourceERow
z >> lastDestERow
k >> firstDestRow
x >> startRow
r >> destCell

Sidenote: Replacing r was a real PITA.
Lastly, Sub and Function names should have Verb-Noun type names. stuck() tells the dev using this code absolutely nothing. Perhaps CopyTheSmithReportRange() would be a good name.
WhiteSpace
Again, this is a readability thing. (I do promise to get around to a better way to do this, but first we do need to be able to read the code.)
You are indenting your code, which is good. I've seen worse, but it could be better. Indentation should visually tell me at what level we're currently working at. For example, consider this snippet.

Do While x < z
    With ws2
        If j > 0 Then
              ws2.Range(("A" & k), ws2.Range("A" & k).Offset(j, 0)).EntireRow.Insert
                    Set r = Cells(r.Row + j, 1)

                    For i = 2 To rngtocopy.Rows.Count
                        With ws2.Range("K" & k)
                            .Offset(0, 0).Value = rngtocopy(i, 1)
                            .Offset(0, 1).Value = rngtocopy(i, 2)
                        End With
                    k = k + 1
                    Next i
        End If
        k = k + 4
    End With
x = x + 1
Loop

Everything starts fine with the Do loop and the With statement, but then you add an extra level of indentation after inserting the row. The rest of that block is logically on the same level, so it should be at the same indentation level. Also take note that your loop incrememtation happens at the same indentation level as the For and Next statements. It shouldn't. It should be one level deeper.
The other thing to note about whitespace is the good use of vertical whitespace. It can make all the difference to readability. Use an extra line (one, never two) to differentiate between logically different things that occur sequentially at the same level of indentation.
This is the code after making these readability changes.
Option Explicit

Sub CopyTheSmithReportRange()

    Dim sourceSheet As Worksheet
    Dim destSheet As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim lastDestERow As Long
    Dim lastSourceERow As Long
    Dim firstDestRow As Long
    Dim startRow As Long
    Dim sourceRange As Range
    Dim destRange As Range
    Dim destCell As Range

    firstDestRow = 3
    startRow = 1

    Set sourceSheet = Sheets("Calc")
    Set destSheet = Sheets("Dealer Orders")

    lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "E").End(xlUp).Row
    lastSourceERow = sourceSheet.Cells(sourceSheet.Rows.Count, "E").End(xlUp).Row
    lastDestERow = destSheet.Cells(destSheet.Rows.Count, "E").End(xlUp).Row

    Set sourceRange = sourceSheet.Range("E2", sourceSheet.Cells(lastRow, "F"))
    Set destRange = destSheet.Range("K2", destSheet.Cells(lastRow, "K"))

    Set destCell = Range("A" & firstDestRow)
    Do While startRow < lastDestERow

        With destSheet
            If lastSourceERow > 0 Then

                destSheet.Range(("A" & firstDestRow), destSheet.Range("A" & firstDestRow).Offset(lastSourceERow, 0)).EntireRow.Insert
                Set destCell = Cells(r.Row + lastSourceERow, 1)

                For i = 2 To sourceRange.Rows.Count

                    With destSheet.Range("K" & firstDestRow)
                        .Offset(0, 0).Value = sourceRange(i, 1)
                        .Offset(0, 1).Value = sourceRange(i, 2)
                    End With

                    firstDestRow = firstDestRow + 1
                Next i

            End If

            firstDestRow = firstDestRow + 4
        End With

        startRow = startRow + 1
    Loop
End Sub

Refactoring
The first thing I notice is that there are a lot of similar variables declared and that the code is deeply nested. These are indications that the code is doing too much and is in violation of the Single Responsibility Principle. It will be our goal now to simplify the code.
There's a quick hit right at the beginning. There is no difference between lastSourceERow and lastRow. We can get rid of lastRow entirely. While we're at it, let's go ahead and extract a function for lastRow. You'll find yourself needing it a lot if you continue to write vba code.
Public Function LastRow(ws As Worksheet, column As Variant) As Long
    LastRow = ws.Cells(ws.Rows.Count, column).End(xlUp).Row
End Function

Note that this function will take input of either a column name ("E") or integer index, so we could pass it the integer index if we so chose.
This simplifies variable initialization a bit, and we have one less declaration.
lastSourceERow = LastRow(sourceSheet, "E")
lastDestERow = LastRow(destSheet, "E")

Set sourceRange = sourceSheet.Range("E2", sourceSheet.Cells(lastSourceERow, "F"))
Set destRange = destSheet.Range("K2", destSheet.Cells(lastSourceERow, "K"))

Setting the ranges leaves a little to be desired though, so we'll use a bit of a hack to clean up those lines. Let's just concatenate the last row to a string indicating the ranges we want to work with.
Set sourceRange = sourceSheet.Range("E2:F" & lastSourceERow)
Set destRange = destSheet.Range("K2:K" & lastSourceERow)

Lets use a similar trick to replace this obtuse line.

destSheet.Range(("A" & firstDestRow), destSheet.Range("A" & firstDestRow).Offset(lastSourceERow, 0)).EntireRow.Insert

With this
destSheet.Range("A" & firstDestRow & ":A" & lastSourceERow).EntireRow.Insert

I'm honestly not a fan of concatenating cell addresses like this, but I think it does a world of good to the readability and maintainability of this code. While we're at it, I think this is useful enough to extract into it's own subroutine.
Public Sub InsertRows(ws As Worksheet, firstRow As Long, lastRow As Long)
    ws.Range("A" & firstRow & ":A" & lastRow).EntireRow.Insert
End Sub

Let's also remove the With destSheet. It's not serving much of a purpose other than to further nest the code. Let's also remove destRange as it's not being used at all. That brings us to here, which is getting somewhere.
Sub CopyTheSmithReportRange()

    Dim sourceSheet As Worksheet
    Dim destSheet As Worksheet
    Dim i As Long
    Dim lastDestERow As Long
    Dim lastSourceERow As Long
    Dim firstDestRow As Long
    Dim startRow As Long
    Dim sourceRange As Range
    Dim destCell As Range

    Set sourceSheet = Sheets("Calc")
    Set destSheet = Sheets("Dealer Orders")

    lastSourceERow = LastRow(sourceSheet, "E")
    lastDestERow = LastRow(destSheet, "E")

    Set sourceRange = sourceSheet.Range("E2:F" & lastSourceERow)

    firstDestRow = 3
    startRow = 1

    Set destCell = Range("A" & firstDestRow)
    Do While startRow < lastDestERow

        If lastSourceERow > 0 Then

            InsertRows destSheet, firstDestRow, lastSourceERow

            Set destCell = destSheet.Cells(destCell.Row + lastSourceERow, 1)

            For i = 2 To sourceRange.Rows.Count

                With destSheet.Range("K" & firstDestRow)
                    .Offset(0, 0).Value = sourceRange(i, 1)
                    .Offset(0, 1).Value = sourceRange(i, 2)
                End With

                firstDestRow = firstDestRow + 1
            Next i

        End If

        firstDestRow = firstDestRow + 4
        startRow = startRow + 1
    Loop
End Sub

But not quite there yet....

Now, instead of this Do While loop, let's iterate through a range of cells with a ForEach loop instead. But first, remove this line, it is also dead code.

       Set destCell = destSheet.Cells(destCell.Row + lastSourceERow, 1)

Actually, completely remove this variable. It's not actually used anywhere. Okay, now let's replace that do loop with a foreach.
Sub CopyTheSmithReportRange()

    Dim sourceSheet As Worksheet
    Dim destSheet As Worksheet
    Dim lastDestERow As Long
    Dim lastSourceERow As Long
    Dim firstDestRow As Long
    Dim startRow As Long
    Dim sourceRange As Range

    Set sourceSheet = Sheets("Calc")
    Set destSheet = Sheets("Dealer Orders")

    lastSourceERow = LastRow(sourceSheet, "E")
    lastDestERow = LastRow(destSheet, "E")

    Set sourceRange = sourceSheet.Range("E2:F" & lastSourceERow)

    firstDestRow = 3
    startRow = 1

    If lastSourceERow > 0 Then

        InsertRows destSheet, firstDestRow, lastSourceERow

        Dim destRange As Range
        Set destRange = Range("K3:K" & lastSourceERow)

        Dim cell As Range, i As Long
        i = 2

        For Each cell In destRange

            cell.Value = sourceRange(i, 1)
            cell.Offset(0, 1).Value = sourceRange(i, 2)

            i = i + 1
        Next cell

    End If
End Sub

A lot just happened there, so let me explain.

Move the If lastSourceERow check and the row insertion out of the loop.
Reintroduce the destRange variable with a new purpose.
Write the values to the iterator cell range, instead of offsetting based on some counter variables.

Now there's just a little more clean up to do.

Let's check the source sheet for data prior to doing anything else.
Remove dead variables startRow & lastDestERow and all related dead code.
Change firstDestRow from a variable to a constant, it's value no longer changes.

And we now have a subroutine that fits on a single screen without scrolling. We could probably extract another method, but this is good enough for me. The code below does exactly the same thing your original did.
Sub CopyTheSmithReportRange()

    Dim sourceSheet As Worksheet
    Dim destSheet As Worksheet
    Dim lastSourceERow As Long
    Dim sourceRange As Range

    Const firstDestRow As Long = 3

    Set sourceSheet = Sheets("Calc")
    Set destSheet = Sheets("Dealer Orders")

    lastSourceERow = LastRow(sourceSheet, "E")

    If lastSourceERow > 0 Then

        Set sourceRange = sourceSheet.Range("E2:F" & lastSourceERow)

        InsertRows destSheet, firstDestRow, lastSourceERow

        Dim destRange As Range
        Set destRange = Range("K3:K" & lastSourceERow)

        Dim cell As Range, i As Long
        i = 2
        For Each cell In destRange

            cell.Value = sourceRange(i, 1)
            cell.Offset(0, 1).Value = sourceRange(i, 2)

            i = i + 1
        Next cell

    End If
End Sub


Improving efficiency of Prim's Algorithm

Single responsibility principle

The primMinimumWeightSpanningTree() is clearly doing to much.
It is

finding the minimum node
updating values in the freeMap
displaying the result

You should extract the finding of the minimum node to a separate method. Also replacing the else with an else if will save one indention.

private Node getMinimumNode(Map<Node, Integer> freeMap){
    Node minNode = null;

    for (Map.Entry<Node, Integer> entry : freeMap.entrySet()) {
        if (minNode == null) {
            minNode = entry.getKey();
        } else if (entry.getValue() < freeMap.get(minNode)){
            minNode = entry.getKey();
        }
    }

    return minNode;
}

To be able to display the result outside of this method, we need to return a Set<Node>.
So let us refactor

public Set<Node> getPrimMinimumWeightSpanningTree(Map<Node, Integer> freeMap) {

    Set<Node> mstSet = new LinkedHashSet<>();
    while (freeMap.size() > 0) {

        Node minNode = getMinimumNode(freeMap);

        freeMap.remove(minNode);
        mstSet.add(minNode);

        /* update values of adjacent nodes in freeMap*/
        for (Map.Entry<Node, Integer> entry : minNode.neighbourerList().entrySet()) {
            if (freeMap.containsKey(entry.getKey())) {
                int value = freeMap.get(entry.getKey());
                if (value > entry.getValue()) {
                    freeMap.replace(entry.getKey(), entry.getValue());
                }
            }
        }
    }

    return mstSet;
}

and add a method for displaying

Public void displayResult(Set<Node> mstSet){

    for (Node node : mstSet) {
        System.out.print(node.getLabel() + " ");
    }

}

You can also think about overriding toString() so you can decide outside of the class, if you want to print to System.out or e.g write to a file.

Style

Comments are useful, but only if they tell why something is done. So telling what is done, where it is clearly visible like

freeMap.remove(minNode); /* remove minimum node from freeMap*/
mstSet.add(minNode); /* add minimum node to MST set(mstSet)*

these comments are just useless and should be removed.


Will this code make some attacks (XSS, CSRF...) harder to do?

I haven't had the need to worry about this kind of thing before, so I can't claim that this will answer your question, but maybe it will help. It looks simple enough, but rand() may not be the best tool here. I know that, at least with Java, the random function is easily beaten because it starts with a number from a list and then iterates over that list each time you call it, and the list is always the same. So maybe this is something to look at in PHP too. Also, I was here anyways and I couldn't help but notice a few things.

A couple of minor notes first. One line of code should only do one thing. This helps with legibility, which is a real problem the deeper you nest functions. And what is "cleaner" by the way? This is a really odd name. Would expect "id" or something else, but anyways.

$id = uniqid( rand(), TRUE );
$cleaner = md5( $id );

You should check if the variable is set, not empty. Unless you already know it is set, which you don't because it hasn't been done in this document. Also, the extra parenthesis are unnecessary in this ternary operation.

$_SESSION[ 'cleaner' ] = isset( $_SESSION[ 'cleaner' ] ) ? $cleaner : $_SESSION[ 'cleaner' ];

A more efficient way, instead of creating something you will now never use, is to only create it if you have to. So...

if( isset( $_SESSION[ 'cleaner' ] ) ) {
    $cleaner = $_SESSION[ 'cleaner' ];
} else {
    $id = uniqid( rand(), TRUE );
    $cleaner = md5( $id );
}

$_SESSION[ 'cleaner' ] = $cleaner;

You may notice that I'm now modifying the session variable no matter what. Its not really necessary, but it keeps the session fresh which is sometimes nice.

With this next line I'm assuming that you are checking if the form has been submitted ("login_button" seems kind of obvious). This is a really debatable subject. Many people still do this, I think because they think it ensures that the user is actually using their form instead of their own, but its not that hard to look at the source and create POST parameters with the same keys, so I don't know how much truth there is in that.  I personally find it better to just check the request method, or, if I'm feeling particularly lazy, to see if the POST array is empty. As I said, its really debatable, so you can take it or leave it.

if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
//Or the hack
if( $_POST ) {

Next you check for the POST version of "cleaner", this should be another isset() check rather than an empty() check by the way, then you compare the session version to the POST version. So then, this would only be possible, theoretically, if we didn't use the cleaner we created earlier because the session version was set. Think I'm with you so far... But why not then use that earlier version we didn't use instead of creating a new one? To illustrate, a full rewrite might look something like this:

$id = uniqid( rand(), TRUE );
$cleaner = md5( $id );

if( isset( $_SESSION[ 'cleaner' ] ) ) {
    $temp = $_SESSION[ 'cleaner' ];
    if( ! $_SERVER[ 'REQUEST_METHOD' ] || $temp != $_POST[ 'cleaner' ] ) {
        $cleaner = $temp;
    }
}

$_SESSION[ 'cleaner' ] = $cleaner;

Hopefully this helps somewhat, sorry I couldn't really answer your question.


Just a word of advice, creating a mutable struct which is always a bad idea.  It must be a class otherwise you're just leaving yourself open to problems and confusion.

You could improve it much more if you don't restrict your methods to use lists of topics.  You could then easily apply recursion here and write it in a more functional style with simpler logic.

static TreeNode GenerateTopicsTree(IEnumerable<Topic> topics)
{
    // shouldn't the root value be null?
    var root = new TreeNode("Topics", null);
    return GenerateTopicSubTree(root, topics);
}

static TreeNode GenerateTopicSubTree(TreeNode root, IEnumerable<Topic> topics)
{
    // partition the topics to child and non-child topics
    var rootId = GetId(root);
    var childTopics = topics.ToLookup(topic => topic.ParentId == rootId);

    // create and add subtrees to the current node
    var childNodes = childTopics[true].Select(GenerateNode);
    foreach (var childNode in childNodes)
    {
        root.ChildNodes.Add(GenerateTopicSubTree(childNode, childTopics[false]));
    }
    return root;
}

static int? GetId(TreeNode node)
{
    int id;
    if (Int32.TryParse(node.Value, out id))
        return id;
    return null;
}

static TreeNode GenerateNode(Topic topic)
{
    return new TreeNode(topic.Title, Convert.ToString(topic.Id));
}

Consider using data binding to create your tree instead.  I don't know how it works with ASP.NET so I can't really give you tips on how to do it.  But doing so should make this step unnecessary as the framework will generate the tree for you.  You'll probably have to create a class to represent the topics organized in a hierarchy but you could use the above code to create that hierarchy.

After thinking about this again, I think it would be better to just group them all at once in the beginning instead of partitioning at every step.  Here's an alternate implementation:

static TreeNode GenerateTopicsTreeAlt(IEnumerable<Topic> topics)
{
    var root = new TreeNode("Topics", null);

    // group all children together now so we don't need to regroup them again later
    var childTopics = topics.ToLookup(topic => topic.ParentId);
    return GenerateTopicSubTreeAlt(root, childTopics);
}

static TreeNode GenerateTopicSubTreeAlt(TreeNode root, ILookup<int?, Topic> childTopics)
{
    // create and add subtrees to the current node
    var rootId = GetId(root);
    var childNodes = childTopics[rootId].Select(GenerateNode);
    foreach (var childNode in childNodes)
    {
        root.ChildNodes.Add(GenerateTopicSubTreeAlt(childNode, childTopics));
    }
    return root;
}


Your code already looks pretty clean. Good work! There are only a few things I would recommend changing.

Don't define timings in CSS that should be defined in JavaScript. In this specific case using a transition made it possible to simplify the code significantly, however in a more involved example it would become problematic. What happens if one progress bar takes 2 seconds to complete, and another takes 5?
Instead of using getElementsByClassName('cls')[0], you can use querySelector('.cls') for more readable code. Though this can be slower, it really isn't an issue unless it is being run thousands of times per second.
There is a built in <progress> element that you may want to use.
It is a good idea to wrap template elements in a <template> element.

Here's a simple demo that defines the timing in the JavaScript.

function Loader(element, time) {
  return new Promise(resolve => {
    let intervalId;
    function tick() {
      element.value = parseInt(element.value, 10) + 1
      if (element.value == element.max) {
        clearInterval(intervalId)
        resolve()
      }
    }
    setInterval(tick, time / element.max)
  })
}

let promise = Promise.resolve()
let container = document.querySelector('.container')
let template = document.querySelector('template')

function addProgress() {
  let progress = document.importNode(template.content, true)
  container.appendChild(progress)
  // progress is a document fragment, not the template element
  return container.querySelector('progress:last-child')
}

document.querySelector('button').addEventListener('click', () => {
  let bar = addProgress()
  promise = promise.then(() => Loader(bar, 3000))
})
progress {
  display: block;
  width: 100%;
}
<template>
  <progress max="100" value="0"></progress>
</template>

<button>Click me!</button>


I have two notes to make here,

Extract a public interface from this code, like ILogger<T>, and store (or inject) an ILogger<T> instead of a Logger<T>

This will allow you to create different implementations of your logger type and pass it to the consumers of your logger without them knowing/caring whether it's logging to a console, to a file, or to a typewriter.

An important use case for that is creating an ILogger implementation for unit tests. You probably don't want your unit tests to have any side effects, so you could create a TestLogger class that implements ILogger and records all the logs to a list instead of a to a file or console.

Handle write access in a safer way

Currently you are not disposing of your StreamWriter instance. Even though you are calling Close you really should be either using a using statement or having a single instance of the stream writer that is accessed through an actor or other thread safe method and is disposed when your logger is disposed.

(Less important, but I would also store the execution path in a static readonly

private static readonly string executionPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location + "/resources/logging/" + file;

private static void LogToFile(string file, string content)
{
    using (var fileWriter = new StreamWriter(executionPath, true))
    {
        fileWriter.WriteLine(content);
        fileWriter.Close();
    }
}


Since you only modify a copy of the second string, the first one should be a const reference:

bool IsAnagram(const std::string &str1, std::string str2)

Also, i and j should be of type size_t to match what they're compared with.

However, I think I'd do it like this:

bool IsAnagram2(std::string str1, std::string str2)
{
    std::sort(str1.begin(), str1.end());
    std::sort(str2.begin(), str2.end());
    return str1==str2;
}

Test program:

#include <iostream>
#include <string>
#include <algorithm>

#define SHOW(x) std::cout << # x " = " << x << '\n'

int main()
{
    std::cout << std::boolalpha;
    SHOW(IsAnagram("\0\0\0\0\0", "\0lehl"));
    SHOW(IsAnagram("hello", ""));
    SHOW(IsAnagram("\0\0\0\0\0", "olehl"));
    SHOW(IsAnagram("hello", "ole"));
    SHOW(IsAnagram("hello", "plehl"));
    SHOW(IsAnagram("hello", "hello"));
    SHOW(IsAnagram("hello", "12345"));
    SHOW(IsAnagram("hello", "Hello"));
    SHOW(IsAnagram("hello", "oellh"));
    SHOW(IsAnagram("hello", "olelh"));
    SHOW(IsAnagram("hello", "elelh"));
}

Program output

IsAnagram("\0\0\0\0\0", "\0lehl") = true
IsAnagram("hello", "") = false
IsAnagram("\0\0\0\0\0", "olehl") = false
IsAnagram("hello", "ole") = false
IsAnagram("hello", "plehl") = false
IsAnagram("hello", "hello") = true
IsAnagram("hello", "12345") = false
IsAnagram("hello", "Hello") = false
IsAnagram("hello", "oellh") = true
IsAnagram("hello", "olelh") = true
IsAnagram("hello", "elelh") = false


I'm deallocating objects created but I'm unsure whether my code is leaking memory or not

You don't need to use new everywhere. Inside your main function, the StudentDatabase could very well reside on the stack so you don't need to delete it yourself.

One of the issues with how StudentDatabase is written now is ownership semantics. Once a student pointer is added to the database, the database asumes ownership upon it and deletes it in the destructor. What if the same student pointer were to be added to multiple databases, or used after the database is deleted?

Smart pointers help prevent such errors.


Find elements occurring even number of times in an integer array

Wiki Answer - discussion of scalability.

After some investigation I thought it would be interesting to publish some of the performance results I have seen.... there are some interesting observations.

I have taken two algorithms, both on this page, the 200_Success one, and the rolfl one. I have run both algorithms through two types of tests, and for each type, I ran it through data of different sizes. I measured the actual performance.

The two types of test are 'data complexity' related. The first test I call 'sparse', and there are very few duplicates of data. The second set of data is 'freq' which has many, many duplicates. The two data sets are constructed as (1 << 18 is 256K elements and runs in an 'about-right' time on my computer):

    int[] sparse = new int[1<<18];
    Random rand = new Random(1); // repeatable 'random' numbers
    for (int i = 0; i < sparse.length; i++) {
        sparse[i] = rand.nextInt(sparse.length);
    }

    int[] freq = new int[1<<18];
    for (int i = 0; i < freq.length; i++) {
        freq[i] = rand.nextInt(10);
    }

So, two different datasets.... and then, I use the data in 5 different sizes.... each size is half the size of the next size.... so, I have data of 16K, 32K, 64K, 128K, and 256K.

I then run each of the algorithms a number of times for each data size. The number of times depends on the size of the data.... The bigger the data is, the fewer times I run the loop, and, as the data size doubles, I halve the number of iterations.

iterations   256    128    64     32      16
data size  16384  32768 65536 131072  262144

In theory, in a perfectly scalable system, the data-size and iteration combinations should result in constant-time execution....

Then I timed the actual execution times, and here are the results (on a warmed up system).

RLsparse,130.632,164.163,225.850,271.158,289.436,322.981,343.293,360.966,390.827,412.959
RLfreq,60.455,66.364,53.215,76.341,82.661,85.065,88.740,87.201,89.798,87.361
2Ssparse,157.926,184.521,214.407,242.943,256.200,286.686,352.467,438.048,420.164,666.043
2Sfreq,152.263,155.817,158.332,160.107,158.856,157.523,159.182,158.238,158.978,157.142
datasize,512,1024,2048,4096,8192,16384,32768,65536,131072,262144
iterations,8192,4096,2048,1024,512,256,128,64,32,16

Plotting this as a graph, using the datasize as the X axis, it looks like:

The 'dip' in the performance of the 2Ssparse 'curve' is consistent... there must be some anomoly that happens in the data of that size that 'wins' for whatever reason.

The 'obvious' observations are:

both algorithms like lots of duplicate values.
for high-duplicate values the 200_Success algorithm is practically O(n) and it appears the HashMap is O(1) as stated.
for sparse-duplicate values the 200_Success scales worse than the rolfl version, and, although it started faster, for larger data sets it quickly degrades to be slower.
for sparse-duplicate values the rolfl version is faster (runs in 2/3 of the time), but is slightly degrading in performance.... I expect that for all reasonable data sizes it will be faster.....

EDIT:

After a request for 'medium' amounts of duplication (the random numbers are taken from a pool of 1024 instead of just 10):

RLsparse,124.211,147.412,216.475,273.934,293.235,330.671,346.458,372.003,399.730,407.985
RLfreq,42.496,41.446,53.732,58.305,66.281,65.889,64.953,66.078,73.901,71.291
RLmedium,122.813,179.644,218.106,253.908,272.583,259.016,232.671,226.121,220.121,207.180
2Ssparse,155.091,180.669,205.877,236.890,254.193,288.193,351.495,450.381,426.626,665.759
2Sfreq,172.426,173.460,173.988,174.462,175.049,174.477,175.384,172.826,174.230,175.976
2Smedium,162.969,210.496,232.372,235.070,229.555,222.412,219.141,219.358,218.502,221.412

And the corresponding plot is:

EDIT2:

The HashSet based implementation has been revised to include hints on th size of the HashSets. The revised performance results are:

RLsparse,113.848,156.549,195.834,264.010,280.561,314.784,332.941,360.607,387.728,401.440
RLfreq,50.688,45.955,61.013,59.733,74.000,68.274,69.208,70.487,76.905,74.185
RLmedium,116.118,177.327,223.468,258.029,275.395,263.365,234.839,225.775,221.798,210.071
2Ssparse,127.956,160.641,159.736,171.221,180.202,195.650,265.159,328.633,270.251,369.847
2Sfreq,154.762,154.865,157.780,157.265,158.705,159.562,160.342,161.276,160.924,163.296
2Smedium,128.366,152.183,187.613,198.995,270.550,198.450,200.526,202.244,205.382,207.368
datasize,512,1024,2048,4096,8192,16384,32768,65536,131072,262144
iterations,8192,4096,2048,1024,512,256,128,64,32,16

And the corresponding plot is (Note the scale is the same as other plots, max 700ms):

Here is the code I used to generate the above graph (the actual algorithms not included since they are above...).

This code is not neat, and please do not review it .... ;-) But feel free to make any changes you like to improve it... I know it is ugly... but it works.

package dupcnt;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class CompareDups {

    public static void main(String[] args) {

        System.out.println("Building Data");

        int[] sparse = new int[1<<18];
        int[] freq = new int[sparse.length];
        int[] medium = new int[sparse.length];
        Random rand = new Random(1); // repeatable 'random' numbers
        for (int i = 0; i < sparse.length; i++) {
            sparse[i] = rand.nextInt(sparse.length);
        }
        for (int i = 0; i < freq.length; i++) {
            freq[i] = rand.nextInt(10);
        }
        for (int i = 0; i < medium.length; i++) {
            medium[i] = rand.nextInt(1024);
        }

        System.out.println("Built data " + sparse.length);

        final int dpoints = 10;
        int[] iterations = new int[dpoints];
        for (int i = 0; i < iterations.length; i++) {
            iterations[i] = 1 << dpoints + 3 - i;
        }

        for (int i = 0; i < 10; i++) {
            long[][] data = new long[8][dpoints];
            for (int dp = 0; dp < dpoints; dp++) {
                int[] input = null;
                input = Arrays.copyOf(sparse, sparse.length >>> dpoints - 1 - dp);
                data[0][dp] = processRL(input, iterations[dp]);
                data[3][dp] = process2S(input, iterations[dp]);
                input = Arrays.copyOf(freq, freq.length >>> dpoints - 1 - dp);
                data[1][dp] = processRL(input, iterations[dp]);
                data[4][dp] = process2S(input, iterations[dp]);
                input = Arrays.copyOf(medium, medium.length >>> dpoints - 1 - dp);
                data[2][dp] = processRL(input, iterations[dp]);
                data[5][dp] = process2S(input, iterations[dp]);
                data[6][dp] = input.length;
                data[7][dp] = iterations[dp];
            }
            String[] series = {"RLsparse", "RLfreq", "RLmedium", "2Ssparse", "2Sfreq", "2Smedium", "datasize", "iterations"};
            for (int s = 0; s < series.length; s++) {
                StringBuilder sb = new StringBuilder();
                sb.append(series[s]);
                for (long l : data[s]) {
                    if (s < 6) {
                        sb.append(",").append(String.format("%.3f", l/1000000.0));
                    } else {
                        sb.append(",").append(String.format("%d", l));
                    }
                }
                System.out.println(sb.toString());
            }
         }
    }

    private static long processRL(final int[] input, final int iterations) {
        System.gc();
        int cnt = 0;
        long nanos = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            cnt += findDuplicates(input).length;
        }
        if (cnt < 0) {
            throw new IllegalStateException("This is just to keep things from being optimized out.");
        }
        return System.nanoTime() - nanos;
    }

    private static long process2S(final int[] input, final int iterations) {
        System.gc();
        int cnt = 0;
        long nanos = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            cnt += findEvenOccurrences(input).size();
        }
        if (cnt < 0) {
            throw new IllegalStateException("This is just to keep things from being optimized out.");
        }
        return System.nanoTime() - nanos;
    }

}


Draw the tiles of the islands that are within bounds, using LibGDX

Reduce Allocations

Creating objects while the game is running is not optimal. You are also creating those objects inside of the render method which will be called many thousands of times.  The garbage collector is good, but you will still see performance spikes when it is doing too much work.

Luckily you can eliminate all of these allocations!

One approach that you will find useful is to use Pools. This is very easy when working with many libGDX classes. Setting it up is just one line where 100 below is the maximum number of objects you think you will need at one time:

private final Pool<Rectangle> recPool = Pools.get(Rectangle.class, 100);

Then when you want a rectangle object:

Rectangle focusedMapRectangle = recPool.obtain();

And when you are done using the object:

recPool.free(focusedMapRectangle);

The Rectangle class has a number of set methods in order to configure it after you obtain the object.

focusedMapRectangle.setX(getMatchMap().getBottomLeft().x);
focusedMapRectangle.setY(getMatchMap().getBottomLeft().y);
focusedMapRectangle.setWidth(Gdx.graphics.getWidth() / 16);
focusedMapRectangle.setHeight(Gdx.graphics.getHeight() / 16);

I mention Pools because I think you will find it useful in the future, however I actually think there is a better approach in this case.

You do need one new Rectangle at the start of the render method because it will match the current view of the world. However, rather than creating a new object each time, you could have one Rectangle and just use the set methods above to set it to the appropriate values.

That brings me to the next offender:

getMatchMap().getIslands().forEach((island, point) -> {
    Rectangle islandRectangle = new Rectangle(
        point.x,
        point.y,
        island.getMaxWidth(),
        island.getMaxHeight()
    );

What getIslands() returns is not totally clear to me, but I can tell that each island has a point associated with it. That point does not appear to be subject to change. I also assume that the maxWidth and maxHeight of the island are not subject to change. So why not pre-calculate the Rectangle for the island when first creating it? Then you can just do

if (focusedMapRectangle.overlaps(island.getRectangle())) {

and completely avoid allocating any new objects.

Beware of iterators

I don't know if you are using the libGDX Array and Map classes, but you should consider doing so if not. forEach by itself is not a problem, but if you are using the regular Java collection classes, iterating will lead to lots and lots of allocations. The libGDX collections are designed to avoid these allocations when iterating.

Separation of concerns

Currently your render method does two main things. It determines whether an island is in view, and then it renders it. However, it does both of those things for each island at the same time. I think that it would be better to separate the sorting from the rendering. First you would call a sortIslands() method that would put all the islands that need to be drawn into an array. Then the render method would just iterate over the array and draw the necessary islands. Later if you decide to change the way the islands are sorted, it will be much easier. It will also be more clear and more self documenting to do the sorting outside of the render method.

Is it worth it?

Sorting through the tiles to decide what needs to be rendered and what doesn't will (in my experience) end up using more resources than it is worth. I recommend profiling with and without culling in order to see if it provides any performance gains for your game.


Send an email if a URL is down twice only

Quoting: Be in the habit of always double-quoting your variables when you use them, e.g. "$url" instead of $url.  Otherwise, nasty vulnerabilities could happen if a variable's value contains spaces or shell metacharacters.  URLs, especially, often contain special characters such as & and ?.
Structure: When processing input with multiple columns, one row at a time, the idiom to use is…

while read url env ; do
    # Do stuff here
done < "$SCRIPT_LOC/urls.txt"

If the columns are delimited by something other than whitespace…

while IFS=: read user pwhash uid gid gecos homedir shell ; do
    # Do stuff here
done < /etc/passwd

Status of wget: You run wget twice for each URL.  Instead of trying to get the HTTP status code, consider using just the exit status of wget to indicate success or failure.

if wget -q -t 0 --spider --no-check-certificate "$url" ; then
    # Handle success
else
    # Handle failure
fi

I've used the --quiet flag here.  Also, I think that an infinite timeout (-t 0) is a bad idea.
HTTP status interpretation: HTTP status codes other than 200 (e.g. 2xx or 3xx) could also indicate some kind of success.
Filesystem littering: You litter the current directory with temporary files wget.output and "${ENV}_DOWN" and "${ENV}_DOWN_2".  Perhaps you could append all the state to a single log file.
SCRIPT_LOC could probably be computed using $(dirname $0).


Go implementation of dining philosophers

All in all, it's not a bad implementation at all. The bulk of my comments will focus on idiomatic golang stuff, and some small tweaks you can make to the main function. As I usually do here, I'll go through it line by line

func main() {
    const numPhilos = 5

OK, so you're starting out defining an untyped constant in your main. That's perfectly valid, and it doesn't make much of a difference, but generally speaking, I'd define my constants outside of functions. This makes it easier to centralise your constants, see what constants are used in the file/package (if you're exporting them), and makes it easier to break up your code into smaller functions further down the line. Moving on:

var forks [numPhilos]chan bool

OK, so arrays can be used in go, but it's generally recommended you don't. The rule of thumb is: use slices if you can. Next:

for i := 0; i < numPhilos; i++ {
    forks[i] = make(chan bool, 1)
    forks[i] <- true
}

Again, no real issues here, only, you're assigning a channel to an index in an array, and then writing to it, accessing the array again. I'd use a scoped variable instead. Next:

var wg sync.WaitGroup
for i := 0; i < numPhilos; i++ {
    wg.Add(1)
    go philos(i, forks[(i-1+numPhilos)%numPhilos], forks[(i+numPhilos)%numPhilos], &wg)
}
wg.Wait()

Right, short of what I pointed out in the comment about forks[(i+numPhilos)%numPhilos] being the same as forks[i], this all works, but there's quite a few things we can improve:

you're creating a var wg sync.WaitGroup, and passing pointers to it. Good, but why not create a pointer literal. It's safer (less likely to pass by value accidentally), and code is easier to read IMO
You're incrementing i, and accessing forks, knowing full well that the len(forks) won't be exceeded. After all, your loop is the same as the one you used to initialise forks. So why not loop over forks to begin with?
wg.Add(1) is incrementing the waitgroup for each routine, but you clearly know beforehand how many routines you're going to spin up. You can add that total number of routines to your waitgroup outside of the loop.
I don't like the names numPhilos and philos for a func.
You're passing the waitgroup as a last argument. It's more common to see context.Context as the first argument, and things like a waitgroup (controlling the runtime and routines) as first arguments, rather than last

Last line:

fmt.Println("Everybody finished eating")

This should not be the end of your program. You should close the channels!

Now, let's put all of this together:

const numPhilos = 5

func main() {
    // create slice, not an array - set capacity to numPhilos
    forks := make([]chan bool, 0, numPhilos)
    for i := 0; i < numPhilos; i++ {
        // create channel in local scope
        ch := make(chan bool, 1)
        ch <- true // write to channel directly
        forks = append(forks, ch) // append to forks slice
    }
    // I prefer literals, because I can create a pointer type directly
    wg := &sync.WaitGroup{}
    // add 1 for each channel in forks
    wg.Add(len(forks))
    for i, ch := range forks {
        // forks[i] is now ch, get the left one using the method you are using already
        go philos(wg, i, forks[(i+numPhilos-1)%numPhilos], ch)
    }
    wg.Wait()
    // close channels
    for _, ch := range forks {
        close(ch)
    }
    // done
    fmt.Println("Everybody finished eating")
}


Enumerate once

I'm not sure whether you intended to write this to be iterable only once. Is this as designed?

[TestMethod]
public void CodeReview()
{
    var bag = new ShuffleBag<string>(new[] { "a", "b", "c", "d" });

    var e1 = bag.ToList();  // randomized: "b", "a", "c", "d"
    var e2 = bag.ToList();  // last element: "d"
    var e3 = bag.ToList();  // last element: "d"
}

Collections interfaces

I would let the bag inherit IReadOnlyCollection<T> to provide eager access to the bag's size:

public int Count => m_values.Length;


Teamwork challenge for Timus Online Judge

Ow, my eyes.  Your variable names all look so long and similar.  I can't even see all of the code at once without line wrapping.  I'd rather read for (int i = 0; i < n; i++) than

for (int integersToBeProcessedCounter = 0; integersToBeProcessedCounter < countOfIntegersToBeProcessed; integersToBeProcessedCounter++) {

In cases like this, short variable names are fine, because it is an established convention that i is an array index, and n is the array size.

Furthermore, the verbose naming isn't really that accurate anyway.  integerBeingProcessed isn't really an integer, but a string.

A further improvement in naming would come from breaking out the array analysis into a separate function, so that main() is just responsible for parsing the input.  Then, integersAsStringArray and countOfIntegersToBeProcessed can become seq and seq.length, respectively.

Just applying some renaming and other minor transformations…

public class TestClass {

    static String firstLine = "8";
    static String secondLine = "1 1 2 3 3 3 10 10";

    public static void summarize(String[] seq) {
        int groupSize = 1;
        for (int i = 0; i < seq.length; i++) {
            if (i == seq.length - 1) {
                System.out.println(groupSize + " " + seq[i]);
            } else if (seq[i].equals(seq[i + 1])) {
                groupSize++;
            } else {
                System.out.print(groupSize + " " + seq[i] + " ");
                groupSize = 1;
            }
        }
    }

    public static void main(String[] args) {
        int arrayLen = Integer.parseInt(firstLine);
        String[] array = secondLine.split(" ");
        if (arrayLen != array.length) {   // Optional validation
            throw new IllegalArgumentException("Expected " + arrayLen + " numbers, got " + array.length);
        }
        summarize(array);
    }
}

I also propose the following algorithm, which does not need as much of a special case for handling the last element.

    public static void summarize(String[] seq) {
        int groupStart, groupEnd;
        for (groupStart = 0; groupStart < seq.length; groupStart = groupEnd) {
            String leader = seq[groupStart];
            for (groupEnd = groupStart + 1; groupEnd < seq.length && seq[groupEnd].equals(leader); groupEnd++);
            System.out.print((groupEnd - groupStart) + " " + leader +
                             (groupEnd < seq.length - 1 ? " " : "\n"));
        }
    }


First, an issue with behaviour: In guess_number you don't make sure the input from the user is a number at all. So you might end up calling int("oops"). This raises a ValueError, and since there's nothing to catch that, the program crashes. You'll want to do something about that. A simple solution could be
try:
    guess = int(input(...))
    if guess == random_number:
        ...
    else
        ...
except ValueError:
    print("That doesn't look like a number to me, but that's OK, I'll count it anyway :)")
    guess_count += 1

Side note, guesses that aren't in the interval also add to the counter. That might be on purpose, but since the validity of the input wasn't checked at all I don't want to assume, so I'm pointing it out.
There are also a couple minor issues with intro
First off, you're duplicating the num_range = input() line. If you get the input at the start of the loop (before the if) instead it'll be easier to change if for some reason you need to
Second, in python the usual approach is that it's better to ask for forgiveness than permission. That if check would usually be written using a try/except KeyError block (a bit like above). But if you don't want to do that, a more robust approach than the current one could be to check if num_range in num_guesses, in case a new option is added, or the program changes from accepting 1 and 2 to accepting "a" and "b".
On a related third note, the messages don't actually know what options are available, so there's a risk they get out of sync with the rest of the program. You can get a list of valid options as num_guesses.keys(), or use a for loop to iterate over the keys in num_guesses directly
Finally, I don't love the variable names. num_guesses sounds like it should be the number of guesses, but it isn't a number at all. Similarly, num_range doesn't have much to do with ranges of numbers either. num_range feels like it would be better described by a name like selection or choice, and num_guesses is a collection of available options, so maybe it could be called options?
options = {
    "1": (5, 50),
    "2": (10, 100)
}

print("Welcome to ... on the range you choose.")

for option in options:
    print(f"From 0 - {options[option][1]}, you'll get {options[option][0]} chances.")

while True:
    print("Choose a range:")
    for option in options:
        print(f"{option}. 0 - {options[option][1]}")

    selection = input()
    try:
        return options[selection]
    except KeyError:
        print(f"{selection} is not a valid selection.")


The viewModel property on the Extension example should be removed as it is redundant:

lazy var viewModel: ViewModel(main: self)

Irrespective of this, it seems unnecessary to create a separate ViewModel class solely for the purpose of encapsulating a configureView function. On that basis, the Extension approach seems like a much more sensible and performant way of managing this kind of configuration.


OK Assuming you need the "Assigned Table" to support the many to many relationship of a voter to address.

`assigned_id` int(11) NOT NULL AUTO_INCREMENT,
`voter_id` int(11) NOT NULL,
`address_id` int(11) NOT NULL,
PRIMARY KEY (`assigned_id`)

You don't need assigned_id. Remove this. The primary key is (voter_id, address_id)


Using hashing to create a PRNG with seed

Clean up

I don't know why it had to be so long and to have so many temporary variables. So I shortened it to make sense out of it. Here's what I got.

static int RandomHashFunction(int input, int max)
{
    using (var sha1 = new SHA1CryptoServiceProvider()) // Disposing things is a good habit
    {
        var ascii = ASCIIEncoding.ASCII;
        var hashAsString = ascii.GetChars(
            sha1.ComputeHash(
                ascii.GetBytes(input.ToString())
            )
        );

        return Convert.ToInt32(
            Math.Abs(
                Math.IEEERemainder(hashAsString.GetHashCode(), max)
            )
        );
    }
}

WAT?

It is still not obvious to me, what are you attempting to achieve. Could you provide:

a few samples of input and output.
declare a variable that you think works as a seed.
a reference to a particular algorithm you're trying to implement or at least are inspired by.
OR at least a mathematical formula that you think will give you the desired result.

To me, there are a lot of unnecessary steps and manipulations.

Convert.ToInt16 was used to return and int (which is Int32) -- this was losing some meaning units of the number...
Math.Abs. Why bother with it if the Math.IEEERemainder already gives you a number.
Relying on String::GetHashCode may also be a bad thing since

  The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another: MSDN

All these things seem very excessive and result in a messy code IMO.

Update 1

Updated the code to use symmetric GetChars and GetBytes based on the same encoding.

Update 2

Frankly, I am not finding the updated question very explanatory. The signature of the original function does not declare meaningful parameters. So I had to guess what their meaning is.

I also don't understand why a regular Random.Next*() won't work for you. It's trivial!

static int RandomHashFunction1(int seed = 1, int max)
{
    var randomDouble = new Random(seed).NextDouble();
    return (int)Math.Round(randomDouble * max);
}

If you really want to stay away from System.Random, you can use SHA1CryptoServiceProvider as you do in the original code, but I don't see why it is necessary.

static int RandomHashFunction2(int seed = 1)
{
    using (var sha1 = new SHA1CryptoServiceProvider())
        return BitConverter.ToInt32(sha1.ComputeHash(BitConverter.GetBytes(seed)), startIndex: 0);
}

Lastly, I don't see why do you need to use any string representation at all and go through unnecessary steps with Math.* which make your function computationally heavier.

Please consider accepting the answer as it does the job, OR carefully describe the acceptance criteria. Your problem statement is unclear!

Update 3

Okay, you updated the question with the important info, which I quote here

  need to generate terrain so say we have a line that consists of dots with an X and a Y value. The X values start at 0 and can go to positive and negative infinity depending on the player position. Depending on the X I need a random Y. System.Random gives a random number and then another random number based on the previous one. If I would only move to the right I could keep on generating terrain based on the previous dot using random.Next () But if I wanted to go back I would need the previous number with you can't do with Random.Next().

This is the new version of the function that should meet your more precise problem definition.

static int ConsistentRandom(
    int maxRandomInt,
    int seedInGame = 1,
    int specificLocationInGame = 0
)
{
    var actualSeedForRandom = seedInGame + specificLocationInGame;
    var randomDouble = new Random(actualSeedForRandom).NextDouble();
    return (int)Math.Round(randomDouble * maxRandomInt);
}

Notice that var actualSeedForRandom = seedInGame + specificLocationInGame; may be implemented in many various ways, I just used the simplest formula that came to my mind.

Here's a test console app:

public static void Main(string[] args)
{
    for (var iteration = 1; iteration <= 2; iteration++)
    {
        Console.WriteLine("TEST ITERATION " + iteration);
        for (var seed = 0; seed < 2; seed++)
        {
            Console.WriteLine("SEED " + seed);
            for (var location = 0; location < 5; location++)
            {
                Console.Write(ConsistentRandom(10, seed, location));
                if (location != 4) Console.Write(" - ");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }

    Console.ReadKey();
}

And here's what it produces:

As you can see, as long as you know the seedInGame, you control the sequence of randoms. And if you know both the seedInGame and specificLocationInGame, you can easily get the specific value of random for this combination.

In other words, your Game should pick a new seedInGame on every new map it's trying to generate. The value of specificLocationInGame will let you "teleport" anywhere within this particular map.

Update 4 - To Address Concerns About Randomness

Here's the exact code I used to generate some consistent but random number sequence. The resulting sequence can be downloaded from here.

static void Main(string[] args)
{
    var path = @"C:\temp\generatedRandom.txt";
    if (File.Exists(path))
        File.Delete(path);
    using (var fileStream = File.Create(path))
    using (var textWriter = new BinaryWriter(fileStream, Encoding.ASCII))
    {
        var seed = 42;
        for (var location = 0; location < 3 * 3000 * 3000; location++)
        {
            var randomByte = ConsistentRandom(Int64.MaxValue, seed, location);
            textWriter.Write(randomByte);
            Console.WriteLine(randomByte);
        }
    }
}

static Int64 ConsistentRandom(
    Int64 maxRandomInt,
    int seedInGame = 1,
    int specificLocationInGame = 0
)
{
    var actualSeedForRandom = seedInGame + specificLocationInGame;
    var randomDouble = new Random(actualSeedForRandom).NextDouble();
    return (Int64)Math.Round(randomDouble * maxRandomInt);
}

I then used ent - pseudorandom number sequence test for checking how well the solution performs in terms of randomness.

I think, only the author can judge how far or how close this result is located from the desired one.

Update 5 - Visualizing the Solution (or How I Screwed Up)

Okay, I built a little tool to visualize the generated "random" sequence via the proposed algorithm (since I didn't find one online). The following picture demonstrates "little regularities" in the sequence... Well, the "random" sequence has very distinguishable regularities, so the proposed approach does not guarantee good results. I think, it's valid to suppose that approach in fact guarantees bad results. :(

@Wagacca, you were right in our conversation under my answer!


One thing I notice is that, you use global variables. While they are not necessarily bad and work fine in this particular case, it might be beneficial to read these answers. It would be better to define these variables in main function and pass them as parameters for other functions.

def start_game(number, counter):
  #Your code here

def main():
  number = 0
  counter = 0
  start_game(number, counter)

if __name__ == "__main__":
    main()

Calling the function within its body is called a recursion and as long as you assure that the calling sequence won't become an infinite loop, it is widely used technique in programming.

One more minor thing: you define val = int(guess) but never use it, maybe delete it?

Other than that, everything looks fine and the code is readable.


No Type Safety

Currently your classes provide no type safety:

Cache cache = new Cache();
cache.put("my key", Integer.class, 5);
// ...
String cached = cache.get("my key", String.class);

This compiles but fails at runtime with a ClassCastException thrown by CachedValue.getValue.

What's The Key?

The reason why this can happen is that your class is not clear on the role of the type given to put and get. Considering the internal map, the type is clearly part of the value. But get uses it as it were part of the key. This makes it possible to request a value which is there (considering the string key in the map) but of the wrong type.

Compare this to the typesafe heterogeneous container as defined in Effective Java. There the type is part of the key (actually the only part) so if something is found in the map, it must be of the correct type. It is hence safe to cast to that type.

So in order to make your classes type safe you have to decide on what exactly the key is.

String

If the key is only the string, I see no way to provide type safety. To keep the API from surprising its users you should then simply return Object. This effectively degrades your cache to a map from String to Object, which I guess is not your intention.

String & Class

The other possiblitiy is to make the type a full memeber of the key. There are several ways to implement this and I only present one. It uses nested maps which define this mapping:

String -> (Class -> Object)

This can be interpreted as

(String, Class) -> Object

so the type is part of the key.

public class Cache {

  private final Map<String, Map<Class<?>, Object>> internalMap;

  public Cache() {
    internalMap = new HashMap<>();
  }

  public <T> void put(String textKey, Class<T> typeKey, T chachedValue) {
    Map<Class<?>, Object> mapForTextKey = getMapForTextKey(textKey);
    mapForTextKey.put(typeKey, chachedValue);
  }

  private Map<Class<?>, Object> getMapForTextKey(String textKey) {
    if (!internalMap.containsKey(textKey))
      internalMap.put(textKey, new HashMap<>());
    return internalMap.get(textKey);
  }

  public <T> T get(String textKey, Class<T> typeKey) {
    Object untypedCachedValue = getUntyped(textKey, typeKey);
    // the cast can not fail because:
    // - if there is no value for those keys, the argument is null,
    //      which can always be cast
    // - if there is a value for those keys, `put` made sure that
    //      its type matches the type used as a key
    return typeKey.cast(untypedCachedValue);
  }

  private Object getUntyped(String textKey, Class<?> typeKey) {
    if (internalMap.containsKey(textKey))
      return internalMap.get(textKey).get(typeKey);
    else
      return null;
  }

}

Improvements

My proposal above is only the barebones of an implementation. There is a lot of room for improvements. Some of them are:

handling null aftert answering these questions:

should it be valid for keys? (please not!)
should it be valid for values? (also rather not; doesn't seem to make a lot of sense for a cache)

let get return an Optional<T>
use Map.computeIfAbsent for more concise code
or use Guava's Table instead of the nested maps
designing the class for extensibility or making it final

Furhter Comments After The Update

Looks much better. :) These comments are mostly nitpicking...

Comments regarding the code:

About null:

@NotNull is nice but as far as I know it's purely for tools. To have a runtime guarantee you should add Objects.requireNonNull. On the other hand, you use the HashBasedTable so you're fine  - it's documentation says: "Null row keys, columns keys, and values are not supported.". If you rely on that, you should declare table as that type and make sure do write a comment explaining this unusual decision (normally you declare the interface as you did).
I'd also make typeKey not-nullable.
I like the use of Optional (see here how much). I recommend to use Java 8's version because I expect it to become more common than guava's version.

Since Table.getis so concise, getUntyped looks a little pointless now. I would remove the method.
I like logging the calls. For symmetry I would also add it to put.

On style:

You are very liberal with empty lines. I'd recommend to not do that and only insert an empty line to separate distinct blocks. There seems to be little need for that in the code above.


Generating a list (or a string) with random elements

Within python there is the faker package creating "human" data. It's often used for testing and can easily be extended to your personal needs:

Link to github

It also has a command line interface. Here is the example from the official documentation:

$ faker address
968 Bahringer Garden Apt. 722
Kristinaland, NJ 09890

$ faker -l de_DE address
Samira-Niemeier-Allee 56
94812 Biedenkopf

$ faker profile ssn,birthdate
{'ssn': u'628-10-1085', 'birthdate': '2008-03-29'}

$ faker -r=3 -s=";" name
Willam Kertzmann;
Josiah Maggio;
Gayla Schmitt;


Document (PDF, TXT, DOCX) to text classes

You have two methods getText() and handle() of which one is not needed. Doing the conversion and returning the result should be one method. So, like this:

class Converter
{
    protected $file;
    protected $text;

    public function __construct($file)
    {
        $this->file = $file;
    }
}

and:

class PDFConverter extends Converter implements IConverter
{
    public function getPlainText()
    {
      if (is_null($this->text)) // not yet converted?
      {
        $this->text = 'Text PDF'; // do the conversion
      }
      return $this->text; // return result
    }
}

This way you still buffer the result, but you get rid of the rather weird handle() method.

When using this class you don't have to think about the order in which to call the methods anymore, just ask for the plain version of the text and the method will do the conversion only once.

You might want to move the declaration of the $text field to the other class.


Below are some of the changes I would make to your code. In my opinion one of the nice aspects of Scala is that it gives you all sorts of ways to reduce the amount of work your mind has to do in order to decipher code. As an example, one of the first things I did was declare a type ArrD that is equivalent to Array[Double]. I then just substitued where necessary and the code (to my mind) became more readable. The choice of ArrD was arbitrary on my part, you could if you wanted use ArrayDouble instead. Along these lines I shortened all of you variable and value names.

As the program is set up right now you don't need to pass in a procs array, but I left it in anyway. As you mentioned this is a homework assignment so I'll leave a bit of mystery as to why this is. And really you don't need the take and the drop.

Next note that jobs.sorted is equivalent to jobs.sortWith(_ > _).

And finally (for now) checkout how I initialized jobs and procs. If you still would like to use your randomElements function you should look into the method called tabulate.

Cheers.

object O {

  type ArrD = Array[Double]

  def findMaxSolver(procs: ArrD, jobs: ArrD): Double = {
    val sJobs  = jobs.sorted
    var sProcs = sJobs.take(procs.size)

    for(job <- sJobs.drop(procs.size)){
      sProcs     = sProcs.sorted
      sProcs(0) += job
    }
    sProcs.max
  }

  def solve(procs: ArrD, jobs: ArrD, f: (ArrD, ArrD) => Double) = f(procs, jobs)

  def run = {
    val jobNum  = 1024
    val procNum = 8
    val jobs    = Array.fill(jobNum)(scala.util.Random.nextDouble())
    val procs   = Array.fill(procNum)(0.0)
    println(s"RESULTS:\nFind max solver ${solve(procs, jobs, findMaxSolver)}")
  }
}


MVC - Control Class - Architecture / Design - Structure Review - PHP

Would separate those includes a bit differently. I'd use a newline after each include then use a double new line when I wanted to section them off. All one line as you are doing, and not even spaces between them, could make someone think that you have only three includes. Speaking of includes. You are loading all of these classes that you aren't going to use. Take a look a lazy initialization. Assuiming you only need to use those classes once in this class, and that is in that switch statement, then you can just include the correct one via case and avoid the overhead of those other unneeded classes.

Would have to agree with Corbin about this looking more like a dispatcher/router. These are okay, just letting you know that what you have isn't a controller.

Would suggest moving the send() method out of the switch. It doesn't really appear to change much and is just causing you to rewrite code. Assign whatever paramters you need to in the switch and just call the method outside of it. To prevent the default case from doing this, since you mentioned wanting to use try/catch, I would throw an error there instead of using echo.


Not a lot to review there;

The code is well documented and readable, the only thing I frowned at was df[df == 0.0], but my Python is probably just not good enough.

In can only think of the fact that replace can take a list of strings for to_replace, so you can merge the last 2 statements, which will give a speed up.

From a design perspective, all the routines writing to your database should never write empty lists, zeros, empty strings or nulls, but NaN instead. Then you would never have to run this script in the first place.


Simple winform that randomizes images in a picturebox

private void initializeImages()
    {
        string appRoot = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
        files = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files2 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files3 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files4 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files = files.OrderBy(x => rnd.Next()).ToArray();
        files2 = files.OrderBy(x => rnd.Next()).ToArray();
        files3 = files.OrderBy(x => rnd.Next()).ToArray();
        files4 = files.OrderBy(x => rnd.Next()).ToArray();
    }

Here you load the same file names into four different arrays of strings. This is very memory inefficient and unnecessary. Instead only load them once into a single array and shuffle that when you want to change the images in the picture boxes.

In general: when you feel the need to add indices to the names of a set of variables like you do, you should reconsider your design - and you'll probably realize that an array or list or other kind of collection is the solution.

Random rnd = new Random();

In general: avoid abbreviated names of properties, fields, methods, object/classes etc. Provide descriptive names and let intellisense in the IDE do the work for you. Here random or randomGenerator would be descriptive names.

private void button1_Click(object sender, EventArgs e)
    {
        initializeImages();
        nextImage();
    }

Here you repeatedly reload the image file names. This makes sense if the number of images in the location changes - but you look in a sub folder to the installation folder which indicates that they are rather constant, so no need to do it other than when the form loads.

Below I've tried to refactor your code while implementing the above suggestions:

private string[] imageFileNames;
Random random = new Random();

public Menu()
{
  InitializeComponent();

  InitializeImages();
}

private void InitializeImages()
{
  imageFileNames = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Resources"));
}

private void ShuffleImages()
{
  Array.Sort(imageFileNames, (a, b) => random.Next(0, 3) - 1);
}

private void SetImages()
{
  var picturBoxes = new[] { pictureBox1, pictureBox2, pictureBox3, pictureBox4 };

  for (int i = 0; i < picturBoxes.Length; i++)
  {
    picturBoxes[i].ImageLocation = imageFileNames[i % imageFileNames.Length];
  }
}

private void button1_Click(object sender, EventArgs e)
{
  ShuffleImages();
  SetImages();
}

If the number of images is limited you can consider to load them all once into an list of Image objects and then shuffle these instead of the file names.

private void InitializeImages()
{
  images = Directory
    .GetFiles(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Resources"))
    .Select(fn => Image.FromFile(fn)).ToArray();
}