Your iff function would be better expressed with <|> or msum. They're for making a choice, so one of them ought be used in place of iff, I'm not sure where the True/False values are feeding out into iff, but I would maybe change them to feed out something that's a Monoid type or MonadPlus instead of Bool then use the appropriate choice technique.

You named a data type which appears to be the purpose of being a state Result, was this supposed to be a Command, Instruction, NextState, or Update instead perhaps? Result seems like a confusing name to me for what I (think?) that is.

data Update = Color (Float, Float, Float) | Quit | Reset | etc | etc | whatever
type Command = (Game -> Update -> IO Game) -- Presuming those functions which execute changes like doColorRed return an IO monad

I think you're missing a cohesive set of data models to present your system and it's possible states for which you could write functions to alter... When working with any UI presentation, it's usually best to create a model of your system and a separate view which responds to your model.

I would change:

  case mx of
     Left ex -> putStrLn $ "Inhibited: " ++ show ex -- this should never happen
     Right (GameColor c) -> do
       Al.clearToColor c
       Al.flipDisplay
       loop w' session' q
     Right Quit -> return ()

To:

toColor (r,g,b) = Al.Color {Al.colorR = r, Al.colorG = g, Al.colorB = b, Al.colorA = 1.0}
ProcessCommand g (Color c) = Al.clearToColor (toColor c) >> Al.flipDisplay >> (gameLoop g)
ProcessCommand g Quit = return ()

then where you do your case, make sure your Game data type (represented as g above) has those w', session', and q variables as a part of your Game data type so the gameLoop function can execute that loop given any Game

and your case can take advantage of the exception monad instead of doing a case...

fmap (processCommand g) (mx <|> Right $ someFunctionThatTakesMxAndCreatesACommandToPrintTheError mx)

Give some of these techniques a try and see how it cleans up for ya. After that perhaps you'll see a higher level design appear that will make the domain a little easier to model and approach.


I think mt_srand seeds the rng for mt_rand, not for rand. What you probably want is srand. Although seeding it with the time is not that good of an idea, as time is a value an attacker might guess.

But really, there is no reason to use rand in the first place (the documentation also warns against using it when secure values are needed). Just use openssl_random_pseudo_bytes:

base64_encode(openssl_random_pseudo_bytes(32));

I don't really see a reason to place hyphens in-between the characters. It doesn't really add anything. It just makes the token longer, without adding randomness. I also don't see a reason for strtoupper, it even reduces randomness.

Also note that uniqid is not supposed to be used for any security purposes. If we assume that it is completely broken (which it is probably not, but I haven't looked at the code, and it does have a big warning in the documentation), that would only leave you with 10 random numerical characters (from a not-so-great rng), which doesn't seem that great.

I don't think that there is really a security issue with what you have, but it is definitely not the correct approach. Just use openssl_random_pseudo_bytes instead. It's definitely more secure, and the code is considerably shorter, and can easily be adapted (just change 32 to 64 if you want more security; with your code, you would have to change a lot more).


I only have a few small remarks to make:

In your header file, don't include <iostream>: include <iosfwd> instead which contains the forward declarations for every type in <iostream>.
Also, you only use std::ostream in your source file, so you could simply include <ostream> there.
Several times, you compute mymonth / 12 and mymonth % 12. If your class is designed to be used intensively, you could consider using std::div(mymonth, 12) which will compute both values at once and may therefore be slightly faster (if you really need it).
You may want to prefix time_t, time, tm and localtime with std::. Them coming from the C standard library doesn't prevent you to use std::.
Using a const unsigned parameter seems pretty useless. I don't have strong opinions on the const on value parameters, but you could safely drop it since it adds little value.


Simulated race among three robots making random steps

You did not model the race correctly. The specification says:

  All three robots stop once one of them is one pace away from reaching 1km.

In your code, each robot runs the whole distance. The effect is that if you have one fast robot with a constant pace of 90 and one slow robot with a constant pace of 1, your code will make the slow robot win.

But at the time the race is over (after 12 steps), and at this point the slow robot is nowhere near the middle.

(Oh, there's one thing. When the paces are random, how can I know in advance whether the robot is one pace away? That gets complicated, but it is possible.)

Following the specification by the letter, the race has to be simulated very closely to the wording. That is, all robots start at the start, and in each step, each of them advances by its own pace.

Here is how I modeled the race:

'use strict';

class Robot {
    constructor(color, pace) {
        this.color = color;
        this.pace = pace;
        this.position = 0;
    }

    advance(distance) {
        this.position += distance;
    }
}

class Race {
    constructor(distance, robots) {
        this.distance = distance;
        this.middle = distance / 2;
        this.robots = robots;
        this.over = false;
        this.minMiddleDistance = this.middle;
        this.bestRobot = robots[0]; // Technically, it's a tie.
    }

    step() {
        // Calculate the robot's paces for this step in advance,
        // before actually advancing the robot's positions,
        // to satisfy the "one pace away from reaching" requirement
        // in combination with the "each pace is random" requirement.
        const paces = this.robots.map(robot => robot.pace());

        const raceLength = this.distance;
        this.over = this.robots.some((robot, i) => robot.position + paces[i] >= raceLength);
        if (this.over) {
            return;
        }

        this.robots.forEach((robot, i) => {
            robot.advance(paces[i]);
            const middleDistance = Math.abs(robot.position - this.middle);
            if (middleDistance < this.minMiddleDistance) {
                this.minMiddleDistance = middleDistance;
                this.bestRobot = robot;
            }
        })
    }
}

function rnd100() {
    return (100 * Math.random()) | 0; // only integer steps
}

// The specification does not say how each robot's pace is determined.
// The lambda functions in the following code can easily be replaced
// with rnd100 or any other number generator.
const robots = [
    new Robot('red', () => 90),
    new Robot('green', () => 7),
    new Robot('blue', () => 45)
];

const race = new Race(1000, robots);
while (!race.over) {
    race.step();
}
console.log('The winner is ' + race.bestRobot.color + ' with a distance of ' + race.minMiddleDistance + '.');

// Blue wins.
// The red robot crosses the finishing line after ceil(1000/90) == 12 steps.
// After 6 steps, the red robot was closest to the 500 mark, at 540.
// After 11 steps, the blue robot was at 11*45 == 495.
// The green robot is too slow to be a competitor.

I made the Robot class pretty small because the robot should not be involved in calculating the outcome of the race. Who knows, maybe one of them would try to cheat?

All the calculations happen in the Race class, which coordinates the robots.


Save/Load GridView layout using SettingsService

At the recommendation of @svick, I decided to serialize the objects themselves. Rather than creating a custom object/stub, I just added [JsonIgnore] attribute to the properties that I did not want to serialize.

Here is the new code for saving the layout:

private void MainGridView_OnDrop(object sender, DragEventArgs e)
{
    var grid = e.OriginalSource as GridView;
    var items = grid?.ItemsSource as ObservableCollection<AppPage>;

    if (items != null)
    {
        foreach (var p in items)
        {
            p.PageIndex = items.IndexOf(p);
        }
        // serialize items
        var layout = JsonConvert.SerializeObject(items);
        _settings.MainMenuLayout = layout;
    }
}

Then I was able to simplify reading the layout from settings like so:

var layout = _settings.MainMenuLayout;
if (!string.IsNullOrEmpty(layout))
{
    var pageStubs = JsonConvert.DeserializeObject<ObservableCollection<AppPage>>(layout);

    foreach (var p in pageStubs)
    {
        var cur = pages.First(page => page.PageName == p.PageName);
        cur.PageIndex = p.PageIndex;
    }
    // sort based on index
    AppPages = new ObservableCollection<AppPage>(pages.OrderBy(p => p.PageIndex));
}
else
{
    AppPages = pages;
}

The only properties of AppPage that get serialized are the PageName and PageIndex, which are the only properties used for this process.

Any further improvements are always welcome!


No way to stop the cycle.
The standard with TPL is to use the CancellationToken.  Even if it is not need now, which I don't know why, it would be easier in the future if it supported it.  For example if it gets turned into a service can just cancel the Token Source or if stays a console app could trap Esc key and cancel token source.
Numbers for Task Delay.
It's easier to read/maintain
Task.Delay(TimeSpan.FromSeconds(1))

then
Task.Delay(1000)

For each Task instead of checking their time you can combine them with Task.Delay()
For example
Task.WhenAll(lastNodeCheck, Task.Delay(TimeSpan.FromMinutes(1)));

Now we have one task that will only complete when either a minute has passed and the main task has completed.  We can make a helper method for this
    public static Task DelayedTask(Task task, TimeSpan delay, CancellationToken token)
    {
        return Task.WhenAll(task, Task.Delay(delay, token));
    }

The downside to this is even if the task failed right away it will still wait the delay time before it gets logged that it failed. I don't think that's a big deal breaker but only you know that for sure.
Optional but you can make this into a queue
We can create a dictionary that waits for task to be complete then re-adds them if needed.   This will make the code a bit more complex but easier to add new task later on.
Something like
    private static async Task TaskQueue(CancellationToken token, params Func<Task>[] tasks)
    {
        if (tasks.Length == 0)
        {
            return;
        }

        var queue = new ConcurrentDictionary<Task, Func<Task>>();
        foreach (var task in tasks)
        {
            queue.TryAdd(task(), task);
        }

        while (!token.IsCancellationRequested)
        {
            await Task.WhenAny(queue.Keys).ContinueWith(completedTask =>
            {
                Func<Task> factory;
                var mainTask = completedTask.Unwrap();
                queue.TryRemove(mainTask, out factory);
                if (!mainTask.IsCanceled)
                {
                    queue.GetOrAdd(factory(), factory);
                }

                if (mainTask.IsFaulted)
                {
                    foreach (var ex in mainTask.Exception.InnerExceptions)
                    {
                        LogException(ex);
                    }
                }
            });
        }
    }

I haven't tested this with all options but with basic test seems to work.   We create a concurrent dictionary and load it with tasks that are in flight and factories to make the task.  As task complete we remove from the dictionary and re-add them.  Continue until we get told to cancel.
Now in the main method can look something similar to this
        var cancellation = new CancellationTokenSource();
        var cancelToken = cancellation.Token;
        Func<Task> checkGateWayFactory = () => DelayedTask(CheckGateways.CheckAll(configuration), TimeSpan.FromMinutes(1), cancelToken);
        Func<Task> checkNodeFactory = () => DelayedTask(CheckNodes.CheckAll(configuration), TimeSpan.FromMinutes(1), cancelToken);
        Func<Task> checkAlertFactory = () => DelayedTask(CheckAlerts.CheckAll(configuration), TimeSpan.FromSeconds(1), cancelToken);
        await TaskQueue(cancelToken,
            checkAlertFactory,
            checkGateWayFactory,
            checkNodeFactory);


Doubly-linked list program with delete functions

Comments in mostly top-down order.

class node // Creates node class

Classes in Java should begin with an uppercase letter.  Ie) class Node.

As it stands, this class can only be used inside DoublyLinkedList, so it should be declared private.  Ie) private class Node.

As a non-static inner class, it implicitly contains a pointer to the DoublyLinkedList object.  You never use this, nor with your current implementation do you need to use it.  It is just taking up extra space.  You can get rid of it by declaring the class static.  Ie) private static class Node.

public node()
{
    num = 0;
    next = null;
    prev = null;
}

This constructor is never used, so probably should be deleted.

If you did want to keep it, you should use constructor chaining, so you don't have to repeat initializations.  Such as:

public node()
{
    this(0);   // Calls node::node(double) constructor
}

public double findAvg()
{
    double mean = 0, total = 0;
    ...

    return(mean = total/i);
}

The parenthesis are not needed.
Possible division by zero, if called on an empty list.
Assignment to mean is unnecessary.  You can remove the assignment and the mean variable.

public void delete(double x) // Deletes a single node
{
    node p = new node(x);

There is no need to create a node here.  You are looking for a node which contains the value x.  Wrapping x in a node and then needing to refer to p.num in tests added complexity for no gain.

    node temp = head;
    node pre, nex;

pre and nex are unused an should be deleted.

    if (head.num == p.num) // If head node needs to be removed

NullPointerException if the list is empty.

    {
        head = head.next;

What of .prev of the new head?  It still points to the removed node.  But if there was only one node in the list, head is now null, and tail is still pointing to the removed node.

        return;
    }

    while (temp != null) // If a node in between is to be deleted

Actually, this will loop for all the nodes, not just the ones "in between".  You will be testing the head node a second time.  And it will test the last tail node as well.

    {
        if (p.num == temp.num)
        {
            System.out.println("Node found! Deleting " + x + "...");
            temp.prev.next = temp.next;
            temp.next.prev = temp.prev;

Fortunately, if the head node matched, the test at the start of the function would process the removal and return.  Otherwise, temp.prev.next = would raise a NullPointerException.

Unfortunately, if the last node happens to match, temp.next.prev = will raise a NullPointerException.

            return;
        }
        else temp = temp.next;
    }

If we get to this point, the number wasn't in the list, so the next code is pointless.

    if (tail.num == p.num) // If tail is to be deleted
    {
        tail = tail.prev;

But if we did get here, tail.prev.next would still point to the original tail node!

        return;
    }

You might consider raising a NoSuchElementException if you never found the value to remove.

}

Many similar comments for deleteMore().

After deleting 1 or more head nodes, you never set the new head.prev to null, or tail to null if you actually ended up deleting all the nodes.

if (temp.num == tail.num) // If tail node needs to be removed

This does not test for reaching the end of the list.  If the list has nodes in the middle which happen to match the value at the end, and that value is above the removal threshold, when you get to that middle node, your processing will skip to the tail node.

To test for the last node, you want

if (temp == tail) // If tail node needs to be removed

or

if (temp.next == null) // If tail node needs to be removed

You should add more test cases, to cover the bug found above.  Once you can show the code breaks, you can fix the code, and demonstrate it works because the test cases now pass.


The only really odd thing I see is this:

x - 0.05 % 1

Modulation takes precedence over subtraction, and 0.05 % 1 == 0.05, so the modulation has no effect. Is this what you intended?


"back substitution" method for solving linear system

A few quick suggestions that I may flesh out in further edits:

If looks like x[i] is a function of x[i+1] and selected items from A and b.  Then it could also be seen as forward itertion on a reversed list, xr[i+1] dependent on xr[i].

np.cumsum and related accumulated functions are often useful in problems like this.

There's a set of tri functions that give you indices and values on upper and lower triangular matrices.

Typically 'vectorizing' in numpy requires stepping back a bit from the problem and imagining in terms of operations on a table or 2d array of values.

(this question would have gotten more attention on SO).


Here are some things that, in addition to the other review, may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  In this program, especially, it's completely simply to eliminate because the namespace is already explicitly specified every place it's needed.

Prefer constexpr to old-style #define

Rather than using a #define for SIZE the code could use a constexpr:

constexpr size_t SIZE{3}; //  this is number of child nodes a node will have

It doesn't make a huge difference here, but generally the advantage is that the value has an associated type.

Use appropriate data structures

The code implies that there are only and exactly 3 children nodes for each node, but the data structure is a std::vector<Node*> with a #define SIZE 3.  This means that the size is set at compile time, but that there is no explicit prohibition to having 2 or 5 or more children.  Better would be to define the variable as std::array<Node*, 3> v_node;.  This would also eliminate both of the resize calls associated with the v_node variable.

Be careful with signed versus unsigned

The code currently contains this line:

    for(int i = 0; i < SIZE; i++){

But would it ever make sense for either i or SIZE to be negative?  Probably not, in my view, which means that it would likely make more sense, considering how they're used, to have both declared as size_t types

Prefer modern initializers for constructors

The constructor could use the more modern initializer style rather than the old style you're currently using.  Instead of this:

Tree(int s){
    size = s;
    root = new Node;
    root->my_vec.resize(s, 36);
    root->val = 0;
    count = 0;
}

You could write this:

Tree(int s) :
    root{new Node},
    size{s},
    count{0}
{
    root->my_vec.resize(s, 36);
    root->val = 0;
}

This could be even more simplified by implementing the following suggestion.

Rely on constructors to always create valid objects

By defining constructors for classes such as Node, you can assure that any Node object is actually valid; that is, it has a consistent internal state, according to whatever that might mean for your code.  In this particular case, defining a constructor for Node makes much of the rest of the code much simpler.  For example, we might move from a struct to a class definition like this:

class Tree;

class Node{
    std::array<Node*, 3> v_node;
    std::vector<int> my_vec;
    int val;
public:
    friend class Tree;
    Node(size_t count, size_t vecsize, int myval) :
        v_node{},
        my_vec(count, vecsize),
        val{myval}
    {}
};

Now the Tree constructor could be this:

Tree(int s) :
    root{new Node{s, 36, 0}},
    size{s},
    count{0}
{ }

And the loop within create_tree reduces to just a few lines:

for(size_t i = 0; i < SIZE; i++){
    n->v_node[i] = new Node{size-1, n->my_vec[0]-1, i};
    create_tree(n->v_node[i], size-1);
}

This same general principle also means that it makes little sense to have separate constructor and initialization calls.  So instead of this in main:

Tree t(4);
t.ct();

It should just be this:

Tree t(4);

And the Tree constructor would be this:

Tree(int s) :
    root{new Node{s, 36, 0}},
    size{s},
    count{0}
{
    create_tree(root, size);
}

The ct function would simply be eliminated.

Avoid memory leaks

You've already mentioned this in your problem statement, but for the benefit of other readers, the current version of the program leaks memory.  Two approaches would be to either add a destructor to each of the classes, or better, to convert from raw pointers to std::shared_ptr.

Algorithm correctness

Because the code is not really complete, (that is, the tree contains no meaningful data), it's difficult to say.  It constructs some tree, but whether it's a minimax tree is difficult to say outside of the context in which it will be used.


Algorithm to return unique values from unsorted input

There are three significant issues I would address here...

Ratchet Freak is right about being concerned about the Iterator/FilteredReader... but I disagree with his suggestion. I think the problem is that your code is converting a BufferedReader in to an Iterator, and making the results unique at the same time. This is a class that is performing 2 functions... and you shoould have two classes instead. One that converts the BufferedReader to an interator, and the other that enforces uniqueness.
If your input data really is huge, then a Set may not be the right data structure because of it's memory footprint. I have found that custom implementations of memory-efficient structures can save a lot of space. I hesitate to recommend that you change from the Set though, it is the 'logical' choice, but, if, for example, your average String value is about 16 characters, then more than half of your memory will be in the Set overhead. I have, in the past, had reason to do similar things to you, and have written a memory-efficient class that can be seen in JDOM here (you will need to make changes to that code if you want to use it because it will need to have a mechanism for a true/false seen-it test).
I have a pattern I use for Iterators that is really effective, and makes the Iterator logic much simpler/readable. I'll give you an example....

First, part 1, a Reader-to-Iterator implementation:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.NoSuchElementException;

@SuppressWarnings("javadoc")
public class ReaderLineIterator implements Iterator<String> {

    private final BufferedReader reader;
    private String nextval;

    public ReaderLineIterator(Reader reader) {
        this.reader = (reader instanceof BufferedReader) ? (BufferedReader)reader :
            new BufferedReader(reader);

        advance();

    }

    private void advance() {
        try {
            nextval = reader.readLine();
        } catch (IOException ioe) {
            throw new IllegalStateException("Unable to read from reader.", ioe);
        }
    }

    @Override
    public boolean hasNext() {
        return nextval != null;
    }

    @Override
    public String next() {
        if (nextval == null) {
            throw new NoSuchElementException();
        }
        try {
            return nextval;
        } finally {
            advance();
        }
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

}

Note how, in this class, I use a trick for the nextval, where it is advanced in the finally block of the next() call. This is a pattern I like because it makes the hasNext() method very light-weight, and it is always a step-ahead of the data.

So, that is a single-purpose class, it converts a Reader to a line-at-a-time Iterator.

Now, you need a unique Iterator... which can look something like:

import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;

@SuppressWarnings("javadoc")
public class UniqueIterator implements Iterator<String> {

    private final Iterator<String> source;
    private String nextval = null;
    Set<String> seenit = new HashSet<String>();

    public UniqueIterator(Iterator<String> source) {
        this.source = source;
        advance();
    }

    private void advance() {
        while (source.hasNext()) {
            String nxt = source.next();
            if (seenit.add(nxt)) {
                // found a unique value....
                nextval = nxt;
                return;
            }
        }
        // no more unique values.
        nextval = null;

    }

    @Override
    public boolean hasNext() {
        return nextval != null;
    }

    @Override
    public String next() {
        if (nextval == null) {
            throw new NoSuchElementException();
        }
        try {
            return nextval;
        } finally {
            advance();
        }
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

}


Creating an array length n * n, separating it into n groups, and adding numbers to it n times

Addressing into a 1d or 2d array is not a real problem for a square array

ary[i,j] = value;

can be written as

ary[i*n + j] = value

where n is the dimension.

The following passes the tests on CodingBat though there may be more elegant ways to approach it

public int[] squareUp(int n) {
    int[] result = new int[n*n];
    int zeroCount = n-1;
    for(int outer = 0; outer <n; outer++){
        for(int inner = 0; inner < n; inner++){
            result[(outer * n) + inner] = zeroCount > inner
                                            ? 0
                                            : (n-inner);
        }
        zeroCount--;
    }
    return result;
}


My method of escaping MySQL strings in C++

if (!MySQL_Database_Connection__global->host)
    int a = NULL;

What is the purpose of this if statement? It only contains one unused declaration.

if (dataIn) ... return ("");

I try to avoid adding defensive behavior like this. Returning empty string for NULL argument seems like a good idea and might even save your program from crashing. But, NULL argument indicates your program is already in invalid state and it's unlikely to function properly. Assertion or exception with clear indication what's wrong would save you a lot of debugging.

std::size_t dataInLen = strlen(dataIn);
escapeSQL(userTypedArgument).c_str()

Consider using just std::string or just C strings. Or at least minimize those awkward conversions back and forth. They can only lead to bugs like this one:

mysql_real_escape_string(MySQL_Database_Connection__global, &to[0], dataIn, dataInLen);

You are creating null-terminated C string inside std::string. std::string ignores null characters. to.length() will always return dataInLen*2+1. Any method other than c_str() will result in unexpected behavior.

char query[1024] = {'\0'};
snprintf(query, sizeof(query), "SELECT * FROM database.table WHERE column = '%s';", escapeSQL(userTypedArgument).c_str());

This is exploitable. You should check if the query exceeds 1023 characters and fail in a safe way (or just use std::string). Currently user can remove part of your query by entering a long string. For example:

"DELETE * FROM table WHERE name='long string ...' AND owner=currentUser"
                                                  ^ 1024th character


First of all: great work on the doctests.

Your spacing could be improved, you might want to run a tool like pep8 over your code and fix the issues it reports: (0, 1, 2) instead of (0,1,2) and such.

Your set method is quite defensive, which is a good thing. However, do you really want to allow setting a field to ' ' when it already contains a 'x' or 'o'? Likewise: Do you want to allow placing something on a field that already contains an 'x' or an 'o'? Either way is fine, depending on if you want the board to know about the rules of the game or not.

One thing I would recommend changing is replacing the elif. Prefer

elif coord not in self.board:

over

elif coord not in self.board.keys():

It's a bit more idiomatic.

The method filled could also be a bit more simple. You're looping over all the values. Using a list comprehension, you could write

return len([x for x in self.board.itervalues() if x != ' '])

There are probably many more ways to rewrite it, though.

Your definition of across:

across = [[i for i in itertools.product([0,1,2], [n])] for n in xrange(3)]

That looks quite complicated to me.

[i for i in itertools.product([0, 1, 2], [n])]

can be replaced by

list(itertools.product([0, 1, 2], [n]))

or even better:

[(i, n) for i in (0, 1, 2)]

This gives

across = [[(i, n) for i in (0, 1, 2)] for n in xrange(3)]

It seems a bit silly to use both (0, 1, 2) and xrange(3). I'd suggest replacing both by range(3) or (0, 1, 2). Using xrange is a bit superfluous for ranges of length 3.

across = [[(i, n) for i in range(3)] for n in xrange(3)]

Ideally, you'd want to just mirror the definition for down, instead of re-using across, as it more cleanly symbolises the symmetry

down = [[(n, i) for i in range(3)] for n in range(3)]

Beyond that, your rows is quite clean, except the definition of values could be replaced by

values = map(self.board.get, row)

But that doesn't matter that much.


Re-organising the code

You've tried to split the logic into small functions and that was a good idea. Unfortunately, because of the way it plays with a class member palinList, the flow is quite hard to follow. In order to avoid this, the best is to define small functions that perform a simple task and return a result and to try to avoid side-effects if we don't need them.

Also, your function and argument names are not really clear. In particular :

splitString() : one would expect this to get a string and to return a list of string
actualString : what is a "non-actual" string ?
largestPalindromeCheck(ArrayList<String> palList) : this returns the biggest string in the list, it doesn't really matter whether this is a list of palindromes or not.

You are importing useless packages.

You should remove useless code before submitting to code review.

The style for spacing and brackets is a bit unusual.

Taking this simple comments into account (except for the last one because I can't be bothered), here's the code I have rewritten :

import java.util.ArrayList;

public class LargestPalindrome{

    public static String findLargestPalindrome(String s){
        return getLargestString(findPalindromes(s));
    }

    public static String reverseString(String s){
        String reversedStr="";
        for(int i = s.length()-1 ; i >= 0 ; i--){
            reversedStr += s.charAt(i);
        }
        return reversedStr;
    }

    public static ArrayList<String> findPalindromes(String s){
        ArrayList<String> palinList=new ArrayList<String>();
        for(int i=0 ; i<s.length() ; i++){
            for(int j=i ; j<s.length() ; j++){
                String sub = s.substring(i,j);
                if(sub.equals(reverseString(sub))&&sub.length()>=3){
                    palinList.add(sub);
                }
            }
        }
        return palinList;
    }

    public static String getLargestString(ArrayList<String> list){
        int maxLength=list.get(0).length();
        int index=0;
        for(int i=1 ; i<list.size() ; i++){
            if(list.get(i).length()>maxLength){
                maxLength=list.get(i).length();
                index=i;
            }
        }
        return list.get(index);
    }

    public static void main(String[] args) {
        String s="JUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGERJUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGER";
        System.out.println(findLargestPalindrome(s));
    }
}

Making things faster

if(sub.equals(reverseString(sub))&&sub.length()>=3) can be rewritten if(sub.length()>=3 && sub.equals(reverseString(sub))) to avoid going through list construction if we don't need to.

Actually, this is not so much of an issue because we can make the check for palindromes more efficient : reusing this answer, one can define a check for palindromness that doesn't need to build a string and stops as soon as the string is indeed not a palindrom. With my examples, instead of going through 2420363 iterations in reverseString(), we now perform 31423 iterations in isPalindrome.

Now, for a more dramatic improvement we have to focus on what we really want to achieve, what we are really looking for : we don't care that much about populating a list of palindromes, we only care about the biggest one. What does this imply ? It implies that we can ignore whatever is smaller than what we have already found.

At this stage, the code looks like this :

public class LargestPalindrome{

    public static boolean isPalindrome(String str) {
        int n = str.length();
        for( int i = 0; i < n/2; i++ )
        {
            if (str.charAt(i) != str.charAt(n-i-1)) return false;
        }
        return true;
    }

    public static String findLargestPalindrome(String s){
        String biggestPalindrome = "";
        for(int i=0 ; i<s.length() ; i++){
            for(int j=i ; j<s.length() ; j++){
                String sub = s.substring(i,j);
                if (sub.length()>biggestPalindrome.length() && isPalindrome(sub)){
                    biggestPalindrome = sub;
                }
            }
        }
        return biggestPalindrome;
    }

    public static void main(String[] args) {
        String s="JUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGERJUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGER";
        System.out.println(findLargestPalindrome(s));
    }
}

Now, an additional trick : for a given i, j will go through all values from i to s.length() -1 and the order does not really matter (yet). Thus, the loop can be returned : for(int j=i ; j<s.length() ; j++) becomes for(int j=s.length()-1 ; j >= i ; j--). First cool thing : for a given i, we'll call length() only once : it doesn't look like much but as it comes for free, it's pretty good already but the best is still to come. Indeed, for a given i, the substrings we are considering will get smaller and smaller. Thus, we can stop iterating whenever the strings we would consider become smaller than what we have found already.

This can be written :

public static String findLargestPalindrome(String s){
    String biggestPalindrome = "";
    for(int i=0 ; i<s.length() ; i++){
        for(int j=s.length()-1 ; j >= i ; j--){
            nbIt++;
            String sub = s.substring(i,j);
            if (sub.length() < biggestPalindrome.length()) break;
            if (isPalindrome(sub)){
                biggestPalindrome = sub;
            }
        }
    }
    return biggestPalindrome;
}

Actually, we don't even need to build that substring to consider its length : because of the way we construct it, sub.length() == j-i and this optimisation can be included as part of the for syntax : for(int j=s.length()-1 ; j >= i + biggestPalindrome.length(); j--).

At the end, my final version of the code looks like :

public class LargestPalindrome{

    public static boolean isPalindrome(String str) {
        int n = str.length();
        for( int i = 0; i < n/2; i++ )
        {
            if (str.charAt(i) != str.charAt(n-i-1)) return false;
        }
        return true;
    }

    public static String findLargestPalindrome(String s){
        String biggestPalindrome = "";
        for(int i=0 ; i<s.length() ; i++){
            for(int j=s.length()-1 ; j >= i + biggestPalindrome.length(); j--){
                String sub = s.substring(i,j);
                if (isPalindrome(sub)){
                    biggestPalindrome = sub;
                }
            }
        }
        return biggestPalindrome;
    }

    public static void main(String[] args) {
        String s="JUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGERJUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGER";
        System.out.println(findLargestPalindrome(s));
    }
}


Both algorithms appear to be O(sqrt(n)), so there isn't anything to choose between them in terms of algorithmic complexity. The only significant difference I see is between a one-off conversion from list to set and a series of calls to add(). I would guess that the former will be quicker (i.e. your first implementation will be quicker), but this is definitely in the realm of things you should benchmark rather than attempting to guess. It depends on the particular implementation of the data structure in Python, and it may even depend on factors like the order in which you insert the elements (though I believe Python implements sets using a hash table rather than a binary tree, which should mean order of insertion doesn't matter).

A bigger question is whether you should be using a set at all. Your algorithm doesn't require a set to ensure uniqueness of factors. When you return the collection from the function the code that uses it might convert it straight to a list, in which case you've wastefully converted it to a set and back again. If you do the minimum of conversions necessary to get a result, then you avoid overhead and the caller can always convert it to a set if they need that.

On the other hand, returning a set clarifies the API by imposing two additional requirements on the returned value: it is a collection for which ordering is unimportant, and it has only unique elements. The second of these is certainly appropriate here. There is a natural ordering of the factors (namely numerical ordering), but it would take extra effort to arrange the results in this order. It might be cleaner to return a set (for which the caller can't rely on any ordering) than an order that exposes the internal implementation to the caller.

Speaking of ordering, the naive way to return a sorted list of factors would be to sort the list at the end, which is of course O(n*log(n)). A better way might be to invert the order in which you process the range and use a deque as the output collection. Then each time you discover a factor pair you can put the large factor on one end and the small factor on the other, returning a sorted list with O(1) insertion overhead.

Returning to your original question: I assume this is code you're writing as an exercise rather than as production code? The right thing to do depends a lot on where the code is to be used, and you don't give any context. If you're trying to build your skills at optimisation then by all means micro-optimise and return the collection in a list to save set overhead. If you're writing high-performance library code then maybe you need to pay more attention to the API. If this is for a production system where it's not time-critical, you should stop trying to optimise for speed and go for whichever solution will be easiest to maintain, which is probably the one that's easiest to read.


Reservoir Sampling of an enumerable collection of unknown size

Let me try another answer.
Background info: Wikipedia Reservoir Sampling.
The intro header to the Wikipedia link states:

The size of the population n is not known to the algorithm and is
typically too large for all n items to fit into main memory.

But consider you have a dictionary to hold the results for all n items in your main memory.  And each example they provide has it returning a complete array, so it all has to fit into memory somehow.
You could make your life easier if your method accepted an IList<T> since that would return a known Count. Consider that each individual call to your method will enumerate over EACH element in the collection.  Since you pass in a 1000 element array, all 1000 elements are enumerated for one call, and you make 100 calls. I am just saying after the first call has been made, the size of the collection is no longer unknown.  Rather it is not remembered between invocations.
But that is not what you asked for. My answer continues to with IEnumerable<T> of unknown length.
Typically, one does not pass in the Random instance, but rather relies upon the method to have one handy.
The method name Random<T> is a poor name producing much confusion with the Random class. I suggest it be GetReservoirSample<T>.
For C#, the CodeReview community strongly supports uses braces to avoid one-liners.
There is no reason to OrderBy Key on histogram since it was created in Key order.
A quick reworking of your method, which includes Random as an optional parameter, would become:
private static Random _random = new Random();

public static T GetReservoirSample1<T>(IEnumerable<T> source, Random random = null)
{
    T result = default;
    int count = 0;
    if (random == null)
    {
        random = _random;
    }
    IEnumerator<T> e = source.GetEnumerator();
    // This enumerates over the entire collection!!!
    while (e.MoveNext())
    {
        if (random.NextDouble() < (1.0 / ++count))
        {
            result = e.Current;
        }
    }
    return result;
}

But that can be simplified by getting rid of the Random parameter.  And since you are iterating over all elements, there is no need for the enumerator.  You may use an foreach instead yielding smaller code.
public static T GetReservoirSample2<T>(IEnumerable<T> source)
{
    T result = default;
    int count = 0;
    // This enumerates over the entire collection!!!
    foreach (var element in source)
    {
        if (_random.NextDouble() < (1.0 / ++count))
        {
            result = element;
        }
    }
    return result;
}

IList versus IEnumerable
Finally, if you ever decide to change source to be an IList<T>, there is this version:
static T GetReservoirSample3<T>(IList<T> source)
{
    T result = source.Count > 0 ? source[0] : default;
    // This enumerates over the entire collection MINUS ONE!!!
    for (int i = 1;  i < source.Count; i++)
    {
        if (_random.NextDouble() < (1.0 / (i + 1.0)))
        {
            result = source[i];
        }

    }
    return result;
}

UPDATED
In my original example using IList<T>, there is no performance benefit.  Each example must enumerate over the full collection.  However, with a IList you can get a performance boost.  Essentially, your method remembers the last element that satisfies the condition but it must continue to enumerate over the remainder of the collection.
With a list, you can process the collection backwards and immediately return on the first item that satisfies the condition:
static T GetReservoirSample3B<T>(IList<T> source)
{
    for (int i = source.Count - 1; i > 0; i--)
    {
        if (_random.NextDouble() < (1.0 / (i + 1.0)))
        {
            return source[i];
        }

    }
    return source[0];
}

Also, I wanted to see the min and max values, so I altered Main for my own purposes.  I share it here:
public static void Main()
{
    var size = 1000;
    var tries = size * 100;
    var array = Enumerable.Range(0, size).ToArray();
    var histogram = array.ToDictionary(k => k, v => 0);
    var random = new Random();
    for (var i = 0; i < tries; i++)
    {
        histogram[GetReservoirSample3B(array)]++;
    }
    var min = int.MaxValue;
    var max = int.MinValue;
    foreach (var kv in histogram)
    {
        if (kv.Value < min)
        {
            min = kv.Value;
        }
        if (kv.Value > max)
        {
            max = kv.Value;
        }
    }
    foreach (var kv in histogram)
    {
        var extra = (kv.Value == min) ? "\t** MININUM ** " : (kv.Value == max) ? "\t** MAXIMUM **" : "";
        Console.WriteLine($"{kv.Key,5}: {kv.Value}{extra}");
    }
}

All that said, I do not know if you are correctly implementing a reservoir sampling.  From what I read, it expects you to return a sample subset of k elements where k is less than or equal to the source collection size of n.  Since you are returning a single element, that is for k == 1, then this produces the same distribution as:
static T GetReservoirSample3C<T>(IList<T> source) => source[_random.Next(source.Count)];


Can I simplify my phone look-up program?

Yes , you don't need to iterate through the map to know if it contains a certain value or not, you can just call get

 String contact = contacts.get(name);
 if(contact == null){
  // no such value
 }

You might have notice that I called it contacts instead of contact, because a map is a collection that holds things and things are plural.
Note: If you need to iterate over a map, don't use iterator, use enhanced-for instead.

for(Map.Entry<String,String> entry: map.entrySet()){

}

any language you use, you have to follow its naming conventions. Use Pascal casing for classes in Java

    class PhoneLookUp

and not

    class phoneLookUp

Use StringBuilder instead of String when you need to append frequently. Every time you do += on a String, it creates a new String because strings are immutable in Java, consider using StringBuilder instead.

  public static String outputFormat(String phone)
  {
  StringBuilder temp = new StringBuilder("(");

   for(int i = 0; i < phone.length(); i++)
   {
   if(i < 2){
     temp.append(phone.charAt(i));
   }
   else if(i == 2){
    temp.append(phone.charAt(i)+") ");
   }
   .....
  return temp.toString();

  }


Check if specific pattern exists in another array and save the index

Naming

NOTE: headerArray is the large array.

If you need to specify this to us, then your variable name isn't good. We should be able to understand your code with only your code because you wouldn't be beside us when we read it.

Don't worry about using full names for your variables. After all, is there a real difference between idxP and indexPosition apart from the fact that it's very clear I'll understand the latter one?

Commenting
Every time you want to write a comment, ask yourself if it is necessary. When you think it is, think again! :p Comments suck (I'm not really talking about XML comments on methods and classes and etc). When you write a comment in a method, it's because there's something weird enough that you'd feel the need to explain why you did something much more than what you did. In your cases, I don't think the comments are necessary.
Readability
In my opinion, there are two great and easy ways to make code more readable.

Extracting methods : Taking small chunks of your code that fills a single purpose and make a method out of it.

Reduce nesting : Remove as much forking as possible (if, while, for, etc.)

When dealing with algorithms, it's often hard to extract methods as many things are dependent.
However, you have lots of forking, so we can work with that.
if (pattern.length == 1) {
    if (pattern[0].equals(headerArray[idxH])) {
        allPositions.add(idxH);
    }
}

Everytime (exceptions might apply lol) you have two if stuck one to another, they can be merged using the AND (&&) operator.
if (pattern.length == 1 && pattern[0].equals(headerArray[idxH])) {
    allPositions.add(idxH);
}

Bam, nesting reduced.
You should try to find other ways to reduce nesting, but again, coding complex algorithms often imply spaghetti-ish code. And in this case, you might want to write a meaningful comment as to why your code is this way.
What's next?
If you really want to reach great performance for a "large" array, you might want to consider looking at String searching algorithms. It's not an exact fit to your problem, but there's something to be done.
Small nitpick : Large has a vague definition. If you want to make your code as correct as possible regarding your input, it can be useful to know an approximation of how much data your working with. For you, maybe an array with 100 elements is large, but for some data scientist at IBM, maybe it's 15000000.


Secure PHP login with SQL injection prevention

Magic variables

You are using invalid_username, invalid_login and some more magic names that are directly related to the login procedure. Factor those out and put them as static properties on your LoginManager class, so the actual contents are irrelevant and you can simply check against LoginManager::INVALID_LOGIN to see if that is the state of the session.

Factor out your session management

Creation and renewing of sessions should happen in their own class. Other code doesn't need to know how to make sessions, just that a session exists and who is authenticated by that session.

Factor out the salt

Move the salt to a config file somewhere. You don't want to have to dig through your code when you have to change the salt. If you do not want to have a config file, at least put it as a static or private variable in your LoginManager.

Odd sessions

You are making a session even if the login was invalid. Later you only check if a session exists, not if that session was valid. This allows someone to log in by entering a wrong username, or a right username with a wrong password.

Your LoginManager should also not disqualify usernames or passwords based on length, as this is a thing that should be enforced when setting a password or username. The login will always fail in those cases, so don't worry about it. You want to do the same amount of work for every login attempt to prevent an attacker gathering information about valid usernames/passwords based on the time it takes for a request to return.

Timezones

You are creating a date with gmdate(..) which is a UTC date. Later you are parsing it with new DateTime(..) as a local date and comparing it with a local date. This causes sessions to last longer or shorter based on where the server is.

Undefined variables

You are making sessions where the $userid is undefined. This means you cannot do anything useful with the session, as you lose information about who is logged in.

You are also setting the expiration date with $Date, a misspelled variable that is not defined either.

Queries can return false

You should always keep in mind that queries may fail. If your username query fails, it will return false, and sizeof(false) === 1. Your code would then error out on $userdata['password'], which is not that great.

Expired sessions

You are currently not doing anything with your expired sessions. That means they are not removed from the database after they expired.

Various

You specifically asked about sql injection and session hijacking. I believe your code to be reasonably safe on both accounts. If you are using truely prepared statements (not a setting that uses sprintf behind the scenes), you should be safe from sql injection. Your queries may still fail, but you should not be able to execute unintended sql queries.

Your sessions are based around com_create_guid, which I believe is cryptographically secure. The generated string is also long enough that guessing a session guid is practically impossible. You are making sessions less secure by essentially wanting a session to last forever, increasing the time they could be used by some malicious third party. I do not believe this to be a great risk in this case though.


UIButton Subclass - Overriding getters to return placeholder/default values

Is this an appropriate use of private variables? Is there any way to accomplish the behavior I want with a single variable rather a second optional settable variable for each color?

This can be much easier accomplished with a lazy stored property:

lazy var buttonColor: UIColor = UIColor.grayColor()
lazy var buttonSelectedColor: UIColor =  self.buttonColor.colorWithAlphaComponent(0.5)

The right-hand side is evaluated exactly once, when the property
is accessed the first time. This makes the private _xxx variables
obsolete. (I think that you seldom need such a "shadow copy" in Swift.)

But there seems to be no real need for buttonColor to be evaluated
lazily. If you make it an ordinary stored property then you can add
a property observer:

var buttonColor = UIColor.grayColor() {
    didSet {
        self.updateButton()
    }
}

If you want buttonSelectedColor to be computed from buttonColor then
it needs to be a lazy property, otherwise you could make it a stored
property as well:

var buttonSelectedColor = UIColor.grayColor().colorWithAlphaComponent(0.5)

  Is overriding UIButton properties to call adjustButtonColor in didSet abuse of the getter/setter?

That is fine. The Swift reference explicitly states: "You can also add property observers to any inherited property (whether stored or computed) by overriding the property within a subclass."

  If initWithCoder is a failable initializer do I need to check if self is nil before calling adjustButtonColor()?

You don't need to (and you can't). If

 super.init(coder: aDecoder)

fails then your init?(coder:) method fails immediately, and the next statement
is not reached.


Simplify IActionResult return value logic

So, as mentioned in comments: the code is readable and there are no issues with "verbosity". And as mentioned you can get rid of else statement, also it's a good habit to exclude "bad" cases at first.

public IActionResult Get(int id)
{
    var movie = context.GetMovie(id);

    if (movie == null)
    {
        return NotFound();
    }

    return Ok(movie);
}


Smallest number in BST which is greater than or equal to N

SmallestNumberGratherThanOrEqual

This looks mostly fine to me. I can't think how else to implement it, since you can't really separate the 'finding smallest' bit from the 'finding where num would go' bit.

The method should probably be public and static.
The spec does say a number N... but oh well. root is fine as the parameter name, but it quickly becomes misleading, as it ceases to be the root node pretty quickly.
It's iterative, which makes me happy.

Since I have so little to say about the code in question...

BstNode.Add(BstNode, int)

Why does Add take a BstNode as a parameter?!?!?!?1 Either it should be an instance method and operate on itself, or it should be static and operate on the parameter. The problem here is both conceptual and technical, as it makes no sense to ask a BstNode to operate on another BstNode, and it means that both nodes are in scope, so you might use the wrong one by mistake. I often have an instance method call a private static method simply to avoid this (e.g. when calling something iterative which will 'change' the parameter as it goes).
This is odd:

if (node == null)
{
    return new BstNode(key);
}

This bit doesn't actually add anything to anything - despite being in a method called Add - and is liable to cover-over a bug elsewhere which passes this method a null. Even worse, a null goes in, and something strange but not null comes out, which means the bug is likely to go even further now that there is some actual state going around.

I can see why it's there (it's part of the recursive method), but this sort of thing should not be public. Better would be to make this method private (and perhaps static and iterative as discussed above), and call it from another Add method which throws on null. This way, the specifics of your implementation of Add will not leak into the public API, and you can instead provide helpful error messages. You could also remove the return value, which is meaningless and just adds more confusion for the consumer.
Channelling t3chb0t for a moment... he might say that finding the base node and adding to it are different concerns, and that you should write one private method to find the node to add to, and call it from another which then does the adding. Such a method could not, however, be directly exploited to find the solution to the problem unless it was implemented in such a way that is basically did solve the problem, which is a bit of a shame.
As always, inline documentation (///) would be nice on this public method.

other BstNode stuff

keyt is a bit of an odd name.
Parent is never set. This is clearly an error and would make me as a consumer very sad if I'd designed my code around the assumption that I can access the parent of a BstNode and then discovered that I can not.
All the members are public fields: perhaps this is an attempt to avoid the overhead of getters? If so, don't worry about that cost: they are usually optimized away completely for non-virtual properties (at least, whenever I look for them they don't seem to be there).

I'd have Left and Right as public { get; private set; }. Parent and Value can be readonly if the tree if nodes are never removed from the tree. Indeed, for an 'add-only' tree, I'd be inclined to have the setters on Left and Right check that they are not overwriting anything. This would break the first test method, but frankly it's horrifying and ought to be rewritten.
Passing BstNode around is fine if everything knows that it is a tree, but really you should have a BinarySearchTree class which encapsulates these nodes, as it is meaningless and dangerous to operate on them independently (e.g. if you call Add on a child node you may end up with a mal-formed tree): nobody should have write-access to BstNode except BinaryNodeTree. Doing so would require exposing methods to traverse the tree without allowing modifications, so that you can still write the specified search outside of the BinarySearchTree class. This also gives a nice solution to the root parameter name problem.

Generics

If it weren't for the really horrible spec (-1 is a perfectly valid number, it should not be used as output here) I'd suggest this should be generic. Performance might suffer (depening on how you facilitate comparisons), but a generic solution is always nice: you can write a concrete version for int if the performance isn't good enough later.

Performance

I don't know anything about binary trees, but this is a very simple non-self-balancing implementation, and has a worst-case lookup time of O(n). A self-balancing tree (such as a Red-Black Tree (there are others) can guarantee logarithmic lookup time, at the cost of a more complicated data-structure and higher and the overheads which come with it. (This doesn't, however, change how you would implemented the specification, as it assumes a binary tree and doesn't ask you to modify it).

Boring stuff

I'd appreciate a few more empty lines to break the code up a bit, e.g. before the while, between all those ifs in Add, and before the returns.


Generating a random string of characters and symbols

Python already defines a number of strings of possible characters.  See string.ascii_lowercase and string.digits Source

I would use True and False instead of "yes"/"uppercase" as arguments to generator(). This function might be used by code that does directly interact with a user, so passing a string would not make sense. Additionally, the restart prompt supports a number of positive responses that are not supported by this function. You should have one layer that controls interaction with the user and one that generates a password. This will make the function cleaner as well as an easier API to work with.

Two more point about separation of concerns with generator():

It should return the password instead of printing it. Again, this allows the function to be used when not directly interacting with a command prompt.
It should throw an exception instance of calling sys.exit().  exit() will stop the python process and not allow any more execution of code. Your code is written so that multiple passwords can be generated one after another. However, if the user accidentally enters an invalid character to the first question, the application stops running instead asking the user to input a correct value. Throwing an exception would have the same result if you don't change the rest of your code, but allows you to change the code that interacts with the user to handle this case without restarting the application.

You convert length to an integer repeatedly instead of storing the value. The first validation completely ignores the result and the while loop does the conversion every time it tests if it should continue looping. This can all be solved by having length be passed in as an integer and letting the user layer handle the conversion and error cases.

Generator is already a well defined term with in Python that do something very different. The function should be renamed to generate_password() or something similar.


Your outer loop starts at 999 and the inner loop multiplies that by all the numbers from 999 down to 100.

Then your outer loop decrements $i to 998, and the inner loop multiplies that by all the numbers from 999 down to 100.  The first test 998*999 has already been considered, since multiplication is commutative.  Not a huge inefficiency at this first step, but it gets worse.

When the outer loop gets down to 100, the inner loop again multiplies that by all the number from 999 down to 100 ... only 1 combination which is new.

You should start your inner loop at $i, instead of at $max.

Early termination.  After finding a palindrome from the product of (say) 901 and 856, you don’t have to test whether the product is a palindrome (expensive operation) unless $result > $found is true (cheap test).  And if $result is less than $found, you can break out of your inner loop, since any successive product will be smaller.   Finally, if $i * $i < $result (combined with the first optimization), you can also exit your outer loop.


Is there a better way how to force file download than using this simple PHP script?

Always use === in your comparisons.

if (substr($_GET['file'], 0, 1) == '.'){
  die('trying to leave this directory? :)');
}

Should be:

if (substr($_GET['file'], 0, 1) === '.'){
  die('trying to leave this directory? :)');
}

Also look into other ways to sanitize $_GET['file'] properly at the moment I could pass in something like /../ and I could access other files.

From the docs you can save on a fopen() call by using readfile() instead see fpassthru()

A better way to use variables in a string is to use curly syntax so this line

header('Content-Disposition: attachment; filename='.$_GET['file']);

Would be better as

header("Content-Disposition: attachment; filename={$_GET['file']}");

I think that covers the three bullet points :)


By PEP 8, whiteScrape() should be renamed to white_scrape().

Variable names should be purposeful.  Therefore, it's a bad idea to continually redefine soup.  If someone were to ask you to explain what the variable soup contained, you would have a hard time explaining.

It seems like what you want to do is to stringify the children of div(s) in question.  One way to do that would be:

def white_scrape(url):
    page = opener.open(url).read()
    soup = BeautifulSoup(page)
    addr = soup.find('div', { 'class': 'addy' })
    return ''.join(str(child) for child in addr.children)

Note that this is not exactly equivalent to your original code.  For example, if an address contains an element, such as 123 1st St., this solution would preserve the  tag and its contents, whereas your original code would discard the tag but keep its contents and strip the tag.


Find a n x m binary matrix with exactly a 1's in all rows and b 1's in all columns

You don't need to collect the rows in a matrix because you only touch each row once, and you don't need Data.Array because you only ever process a whole row. The check at the end makes the checks in the middle functionally superfluous. mapAccumL captures the explicit recursion.

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n,m,a,b] <- map read . words <$> getLine
    mapM putStrLn $ case solve n m a of
      (colcnts, rows) | all (==b) colcnts -> "YES" : map (concatMap show) rows
      _ -> ["NO"]

solve :: Int -> Int -> Int -> ([Int], [[Int]])
solve n m a = mapAccumL go (replicate m 0) [1..n] where
  go colcnts c = (zipWith (+) row colcnts, row) where row
    = map fst $ sortOn snd $ zip (replicate a 1 ++ repeat 0)
    $ map fst $ sortOn snd $ zip [1..] colcnts

Note that your entire approach doesn't obviously find a solution if there is one. Can you prove that?

Edit: I thought you process each row at a time. Easy to mix up since the approaches are symmetric :). I choose the row-at-a-time approach, since they can be directly printed.


Using dplyr and pipes for logistic regression plotting

Here is what I would do leaning fully into the tidyverse style to get a nice "pipelined" set of steps that are easy to wrap up into functions.

Loading tidyverse just gets some extra tools from purrr here, but I find it much more productive for data manipulation in general, compared to just using dplyr alone. That said if you can only use dplyr you can replace the purrr::map() for lapply() and purrr::keep() for Filter(), but you lose a little pipe readability.

First time posting on the sub-Exchange, so feedback is welcome.

df <- read.csv("https://sciences.ucf.edu/biology/d4lab/wp-content/uploads/sites/125/2018/11/parasites.txt", header = T)

m1 <- glm(data=df, infected ~ age + weight + sex, family = "binomial") # add spaces to variables separated by arithmetic operators
link_func <- m1$family$linkinv # maybe this could become a generic function

library(tidyverse)

# anonymous functions are quick and easy to type, my preference if only one input arg
newdat_func <- . %>% # meant to start with df
  select(weight, age) %>% # keep only column of interest
  map(~ round(seq(min(.), max(.), length.out = 15))) %>% # don't repeat yourself and call the same operation on both columns in one line
  c(list(sex = c("female", "male"))) %>% # prep a 3-element list for expand.grid to process
  expand.grid()

newdat2 <- newdat_func(df)

# fall back to traditional function format for multiple inputs
x_func <- function(model, newdata, link_func) {
  predict.glm(model, newdata = newdata, type="link", se=TRUE) %>% # obviously this only works on glm objects, you could add checks to be defensive
    keep(~ length(.) == nrow(newdata)) %>% # drop the third element that is length 1
    bind_cols() %>% # build data frame with a column from each list element
    mutate(low = fit - 1.96 * se.fit,
           high = fit + 1.96 * se.fit) %>%
    mutate_all(funs(link_func)) %>% # again don't repeat yourself
    bind_cols(newdata) %>% # bolt back on simulated predictors
    mutate(category = cut(age,
                          breaks = c(0, 69, 138, 206),
                          labels = c("0-69", "70-139", "139-206")),
           age = as.factor(age))
}

x2 <- x_func(m1, newdat2, link_func)

ggplot(data = x2, aes(x = weight)) + # always use spaces around '+' and '=', do ggplot(data = data) +
  geom_line(aes(y = fit, color = age)) +
  geom_ribbon(aes(ymin = low, ymax = high, fill = age), alpha = 0.1) + # okay is all on one line (<80 chars)
  facet_grid(category ~ sex) +
  labs(x = expression(bold("Weight")), # if a function goes beyond 1 line, split its args one per row
       y = expression(bold(y = "Infection Probability")),
       linetype = "Age (months)",
       colour = "Age (months)",
       fill = "Age (months)") +
  theme(panel.grid.major = element_blank(), # split args again
        panel.grid.minor = element_blank(),
        legend.position = "right",
        strip.text.x = element_text(face = "bold", size=12),
        strip.text.y = element_text(size=10),
        axis.text.y = element_text(size=10, face = "bold"),
        axis.text.x = element_text(size=10),
        axis.title = element_text(size=12),
        legend.text = element_text(size=10),
        legend.title = element_text(size=12, face="bold"))

Minor tidy-style adjustments everywhere are adding spaces around ~/=/+ signs and only one argument per line for multiy line calls like theme() and labs(). See more here https://style.tidyverse.org/

Obviously I went the last inch and wrapped the processing steps into functions. But I developed the sequence as an open pipe chain, adding a step and printing the result to console as I progressed. The speed of that iterative/dev workflow is why I love leveraging pipes, but I think it also makes the code easier to read. Now instead of multiple intermediate variables and repeated patterns your have two code chunks/functions that handle the two distinct phases of this model plotting problem


A small custom encryption / decryption script

This is a simple variant of the caesar-cipher, namely a vigenere-cipher with the fixed key 'EH'.  Any variant of these ciphers is considered a toy-grade cipher that is trivially crackable if the attacker has gathered enough ciphertext to analyze the letter frequencies.  There is no way to make this class of ciphers secure, except to allow an insanely long and random key to be used, in which case it becomes a one-time pad.

If, despite acknowledging that it cannot be made secure, you still wanted to try to make some improvements to this code as a learning exercise, you could…

Allow the key to be specified as a parameter rather than hard-coded as alternating between +4 and +7
Eliminate the text variable
Write var ASCII = text[i].charCodeAt(0); as var unicode = message.charCodeAt(i);
Avoid repeated string concatenation with encrypted += s;;.  Since strings in JavaScript are immutable, you are actually creating a new string and copying the entire old string each time you want to append one character.  Instead, you should use Array.join():

var encrypted = new Array(message.length);
for (var i = 0; i < message.length; i++) {
    …
    encrypted[i] = …;
}
return encrypted.join('');


The type function is definitely overengineered in this case because you only need two values. The entire first snippet boils down to a simple function and the logic is instantly observable.

var req = {
    check: function(v){
        if (typeof v === "function") {
            return e();
        }
        if (typeof v === "array" || $.isArray(v)) {
            return v.every(function(e) {
                return typeof e !== "function" || e();
            });
        }
        return true;
    }
}

Note, there's no need for semicolons after closing curly braces of if, for, so if anything it shows you don't understand the automatic semicolon insertion rules.


Performance problem: Ranking with ties and skipping rows on passmark condition

First, let's confirm the intention of your query.  According to my interpretation, it ranks students according to the sum of their exam scores, best students first, but disqualifying anyone who has ever failed an exam by scoring lower than 33%.  (Why does the disqualification rule exist?  Does failing an exam allow a student to take it again?  If so, a fairer rule would be to disqualify students who have retaken an exam.)

Next, I would like to point out problems in your schema.  You included this table definition in your SQL Fiddle, which you should also have stated within the question itself (it's essential information for reviewing your code):

CREATE TABLE exam
    (`id` int, `Names` varchar(6), `Subject` varchar(8), `Exam` varchar(5), `Fullmark` int, `score` int)
;

Naming the first column id is weird and tricky: at first glance, one would expect the id column of an exam table to identify an exam, but you use it as a student ID.

That oddity is an indication of another anomaly: your schema is denormalized.  There is a M : N relationship between students and exam scores.  (Each student takes M exams; each exam is taken by N students.)  There should be three tables:

CREATE TABLE student
( id SERIAL PRIMARY KEY
, `Names` VARCHAR(6) NOT NULL  -- Probably too short
);

-- Using the long name to distinguish it from your exam table
CREATE TABLE examination
( id SERIAL PRIMARY KEY
, `Subject` VARCHAR(8) NOT NULL
, `Type` VARCHAR(5) NOT NULL
, `Fullmark` INTEGER NOT NULL
);

CREATE TABLE examination_score
( student_id INTEGER NOT NULL
, examination_id INTEGER NOT NULL
, `Score` INTEGER NOT NULL
, FOREIGN KEY (student_id) REFERENCES student (id)
, FOREIGN KEY (examination_id) REFERENCES examination (id)
);

To populate the new tables, you would use the query

INSERT INTO student
    SELECT DISTINCT `id`, `Names`
        FROM exam;

INSERT INTO examination (`Subject`, `Type`, `Fullmark`)
    SELECT DISTINCT `Subject`, `Exam`, `Fullmark`
        FROM exam
        ORDER BY `Subject`, `Exam`;

INSERT INTO examination_score
    SELECT exam.id AS student_id
         , examination.id AS examination_id
         , exam.score AS score
        FROM exam
            INNER JOIN examination
                ON examination.`Subject` = exam.`Subject`
                AND examination.`Type` = exam.`Exam`
                AND examination.`Fullmark` = exam.`Fullmark`;

Notice that you misspelled "Science" in two different ways, as well as "Mizo" (whatever that is).  The PRIMARY KEY constraint caught the misspelling of the student names "Lawma" and "Thanga".

Verify that this query works:

SELECT student_id
     , SUM(`Score`) AS TOTALSCORE
    FROM examination_score AS e
        WHERE NOT EXISTS (
            SELECT dq.student_id
                FROM examination_score AS dq
                    INNER JOIN examination
                        ON examination.id = dq.examination_id
                WHERE
                    dq.`Score` / `Fullmark` < 0.33
                    AND dq.student_id = e.student_id
        )
    GROUP BY student_id
    ORDER BY TOTALSCORE DESC;

Compare its performance against the equivalent query based on the denormalized schema:

SELECT id, Names,SUM(score) TOTALSCORE
   FROM exam e1
   WHERE NOT EXISTS(
      SELECT null FROM exam e2
      WHERE e1.id = e2.id
      AND e2.score/e2.Fullmark < 0.33
    )
   GROUP BY id
   ORDER BY TOTALSCORE DESC;

My guess is that the revised query will be faster.  The root cause is that you didn't have an index on the id column of your exam table.  You could just create the index, but normalizing the schema and writing the appropriate PRIMARY KEY constraints would implicitly create such indexes, and is better practice.


Python 3.6 introduced random.choices, which allows you to write this even more succinctly than using random.choice:

from random import choices
from string import ascii_lowercase

three_letter_words = ["".join(choices(ascii_lowercase, k=3)) for _ in range(10)]


My recommendation would be to not worry about the performance (see: http://www.kendoui.com/blogs/teamblog/posts/12-09-28/css_tip_star_selector_not_that_bad.aspx for actual tests).

If you're still not convinced that it's not as bad as everyone makes it out to be, then your only real option is to modify the contents of <random-element />.

    <random-element>
content is here
</random-element>

Which allows your CSS to be:

.img + #foo { ... }

Or just

#foo { ... }


I think you could use a one-liner like:

$zip_arr_id = floor(($zipInt/1000)/5 )*5;

which could correspond to the $zips${$zip_arr_id}_array (unsure if this is exactly right) that you're saving the org ID's to. Look into variable variables in php.

Riffing on this idea could save you a lot of lines in your code.


Retrieve and load playlists from YouTube

The freezing comes primarily from the fact that JavaScript is single-threaded so when your loop is busy-looping everything else will wait until the scope has finished before the browser can continue to poll on the event queue.

To solve this you can convert your code to asynchronous executing using setTimeout() to allow the browser to do other tasks in-between.

Another thing is that for in loops are very slow so this can be replaced by using Object keys instead.

Your parsing can be optimized by caching the current object as well as re-factor the parsing itself to a separate function method:

var keys = Object.keys(a.feed.entry),  // retrieve all keys from the object
    count = keys.length,               // number of keys to parse
    segment = 10,                      // number to parse each segment
    current;                           // counter for segment

// start loop
(function doSegment() {

    current = segment;                 // reset segment counter for each iteration

    while(current-- && count)
        parseFeedEntry(a.feed.entry[keys[--count]]);

    if (count)
        setTimeout(doSegment, 11);     // delay 11ms to allow browser to breath
})();

function parseFeedEntry(entry) {
    // parse the entry here
    var feedTitle = entry.title.$t.replace('] - ', ']'). ...8X...
    // etc., notice entry is now cached
}

Online demo

Hope this helps!


Tree list recursion from Stanford tutorial

Your solution may work great, but I see some room for improvement, especially in terms of readability and maintainability and using OO.

I quickly went over your recursive function btc, it seems to do the trick. But the code is a bit messy.

The stanford solution tries to embrace the typical list methods, like: appending elements, joining lists, etc. In fact that's the goal, right: porting a binary sorted tree to a list, so one should also provide a good list interface. They also do this in a good object oriented/modular and readable way.

A review on your coding style

To start: you miss some indentation (in your if/else clauses). This already can make it more readable!
Perhaps also document some steps in the recursion method, since recursion always results to confusion.

Methods

your method names are not that understandable, use camelCase and use appropriate, complete names, that indicate the purpose of the method.

for example:

treecre()

should be

treeCreate()

it would even be better to use a Tree class that has a create() method, which builds your test tree.

Classes

You also used a struct for your node, may I suggest to use classes, since they offer a wide set of feature that can be used for future purposes of your code: inheritance, polymorphism, etc. This is important since one might want to extend this implementation to handle nodes that contain ASCII characters instead of integers.  Or, refactor the class to use C++ templates to support generic types.

In addition I would use the standard list/binary tree names, like: root, node, .. which is easier for communication purposes.

I hope this is a bit helpful!


Just some convention points:

The indentation is off in the first couple of lines. Is this due to copy-paste? I have to assume so, as the rest of your code seems fine.
The following if statement:

if(invEstSwitch.isChecked())
{
    billType = textViewEstimate.getText().toString();
}else{
    billType = textViewInvoice.getText().toString();
}

is inconsistent. You put a newline before the beginning brace at the if, and not at the else.

It is also bad formatting. There should be a space both left and right of the else, and a space after if:

if (invEstSwitch.isChecked()) {
    billType = textViewEstimate.getText().toString();
} else {
    billType = textViewInvoice.getText().toString();
}

The if statement can be simplified into a ternary expression, as it is assigning the same thing (assuming textViewEstimate and textViewInvoice are the same type):

billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
        .getText().toString();

Try not to use ArrayList. As I said in this answer:

  It is almost always a poor option, as it is pretty much an array with
  helper functions. If you have an ArrayList of 10000 integers, and
  then add another integer, ArrayList will (if its current array it's
  storing the values in is of size 10000) create a new array, move all
  the values of the old array in the new array, then add the integer to
  the end. Sounds inefficient? Certainly does.

  My opinion is to use LinkedList. LinkedList is faster, because it
  works like this:

  Each value in the list is stored in a Node.
  Each Node points to the next Node.
  Adding something to the end is as simple as creating a new Node and linking it to the Node chain.
  Removing and inserting is as simple as changing some links around. The problem would be to find that link.

  Worst-case time complexity comparison:

        LinkedList        ArrayList
Get:       O(n)              O(1)
Add:       O(n)              O(n)
Insert:    O(n)              O(n)

  Best-case time complexity comparison:

        LinkedList        ArrayList
Get:       O(1)              O(1)
Add:       O(1)              O(1)
Insert:    O(1)              O(n) <- assuming not inserting at end of list

  Yes, LinkedList is losing, but in this case, you don't use get
  often. On the other hand, memory is an issue for ArrayList:

        LinkedList        ArrayList
Get:       O(1)              O(1)
Add:       O(1)              O(n)
Insert:    O(1)              O(n)

Your method is fairly inefficient. You create a new JSONArray each time you call the method. Instead, use the given put() method (this also means you don't need an ArrayList):

private Map<String, String> itemselected = new HashMap<>();
JSONArray itemSelectedJson = new JSONArray();

private void selectedItems() {
    billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
            .getText().toString();

    itemselected.put("custInfo",custSelected.toString());
    itemselected.put("invoiceNo", textViewInvNo.getText().toString());
    itemselected.put("barcode", barCode.getText().toString());
    itemselected.put("desc", itemDesc.getText().toString());
    itemselected.put("weight", weightLine.getText().toString());
    itemselected.put("rate", rateAmount.getText().toString());
    itemselected.put("makingAmt", makingAmount.getText().toString());
    itemselected.put("net_rate", netRate.getText().toString());
    itemselected.put("itemTotal", itemtotal.getText().toString());
    itemselected.put("vat", textViewVat.getText().toString());
    itemselected.put("sum_total", textViewSum.getText().toString());
    itemselected.put("bill_type", billType);
    itemselected.put("date", textViewCurrentDate.getText().toString());

    // Add the map to the Array
    itemSelectedJson.put(itemselected);
    index++;
}


Why is my Python web scraper taking so long?

serializing
You are serializing all HTML text and sending it back to the parent.
That can be time consuming.
Consider having the child (my_function()) write HTML text to a file in /tmp,
and pass back the temporary filename to the parent.
Better, also pass back some timestamps: (start, end, filename)
stragglers
If you can predict that a page will be "big" or a site will be "slow",
sort those to the front of your list of 500 URLs.
That way you won't have a handful of sluggish stragglers
impacting your overall time,
while most cores are idle and waiting for them to complete.


Does using a lambda make this code more DRY?

First, yes, I do think your solution with a lambda is a good choice. But it's worth to also consider other options:

Translate the closure into an object. That would mean creating a class, with a constructor that takes url (and possibly RestCall, if it's an instance property) and stores it into a filed. It also has a method that actually does the work. Basically, this is the same as you lambda, only much more code. I think this is probably not a good solution in this case.
Go the other way around: create a Dictionary<string, object> (or Tuple<string, object>[] if order is important for you; or an array of anonymous type) with your parameters and then iterate over that:

var items = new Dictionary<string, object>
{
    { "access_id", 1 },
    { "affiliate_status", "approved" }
};

foreach (var item in items)
{
    if (url.Contains("[" + item.Key + "]"))
    {
        RestCall.UriVariables.Add(item.Key, item Value);
    }
};


A couple of small suggestions.

Var:
You spend a lot of time redeclaring variable types when they are already well established by your code. For example:

decimal totalprice = 0.00m;
foreach (ShoppingCartItem item in itemList){...}
List<ShoppingCartItem> lstItems = new List<ShoppingCartItem>();

I know there can be some debate about whether var is preferred or not, but I can say I work in a shop that currently uses it heavily and it makes refactoring a dream. Just changing the Foreach to:

foreach(var item in itemList)

would make refactoring much easier later. This way it will figure out the type for you at compile time, meaning itemList can be an ienumerable of anything as would still be valid in that case.

Console.WriteLine:
There is already a string format overload for Console.Writeline. The following lines are equivalent:

Console.WriteLine(string.Format("{0} ", x));
Console.WriteLine("{0}",x);

Collection Construction:
You can use simpler syntax to construct your collection in getItemsList() making your entire signature for the function something closer to this:

    private static IEnumerable<ShoppingCartItem> getItemsList()
    {
        return new List<ShoppingCartItem>
        {
            new ShoppingCartItem
            {
                Item = new Product {Name = "Book", Price = 12.49m, Type = Product.ProductType.book, IsImport = false},
                Quantity = 1
            },
            new ShoppingCartItem
            {
                Item = new Product{Name = "music CD",Price = 14.99m,Type = Product.ProductType.other,IsImport = false},
                Quantity = 1
            },
            new ShoppingCartItem
            {
                Item = new Product{Name = "chocolate bar",Price = 0.85m,Type = Product.ProductType.food,IsImport = false},
                Quantity = 1
            }
        };
    }

Return Type List:
For what you use the return value for, in getItemsList, it doesn't need to be returned as a List. It could be an IList or IEnumerable without any ill effects. It's not a huge deal in your case as it's private, but around where I work we generally try to return collections under there interfaces. I know resharper will flag this as well.

Naming:
The enumeration ProductTypes values and the getItemsList method do not follow C# standards for naming. It really should be GetItemsList and Food/Book/Medical/Other.

IsExempt
Why is it:

return (int)Type < 4;

instead of:

return Type != ProductType.Other;

They mean the same thing, but one is a bit more obvious as to it's intentions.

Taxes Getter:
This is more of a soft suggestion, but this getter is a bit convoluted to read. I had to dig through and add some spacing to figure out what it was doing and even then I misplaced a paren the first time and got the wrong solution. I understand what you are doing with this type of code but it's honestly something that will be more of a headache than a help later as it is not immediately obvious what it is doing unless you dig in. Maybe simplifying out the ternary statements into getters for those values, or methods if you prefer, would be a better solution as it would vastly simplify the amount of parenthesis and make the statement a bit easier on the eyes. Example:

public decimal Taxes
    {
        get
        {
            return decimal.Ceiling( Item.Price *( CalculateTaxRate() + CalculateImportRate()) * 20) / 20;
        }
    }

    private decimal CalculateTaxRate()
    {
        return Item.IsExempt
            ? 0
            : TaxRate;
    }

    private decimal CalculateImportRate()
    {
        return Item.IsImport
            ? ImpTaxRate
            : 0;
    }

This seems much easier to read at a glance.

Writelines
Also worth noting that you swap between the string.format method of writing variables out to the string concatenation method in a couple of places:

Console.WriteLine(string.Format("{0} {1} : {2}", item.Quantity, item.Item.Name, (item.Item.Price + item.Taxes) * item.Quantity));
Console.WriteLine("Sales Taxes : " + salestaxes);

Best to stick with a style when you start. I prefer the string format approach, using the appropriate Console.WriteLine overload, as it hedges away from doing string + string. In this case it's really not more efficient, but it's a bad to get into the habit of string + string, as in non-trivial usages of concatenation it's inefficient. When I find yourself using string + string it's usually a tip off that there is a better way to be doing it (StringBuilder, String.Format, etc). Once again, no actual gain from this in your instance, just a good habit to build upon.

Overall:
The solution itself looks pretty good, though I'll admit I didn't run it through too much in the way of testing. I would just suggest those small style changes. Hope that helps.


JavaScript component to display ephemeral notifications

I think you could improve a lot. :)

I don't think you need an init function, it just add stuff and the code is difficult
to follow and understand.

The main function is yet your initialization.

Even the other functions are a big overhead and make the code complicated.

I put inline comment to explain the code.

function notification(notificationType, message, delay) {
  // you don't need to attach things to this, just use variables.
  const classNameSelector = 'notification';
  const disappearingClass = 'disappei'
  if ($('.'+classNameSelector).length === 0)
    return; // if component is still there you want to avoid recreate it, but
            // so don't need to load all the code, just exit at the beginning.

  // what about place in a template or in a hidden div?
  const _notification = $('

' + message +
    '

');

  $(body).append(_notification);

  // here I'm a bit confuse, you have a delay, but you set an arbitrary number
  // to remove the notification box: 1200
  // So I changed it in a way that works for me:
  const startDiappearing = delay / 3
  const disappearingAll = delay - startDiappearing

  // the first timeout is startDisappearing
  let removeTimeout;
  const disappearingTimeOut = setTimeout(function() {
    _notification.addClass('disappearing');
    removeTimeout = setTimeout(function () {
        _notification.remove();
    }, disappearingAll);
  }, startDiappearing);

  // Last but not last the bind to the click event
  _notification.on('click', function() {
    clearTimeout(disappearingTimeOut);
    clearTimeout(removeTimeout);

    _notification.remove();
  });
}

I know you feel there is some duplication of remove() but is just a lib call and just one.

The purpose here is made something simple and short as effectively simple and short, avoiding overengineering some part of code.


Improve performance for stanford-nlp in a "homemade" search engine

Most of the time is going in loading the CRFClassifier model. You want to put the model loading outside the page processing:

// assuming all needed imports are done

String model = "english.all.3class.distsim.crf.ser.gz";
AbstractSequenceClassifier<CoreLabel> classifier = CRFClassifier.getClassifier(model);
String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) "
        + "AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
String[] pages = { "https://www.example.com" };

for (String url : pages) {
  Document htmlDocument = Jsoup.connect(url).userAgent(userAgent).get();
  String text = htmlDocument.body();
  System.out.println(classifier.classifyToString(text));
}


It is hard to suggest improvements because the variable names are not very meaningful and, thus, it is hard to understand what they are for and which is the intention behind the code.
Lesson to learn: using meaningful variable names is important.

Here is an attempt.
"Opening brackets not taking a new line" is a matter of style, disregard it.

Could you address the code comments I left?

public static class Font
{
    private const string chars =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ      " + // I assume the spaces are padding to 32 chars.
        "0123456789.,!?'\"-+=/\\%()<>:;     " // 35chars?!? What is the use of the 5 spaces?
        ;
    // Since the sprites never change, you can have them as a static property.
    private static SpriteSheet _Sprites = ...;

    public static void Draw(string msg, SpriteBatch spriteBatch, int xOffset, int yOffset, Color color) {
        msg = msg.ToUpper();
        for (int x = 0; x < msg.Length; x++) {
            int spriteX = chars.IndexOf(msg[x]);
            if (spriteX < 0) {
                continue; // Skipping char.
            }
            int spriteY = 240;
            if (spriteX >= 32) {
                // I really do not understand the justification of this...
                // Drawing a 1 is supposed to get a B, right? Strange.
                spriteX -= 32;
                spriteY = 248;
            }
            Rectangle charMask = new Rectangle(xOffset + x * 8, yOffset, 8, 8);
            Rectangle spriteMask = new Rectangle(spriteX * 8, spriteY, 8, 8);
            // XNA method: http://msdn.microsoft.com/en-us/library/ff433987.aspx
            spriteBatch.Draw(Sprites.Sheet, charMask, spriteMask, color);
        }
    }
}


It's good to follow the single responsibility principle. The current method does many things that would make sense to extract to smaller helper functions, for example:

convert query string to dictionary
concert dictionary to query string
delete list of keys from dictionary
... and so on

What's the point? Next time you need something similar (and most certainly you will), you will be able to reuse the common elements easier.

And yeah, as @Quill said, the names are horrible. Some ideas:

params instead of para_dict
index instead of ii
key_value instead of tmp
url instead of pathname


Scraper to deal with some complicated site with ads

There is a room for improvement - like there always is:

avoid bare exception handling. Instead of having an except clause without specifying exception classes to handle, you can handle TimeoutException (which you even already have imported)
use with context manager when dealing with files
instead of using the find_elements_by_css_selector() method and then getting the first result - just use find_element_by_css_selector() directly
use try/finally to make sure the browser is closed in case of an unexpected exception during the web-scraping
respect PEP8 rules - specifically: spaces between arguments, order of imports
adding couple clarifying comments might help to improve readability
I think you can switch to "by id" locator for the "next" button

Improved version:

import csv

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

driver.get("https://www.inc.com/inc5000/list/2017")

# skip ad popup if present
try:
    wait.until(EC.element_to_be_clickable((By.XPATH, "//span[.='SKIP']"))).click()
except TimeoutException:
    pass

try:
    with open("inc.csv", "w", newline='') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(["Rank", "Company", "Growth", "Revenue", "Industry"])

        while True:
            for row in driver.find_elements_by_css_selector("#data-container .row"):
                rank = row.find_element_by_css_selector(".rank").text
                company = row.find_element_by_css_selector(".company a").text
                growth = row.find_element_by_css_selector(".growth").text
                revenue = row.find_element_by_css_selector(".revenue").text
                industry = row.find_element_by_css_selector(".industry").text

                writer.writerow([rank, company, growth, revenue, industry])
                print(rank, company, growth, revenue, industry)

            # next page
            try:
                wait.until(EC.element_to_be_clickable((By.ID, "arrow-r"))).click()
            except TimeoutException:
                break  # reached the end of the page
finally:
    driver.quit()


Pascal triangle produced for a particular integer K

Types
Given the description, I would assume that the return value is supposed to be int[] instead of List<Integer>....
... but, you are not using the more general List<Integer> value, but instead the ArrayList<Integer>. Always use the most general class type for your interfaces.
Also, by keeping the data as Integer values, you are doing a lot of boxing, and unboxing in the loops. Really, you should keep the calculations as Java primitives (int), and then box the results if needed.
Conditions
Your code has a special-case for row 0, where it returns [1]. By preference, I recommend not having special cases, although it is a rule I bend often.
Still, after the rowIndex == 0 special case, you then check to see whether it is rowIndex >= 1. This does not make sense because the rowIndex == 0 case returned from the function, so the other condition is useless. Well, not quite useless, it avoids an error condition for negative values. But, the negative-value condition should have been checked at the method start. Basically, it is a useless check. Consider this restructure:
if (rowIndex < 0) {
    throw new IllegalArgumentException("Nevative row");
}
if(rowIndex==0){
    toAdd.add(1);
    return toAdd;
}

toAdd = new ArrayList<Integer>();
toAdd.add(1);
toAdd.add(1);
allList.add(toAdd);
if(rowIndex==1){
    return toAdd;
}

Conclusion
I agree that the complexity is about O(n2), but I know it must be psosible to do it faster. The data types are a problem, but the result looks accurate.
Alternative...
So, I cheated, and looked at wiki, and it has a relatively easy function for calculating the row values for a function. I adapted it here. This is the way I would have done it, if I was able to google the algorithm. I would have used a similar approach to you, but as arrays-of-int instead, if I could not search the algorithm.
public static final int[] pascalRow(final int row) {
    // using same names as wikipedia:
    // http://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_a_row_or_diagonal_by_itself
    int n = row + 1;
    int[] ret = new int[n];
    int val = 1;
    final int mid = (n)/2;
    for (int k = 0; k <= mid; k++) {
        ret[k] = val;
        ret[n - 1 - k] = val;
        val = (int)(val * ((n - k - 1) / (double)(k + 1)));
    }
    return ret;
}