JavaScript Priority Queue implementation using a binary heap

Naming
The name Heap is confusing, since this is a priority queue, not a heap. The heap is merely an internal private implementation detail that should not be exposed to the outside world. Just call it what it is: a PriorityQueue.
The same applies to heap. This one is a local variable with limited scope and obvious semantics, so I would be fine with pq as a name in this case.
Conversely, the pq field actually looks like it is a heap, not a priority queue, so it should probably be named heap.
delMax sounds like the method is deleting the highest priority element, but it is actually popping the highest priority element, i.e. it is returning it. pull, poll, pop, getMax, dequeue are all popular names for this operation.
In fact, in the beginning, I thought you don't even provide this operation at all, since I was led amiss by the name. Even in your own tests, you actually ignore the return value!
Bug
Your isEmpty() method does not return anything. It is evaluating an expression and then throwing away the result. It should be something like this instead:
isEmpty() {
    return this.n === 0;
}

Testing
The above bug is actually caught be the very tests you posted in your question. That seems to indicate that you wrote those tests but are not running them, otherwise you would have noticed.
You should regularly run your tests, ideally in an automated fashion and with automated verification of the results. I run my tests automatically every time I save, every time before I commit to my local Git repository, every time locally before I push to my remote Git repository and then again on the remote repository every time someone pushes to it, every time before and after a merge, every time before a release … you get the idea. Run them as often as possible.
Potential bug?
I have the feeling, although I have not tested it, that your priority queue will not deal well if I want to store null in it.
Triple equals
There is one place where you use the Abstract Equality Comparison Operator == or its negation !=. It is generally best if you forget about its existence and never use it.
Always use the Strict Equality Comparison Operator === or its negation !== instead.
Consistency
Sometimes you use the Abstract Equality Comparison Operator and sometimes the Strict Equality Comparison Operator. Sometimes you use 4 spaces for indentation, sometimes 2. Sometimes you use the term heap and sometimes priority queue (or pq) to refer to the priority queue.
Getters
isEmpty and size should probably be getters instead of normal methods:
get size() {
    return this.n;
}

get isEmpty() {
    return this.n === 0;
}

And the tests need to change accordingly as well:
console.log(pq.isEmpty);
console.log(pq.size);

Use abstractions internally
I am a big fan of using public abstractions also internally. Not everybody agrees with this, though.
So, personally, I would use the size getter in isEmpty instead of accessing the internal n field:
get isEmpty() {
    return this.size === 0;
}

That way, if someone extends your class and overrides some parts of it with a different implementation that doesn't use an n field, isEmpty will still work unchanged.
const over let
When ECMAScript 2015 introduced let and const, the general sentiment was let is the new var, you should always use let. Personally, I disagree, and I think const should be the new var, and you should always const unless you really, really, really need to re-assign it and can't find a way around. Then, and only then, use let.
In your code, heap, max, and temp are never reassigned, so you can use const for them instead.
Class fields
n and pq should probably be class fields. Note that class fields are currently a Stage 3 proposal, which means that while it is highly likely that they will end up unchanged in the ECMAScript Language Specification, they have not been accepted yet and have definitely missed the window for the 2020 release.
class PriorityQueue {
    n = 0;
    pq = [];

    // no constructor needed, all fields already initialized
}

Private methods and fields
swim, sink, less, and exch should be private methods, they shouldn't be part of the public API, same for the class field n.
pq (or heap) should probably also be private. You are using it externally in the tests, but I don't think this is something that should be exposed to the outside world.
class PriorityQueue {
    #n = 0;
    #heap = [];

    get size() {
        return this.#n;
    }

    get isEmpty() {
        return this.size === 0;
    }

    #swim(k) {
        while (k > 1 && this.#less(Math.floor(k / 2), k)) {
            this.#exch(Math.floor(k / 2), k);
            k = Math.floor(k / 2);
        }
    }

    #sink(k) {
        while (2 * k <= this.#n) {
            let j = 2 * k;

            if (this.#heap[j + 1] !== null) {
                if (k > 1 && this.#less(j, j + 1)) {
                    j++;
                }
            }

            if (this.#heap[k] > this.#heap[j]) {
                break;
            }
            this.#exch(k, j);
            k = j;
        }
    }

    insert(v) {
        this.#heap[++this.#n] = v;
        this.#swim(this.#n);
    }

    getMax() {
        const max = this.#heap[1];
        this.#exch(1, this.#n--);
        this.#heap[this.#n + 1] = null;
        this.#sink(1);
        return max;
    }

    #less(i, j) {
        return this.#heap[i] < this.#heap[j];
    }

    #exch(i, j) {
        const temp = this.#heap[i];
        this.#heap[i] = this.#heap[j];
        this.#heap[j] = temp;
    }
}

Note that private methods are also in Stage 3.
API limitations
As currently implemented, the values stored in your priority queue and the priorities assigned to the values are actually the same thing. This is very limiting:

You cannot have an ordering of priorities that is different from the natural ordering of the values. For example, you cannot have a priority queue where the priority is based on the length of a string instead of its lexicographic ordering.
You can only store values in your priority queue that have a total ordering. Note that in ECMAScript this is trivially true, because all objects are totally ordered with respect to each other, but the ordering is not always intuitive, or do you know offhand what the result of { b: "a", a: "b" } < ["a", 2] is?

Typically, priority queue implementations resolve this in one of two ways:

Each value is associated with a numeric priority.
The priority queue is instantiated with a comparison function that expresses the total ordering relation between the values.

Solution #1 would mean that you change the signature or your insert method to something like this:
insert(v, p)

and then use p as the key for the heap.
Solution #2 would mean that you change the signature of the constructor to something like this:
constructor(f)

and then use f inside less as the comparison function instead of <.
Here is a rough sketch of what that would look like for option #1, the only changes are in insert and less:
insert(v, p) {
    this.#heap[++this.#n] = { element: v, priority: p };
    this.#swim(this.#n);
}

#less(i, j) {
    return this.#heap[i].priority < this.#heap[j].priority;
}

The usage would then look like this:
pq.insert("tally", 2);
pq.insert("plus", 1);
pq.insert("rust", 8);
pq.insert("no", 127);

The version for option #2 would look something like this:
#comparator;

constructor(f) {
    this.#comparator = f;
}

#less(i, j) {
    return this.#comparator(this.#heap[i], this.#heap[j]);
}

And the usage like this:
const pq = new PriorityQueue((a, b) => a.length < b.length);

Further API additions
Being a collection, your priority queue should implement the Iterable interface.
All major data structures in the ECMAScript standard library have methods entries, keys, and values. It makes sense to conform to that interface as well.


Interesting question,

it is of course not good to fill up memory with copies of pictures. Especially with this scandal in recent memory where deleted pictures haunt users.

It seems from reading your code that you take a copy of the file whether or not you have the extension and MIME type. At least only copy if you see no other way.

Furthermore, from the documentation ( and I could be wrong ), the FileEntry object has a method called file which creates a File Object which has a type property which is the mime type of the file. Could this solve your conundrum ? If that does not work, you should see if you can file a bug.

From a real code review perspective, this is my quick once over:

Respect for dealing with this immature API
JsHint has nothing on this, except for 1 missing semicolon
Have you considered using 'use strict' ?
The multi-line comments definitely stop the reading flow, but removing them would reduce the value of your commenting. I wonder if those multi-liners can be part a narrative on top of your function..
You are at the limit of having to break things up into helper functions, as per this arrow half:

                            });
                        }, fail);
                    }, fail);
                }, fail);
            } else {
                resolve(false);
            }
        });
    }, 0);

}, function (fail_message) {


Since the two queries don't depend on each other,
and they both return the same column,
it seems you can UNION them.

I cannot test this, but it seems this should work:

  def searching(term: String): List[String] = {
    DB.withConnection { implicit c =>
      val result = SQL(
        "SELECT body FROM tableName WHERE body like {liketerm} limit 0,14 " +
        "UNION " +
        "SELECT body FROM tableName WHERE " +
        "MATCH (body) AGAINST ({term} IN BOOLEAN MODE) limit 0,14 ").on(
          "liketerm" -> ("%" + term + "%"),
          "term" -> term
        )()
      result.map(row => row[String]("body")).distinct
    }
  }

Not only this is simpler,
running one query instead of two is more efficient.


Checking in four directions for board game win

Nice question! This is a little trickier than the usual “clean up a string of Maybes” in that you want short-circuiting on the Just case, and continued computation on Nothing. There is—of course—a function for that. Skip to the bottom for the answer, or read through for how you might find or derive it.

Finding the Answer

Hoogle. Pretty much always Hoogle. Think about what you've got and what you need, then start testing types against Hoogle. In this case you've got a sequence of Maybe a values that you want to reduce to a single value. The key insight is that the sequence must all be of the same Maybe a type, so it's possible (and thus probably necessary) to create a list (an actual [Maybe a]) of them. Thus our candidate type signature—

? :: [Maybe a] -> Maybe a

Pop that type signature into Hoogle and the very first thing that comes up is—

-- "base" Control.Monad
-- | This generalizes the list-based concat function.
msum :: MonadPlus m => [m a] -> m a

Test it in GHCi and—

> msum [Nothing, Just 1, Just 2]
Just 1
> msum [Just 1, Nothing, Just 2]
Just 1
> msum [Nothing] :: Maybe Int
Nothing

Yep, that's what we want.

Deriving the Answer

There are probably two different ways you might come up with your own solution. Either start at the concrete and generalize, or cobble a solution from typeclasses down.

From the Concrete

Consider again the type of the function you need.

? :: [Maybe a] -> Maybe a

A no-frills solution to this with primitive recursion and pattern matching should be self-obvious (or will be with experience).

firstJust :: [Maybe a] -> Maybe a
firstJust []             = Nothing
firstJust (Nothing:ms)   = firstJust ms
firstJust (j@(Just _):_) = j

From there we can deploy our usual bag of tricks higher-order functions to write this more idiomatically.

firstJust :: [Maybe a] -> Maybe a
firstJust = foldr orElse Nothing
    where
        orElse :: Maybe a -> Maybe a -> Maybe a
        orElse Nothing    m = m
        orElse j@(Just _) _ = j

Now a few facts may percolate to the top of your brain and strike you as insight.

Maybe encapsulates a notion of “failure”.
orElse provides an alternative value in the case of failure.
Alternative is a typeclass that exists.

So we get a spiffy one-liner—

firstJust :: [Maybe a] -> Maybe a
firstJust = foldr (<|>) Nothing

From the Typeclass Down

This all depends on which tools you're most familiar with. If you're a Monoid fan and used to relying on newtypes you may recognize the pattern of condensing a list of values as Control.Monoid.mconcat. Then you just need to write or choose an appropriate Monoid instance, and of course if you're really on top of the ball you'll know that one already exists.

import Control.Monoid
import Data.Coerce (coerce) -- GHC 7.8.1

firstJust :: [Maybe a] -> Maybe a
firstJust = getFirst . mconcat . coerce
-- Compatible with older GHC but slower, `getFirst . mconcat . map First`

Just the Answer

This version relies on MonadPlus, which ties up all of the other concepts we used and provides various handy functions to leverage their combined power. This version is as terse as it's gonna get.

import Control.Monad (msum) -- Or, Control.Applicative.asum

checkWon :: Board -> Maybe col
checkWon board = msum [ east moves col n
                      , west moves col n
                      , north moves col n
                      , south moves col n
                      ]
    where
        moves = pieces board
        n     = target board
        col   = snd (moves !! 0)


Executing multiple async methods synchronously without throwing

After my initial answer and based on your subsequent comments, I would say that your implementation is OK.

As for naming I would keep it simple like WhenAllCompleted

/// <summary>
/// Creates a task that will complete when all of the supplied tasks have completed synchronously.
/// </summary>
/// <param name="tasks">The tasks to wait on for completion.</param>
/// <returns>A task that represents the completion of all of the supplied tasks.</returns>
public static async Task WhenAllCompleted(this IEnumerable<Func<Task>> tasks) {
    if (tasks == null) throw new ArgumentNullException("tasks");
    var exceptions = new List<Exception>();
    using (var e = tasks.GetEnumerator()) {
        while (e.MoveNext()) {
            var task = e.Current;
            try {
                await task();
            } catch (Exception ex) {
                exceptions.Add(ex);
            }
        }
    }
    if (exceptions.Any()) {
        throw new AggregateException(exceptions);
    }
}

I've basically only added the null check on the provided argument. I considered doing null checks on the function and task returned like

var function = e.Current;
if (function == null) {
    exceptions.Add(new ArgumentException("The tasks collection contained a null task.", "tasks"));
    continue;
}
//...

but figured that would all be caught by your simpler implementation, so decided against it.

Though you have not added cancellation as yet the following should be of some help with an optional cancellation token

/// <summary>
/// Creates a task that will complete when all of the supplied tasks have completed synchronously.
/// </summary>
/// <param name="tasks">The tasks to wait on for completion.</param>
/// <returns>A task that represents the completion of all of the supplied tasks.</returns>
public static async Task WhenAllCompleted(this IEnumerable<Func<Task>> tasks, CancellationToken token = default(CancellationToken)) {
    if (tasks == null) throw new ArgumentNullException("tasks");
    var exceptions = new List<Exception>();
    using (var e = tasks.GetEnumerator()) {
        while (e.MoveNext()) {
            if (token.IsCancellationRequested) {
                exceptions.Add(new OperationCanceledException("tasks collection was cancelled", token));
                break;
            }
            try {
                await e.Current();
            } catch (Exception ex) {
                exceptions.Add(ex);
            }
        }
    }
    if (exceptions.Any()) {
        throw new AggregateException(exceptions);
    }
}


Starting a new transaction inside a single bean

Variable Names:
Your variable names are very generic. The List<Object> you pass in is just called list. This might be fine at coding-time, but as soon as you have to analyze the code weeks or maybe even months later, you will probably wonder, what purpose that list serves.
I'd thus propose you change the variable name a bit. Something like listForPersisting or something should be fine ;) The same may apply to your UserTransaction and the SessionContext, but as they are defined enough by their typename, that shouldn't be a big problem.
Spacing / Comments
I realy like your spacing. Your code is speaking enough, that you can leave out comments and still you understand it on first reading.
That's very good, keep it up!
Approach
I don't think you can solve your specific problem in many other ways as elegantly as you did.
What I do not like about your code is that you needlessly create the interface ManagerInternal  as if you needed a function to override.
You name that interface "Internal" and go through the hassle of making it @Local. But then you do something totally incomprehensive. You expose the overriden method.
If you don't need the method anywhere else, the principle of information hiding applies.

In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed. The protection involves providing a stable interface which protects the remainder of the program from the implementation (the details that are most likely to change).
Written another way, information hiding is the ability to prevent certain aspects of a class or software component from being accessible to its clients, using either programming language features (like private variables) or an explicit exporting policy.


Okay, so there are a lot of problems here. I think the best way to address them is in stages. I want to show you how to go through your own code critically and address problems in it as you write.
Before I begin, for the benefit of someone who will review your code, it is helpful to include all the imports you used so that the person doing the review can just copy your code into their environment and run it if they need to.
So a good first inclusion would be:
import numpy as np
My first stylistic point is that you really should conform to PEP8, it creates a standard that all Python programmers should follow and while some of its requirements can be a bit frustrating at times it is, for the most part, a very good style guideline.
def count_neighbours(point, mask, n):
    # Create the square around this point and count the number of neighbors.
    # Change 1: changed name from 'neighbour' to 'count neighbours'.
    #     It is often helpful to have expressive names for functions and
    #     variables. Since functions DO something I find verb-object phrases
    #     very intuitive when I'm not working on a project where function
    #     names are standardised. Someone looking at your code can ask
    #     "what does this function do?", answer: oh it "counts neighbours".
    # Change 2: fixed spacing in arguments. Look into PEP8 and a linter that
    #     will tell you when you place spaces in poor or unconventional
    #     locations.
    mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1] + int(n/2) + 1]
    return n**2 - np.count_nonzero(mask)
    # Change 3: made indent of count_neighbours function a multiple of four.
    #     Again, please follow PEP8 guidelines.

All my present changes are simply style related, now lets talk about this... thing:
mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1]
There's no way around the fact that this is quite ungainly. What can we do about it? The biggest problem, aesthetics aside, is that at first glance I have no idea what it's actually supposed to do. Here I approve very much that you added a comment to give some explantion as to what this function does, that comment is the only thing that made figuring out the intention easier.
Python actually attaches a string encountered directly after a function defintion as a docstring for that function. You can find style guidelines for writing doctrings here. Let's make that comment more explicit and put it in a docstring.
def count_neighbours(point, mask, n):
    """
    Count the neighbours of a point, where neighbours are other points in
    mask that are within a square of side length n, centered on point.

    If a copy of point appears in mask it is counted as a neighbour.

    Arguments:
    point -- the point on which the square will be centered.
    mask -- the set of points to check.
    n -- the side length of the square.
    """
    mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1] + int(n/2) + 1]
    return n**2 - np.count_nonzero(mask)

Here I have guessed at what is supposed to be contained in mask and written it in the docstring. I have made this assumption based on what the function is supposed to do, but based on the call in your other function: neighbour(contour[i], mask, n) where you have said that contour is in fact your list of points I suspect there may be some confusion at the variable naming stage.
I am going to give mask the revised name all_points in order to make it clearer what the argument is, and update the docstring accordingly. Now, we've finally arrived back at this
all_points = all_points[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1].
How can I make this easier to follow? One obvious idea is that, since we seem to be concerned with a plane we can name some variables of interest:
px = point[0]  # x-value (first coordinate) of the point p
py = point[1]  # y-value (second coordinate) of the point p
offset = n/2  # half of square side length

And now finally, after some cleaning up, we actually realise that there is a deeper problem here: the confusion expression was not only poorly written, but logically flawed! Why are we slicing using the nearest integer to the boundaries of the square as indicies? This makes no sense. We are interested in comparing the bounds px-offset and px+offset to the contents of all_points, not to the indicies of all_points.
So, what we really want to know which points in all_points satisfy these inequalities:
neighbours_x = all_points[:, 0] >= px-offset
# is a point >= the lower bound in x?
neighbours_x &= all_points[:, 0] <= px+offset
# is a point <= the upper bound in x?
neighbours_y = all_points[:, 1] >= py-offset  # lower bound in y
neighbours_y &= all_points[:, 1] <= py+offset  # upper bound in y
neighbours = neighbours_x & neighbours_y  # neighbours in both axes

Go through each step of this process and print the output at each step using the example given at the end and see what each step does.
Finally we want to return the number of neighbours. Both of the below expressions work. The former is faster, but the latter might give you more intuition about what we're doing:
return neighbours.sum()
return all_points[neighbours].shape[0]

I also recommend you print all_points[neighbours] and see what the output is, again using the example at the end.
import numpy as np
from itertools import product

def count_neighbours(point, all_points, n):
    """
    Count the neighbours of a point, where neighbours are other points in
    all_points that are within a square of side length n, centered on point.

    Arguments:
    point -- the point on which the square will be centered.
    all_points -- the set of points to check.
    n -- the side length of the square.
    """
    px = point[0]  # x-value (first coordinate) of the point p
    py = point[1]  # y-value (second coordinate) of the point p
    offset = n/2  # half of square side length
    neighbours_x = all_points[:, 0] >= px-offset
    # is a point >= the lower bound in x?
    neighbours_x &= (all_points[:, 0] <= px+offset)
    # is a point <= the upper bound in x?
    neighbours_y = all_points[:, 1] >= py-offset  # lower bound in y
    neighbours_y &= all_points[:, 1] <= py+offset  # upper bound in y
    neighbours = neighbours_x & neighbours_y  # neighbours in both axes

    return neighbours.sum()

# example 1
X = np.array(list(product([-2,-1,0,1,2], [-2,-1,0,1,2])))
count_neighbours(X[0], X, 2)

# example 2
X = np.array(list(product([-2.1,-1,0.3,1.7,2], [-2.2,-1.8,0.1,1,2])))
count_neighbours(X[0], X, 4.7)

I hope this helps you identify logical errors in future. I think you should be able to review and refactor the other function on your own. Feel free to edit your question with the updated version later if you still want a second opinion one it is clearer what the function is doing and then we can address performance issues.


Google Kickstart Round A 2019 - Training

First of all, this looks good to me! I have some minor comments.

General comments

Consider compiling with -Wconversion. It will give you a couple of hints where you implicitly convert between std::vector::size_type (usually std::size_t) and int. Whether you work with unsigned data types for skills and quantities might be a matter of taste, but I think you should be aware of the conversion issue. Also, this compiler flags gives you (on my machine)

  implicit conversion loses integer precision: unsigned long to int [-Wshorten-64-to-32]

int remainingPossibilities = skills.size() - p;

which should definitely worth tackling even if the problem description specifies input characteristics that make a digit loss impossible.
Not that this will be an issue for this example, but when you want to be as fast as possible, don't use <iostream>, but <cstdio> instead.

Input handling/parameter types

When retrieving the input data, don't pass non-const references, but prefer returning by value instead. (N)RVO will make sure there is no overhead. As you have more than one value, define a small, custom type for this. So, I'd suggest going with

struct TestCaseInput {
   int nToChoose;
   std::vector<int> skills;
};

TestCaseInput getData();
int minTrainingTime(TestCaseInput& input);

cf. the Core Guidelines on this topic, F.20 and F.21
std::vector::emplace_back makes sense when you can in-place construct an object with given parameters, but when you pass the already existing object to this function, it's probably clearer to use push_back. In the case of an integral value, it doesn't matter anyhow whether you move-construct or copy it. As an alternative, you could also

std::vector<int> skills(n); // Allocates and set all values to zero

for (int i = 0; i < n; i++)
    std::cin >> skills[i]; // No temporary variable required

And also have a look at the combination of std::copy_n and std::istream_iterator that @papagaga suggests to eliminate the manual loop here.

Main function minTrainingTime

In the first loop, you read skills[high] in every iteration, even though this value doesn't change. Instead, just read it once and save it in a variable. Or, leave it as it is and verify that the compiler optimizes this away anyway.
You can also replace this whole first loop by including <numeric> and using std::accumulate with an initial value high*skills[high] and std::minus<>{} as the binary operation parameter.
If you can const-qualify a variable, do so:

const int remainingPossibilities = skills.size() - p;

But if can alternative reduce the scope of such a variable and by that even eliminate another one (the loop counter i), do so instead (as long as the negative influence on the readability is not too big, which I think is ok here):

// remainingPossibilities is now superfluous, just use the for loop for
// the initialization and count differently:
for (int n = skills.size() - p; n != 0; n--) { /* ... */ }

You might want to consider an additional level of indirection for the function minTrainingTime here, as it can equally well operate on random access iterators instead of indices. This way, you eliminate the dependency of this function on the actual value type that you are using (which also considerably reduces the number of -Wconversion warnings at one go), as well as the dependency on the container type. Using some of the above hints, the resulting function template looks e.g. like this:

template <class RandomAccesIt, class T>
auto minTrainingTime(RandomAccesIt first, RandomAccesIt last, T p)
{
    using value_type = typename RandomAccesIt::value_type;
    auto low = first, high = std::next(first, p - 1);
    const value_type init = std::distance(low, high)*(*high);

    value_type currentResult = std::accumulate(first, high, init, std::minus<>{});
    value_type minResult = currentResult;

    for (auto n = std::distance(first, std::prev(last, p)); n != 0; --n) {
        currentResult -= *++high - *low++;
        currentResult += p*(*high - *std::prev(high));
        minResult = std::min(minResult, currentResult);
    }

    return minResult;
}

and can be deduced and invoked by minTrainingTime(skills.begin(), skills.end(), p).


Formatting

I think your query could really use some white space to make it easier to read. I realize there is no official standard for SQL, but here is my preferred style:

SELECT
    "odds_odds"."id",
    "odds_odds"."offer_id",
    "odds_odds"."time",
    "odds_odds"."o1",
    "odds_odds"."o2",
    "odds_odds"."o3",
    "odds_odds"."o4",
    MAX(T3."time") AS "max_time"
FROM "odds_odds"
    LEFT OUTER JOIN "odds_offer"
        ON ( "odds_odds"."offer_id" = "odds_offer"."id" )
    LEFT OUTER JOIN "odds_odds" T3
        ON ( "odds_offer"."id" = T3."offer_id" )
GROUP BY
    "odds_odds"."id",
    "odds_odds"."offer_id",
    "odds_odds"."time",
    "odds_odds"."o1",
    "odds_odds"."o2",
    "odds_odds"."o3",
    "odds_odds"."o4"
HAVING "odds_odds"."time" =  MAX(T3."time");

Table aliases

A table named "odds_odds" seems odd to me, but you could save some typing by aliasing as odds at least. Also not sure why you are using quotation marks everywhere, but maybe it's a requirement for your system. I have a Postgres database and never needed those, so it just feels like noise.

Simplifying

You said:

  For each offer I want the latest Odds (ORDER BY time).

What I see your code doing is what seems like unnecessary computation to find MAX(), where you likely could entirely remove your aggregation and write something along those lines:

SELECT
    "odds_odds"."id",
    "odds_odds"."offer_id",
    "odds_odds"."time",
    "odds_odds"."o1",
    "odds_odds"."o2",
    "odds_odds"."o3",
    "odds_odds"."o4",
    T3."time" AS "max_time"
FROM "odds_odds"
    LEFT OUTER JOIN "odds_offer"
        ON ( "odds_odds"."offer_id" = "odds_offer"."id" )
    LEFT OUTER JOIN "odds_odds" T3
        ON ( "odds_offer"."id" = T3."offer_id" )
ORDER BY "odds_odds"."time" DESC
LIMIT 1; -- or however many you need


You're trying to create a so called hybrid cryptosystem or hybrid encryption method (crypto is not just considered encryption anymore, after all).

The problem with CBC mode is that it is very vulnerable to padding oracle attacks. It is itself not authenticated, which means that you can change any data within the ciphertext and thereby change plaintext blocks. Using GCM mode is recommended.

Adding a digital signature over the message is recommended if you want to know who send the message to you. Currently your code is only valid for providing confidentiality for locally stored data (data "at rest" in the jargon).

The whole idea of hybrid encryption is to send the encrypted AES key as part of the ciphertext. Since the size of the encrypted AES key is always the same size as the key size of the RSA key pair in bytes, it can simply be prefixed to the AES ciphertext.

Of course, you'd need to split the resulting ciphertext message in two again to be able to decrypt it. Note that the Java API misses a method to retrieve the RSA key size. This is however OK because you can retrieve the modulus size by using ((RSAPrivateKey)RSA_KEYS.getPrivate()).getModulus().bitLength() in your code. This is - by definition - the same as the key size in bits.

Your code is clearly not keeping to any conventions when it comes to capitalization. This is however already mentioned in the other answer, so I don't see any reason to repeat it here.

So lets make a list of what's wrong:

first of all, the RSA key pair is the static key pair. That means that it should be pre-generated, and the public key must be distributed and trusted in advance. If the RSA and data specific AES key are generated in the same method (in this case the constructor), then something is seriously wrong.
Cipher instances carry state, and should preferably not be stored in fields. Storing static keys such as the RSA key pair is OK, but otherwise everything should just be created within the various methods. Cipher instances are relatively lightweight, so constructing / deconstructing them is relatively efficient (certainly compared against their operation). All in all, only the key pair field makes some sense; all the rest is unnecessary state.
The RSA key size of 2048 has about the same security as a 112 bit cipher such as 3DES. That's lower than AES-128 and much lower than AES-256. I'd use at least a 3072 bit key and prefer a 4096 bit key. Above that Elliptic Curve cryptography (ECIES) starts to make more sense (or a post-quantum algorithm).
SecureRandom.getSeed(16) retrieves data that can be used to seed a random number generator. Using a truly random IV is (more or less) required for CBC mode, but it is actually more secure and more performant to use SecureRandom#nextBytes.

Other smaller notes:

the name of the class: "Cryptographer" is of course horrible and it doesn't explain what the class does. This class does not represent a person.
It's "necessary" not "necesary". The shouting makes such spelling mistakes all the worse.

All in all, nice as a first try, don't use in production.


Refactor multiple condition statements in map function

Use ES2017 object spread:

const uploadedFiles = images.map((item, index) => {
  const props = {
    key: index,
    src: item.blobUrl,
    onClose: this.props.removeImage,
  };

  const isSingleGif = images.length === 1 && /\.gif$/i.test(item.file.name);
  if (isSingleGif) {
    return (<ImageGif {...props} />);
  }

  const isLastOfVisible = index === MAX_SIZE - 1 && index > 0;
  return (<ImageContainer
    id={index}
    {...props}
    {...isLastOfVisible && {hiddenImages}}
  />);
});

Not tested.

Notes:

images.length < 2 was misleading and confusing. The .map callback runs only when there are some elements so 0 is not possible. Simply compare with 1.
images.length >= 2 is superfluous and thus confusing: the previous check ensured this is always the case.
MAX_SIZE === index + 1 this yoda style obfuscates the actual goal, which is to determine whether the element is the last in the range.
MAX_SIZE !== index + 1 is superfluous and thus confusing: the previous check ensured this is always the case.
/.(gif)$/i incorrectly allowed any character before gif. The dot should be escaped. Also, no need for the slower .match if you don't use the captured strings. Use .test


Shorter way to write multiple if-then-else-if

Simon has already answered while I was writing something similar:

foreach(array('best', 'average', 'bad') as $rank) {
  if($row[$rank]) {
    $id = $row[$rank];
    break;
  }
}

Note however, that in both this and Simon's answer, there is a possibility of $id never being assigned a value. Konijn's answer avoids that (although $id might still end up false'y)


I would not put the results in the same table.  I would make a new table and put the results in the new table.  The new table can use the same surrogate keys as the original.  It is a basic principle in database design that you never work on live data when doing development.  I also like inputs and outputs to be separate.  Sometimes you can damage the data subtly and if you have changed the input data rather than create a separate output table, these changes can be harder to detect and remedy.

Other than that the code looks fine.


Better Alternative For Storing Multiple Booleans?

I would suggest that you use a Dictionary, with the property as the key and the bool as the value. e.g.

Dictionary<string, bool?> myProperties = new Dictionary<string, bool?>();

Use reflection to get all the properties from your object. Then you dont have any work when properties gets added/removed.

You can initialise your dictionary with reflection like this:

foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties()) {
    myProperties.Add(propertyInfo.Name, false);
}

Or you can even only add those that are not null.


Sanitizing words extracted from text files and writing them to a database

Memory usage

What I notice most, is that this is bound to use a lot of memory.

First you load all the files (at once) into memory.

Then you copy over (with modifications) the data into another variable. And another. And another. ...

This creates a few lists, all with the same total memory size as the entire documents you have read.

Ex-pen-sive.

Generators/Iterators to the rescue!

In Python, iterators are really nice. They allow something like continuations and just-in-time calculation. This causes memory usage to be a lot lower, on the (perhaps) extra cost of a bit more CPU processing. But... I think in this case it will overall be a saving because you have a lot less memory usage, so probably also less cache-misses.

Let's see what we can do about that.

The last step

nrfinal = []
for j in nr:
    rem = 0
    outr = ''
    for i in j:
        if ord(i)>= 48 and ord(i)<=57:
            rem += 1
            if rem == 1:
                outr = outr+ '#'
        else:
             rem = 0
             outr = outr+i
    nrfinal.append(outr)

The easiest step is to first make it a function.

def calc_nrfinal(inp):
    retval = []
    for j in nr:
        rem = 0
        outr = ''
        for i in j:
            if ord(i)>= 48 and ord(i)<=57:
                rem += 1
                if rem == 1:
                    outr = outr+ '#'
            else:
                 rem = 0
                 outr = outr+i
        retval.append(outr)
    return retval
nrfinal = calc_nrfinal(nr)

Now this does not save us memory. But by rewriting it a little bit, it will become a generator.

def calc_nrfinal(inp):
    for j in nr:
        rem = 0
        outr = ''
        for i in j:
            if ord(i)>= 48 and ord(i)<=57:
                rem += 1
                if rem == 1:
                    outr = outr+ '#'
            else:
                 rem = 0
                 outr = outr+i
        yield outr
nrfinal = calc_nrfinal(nr)

The downside is that you can only iterate over nrfinal once, but you only need to do it once.

The inner loop

One thing that bothers me is the inner loop here. ord(i)>=49 and ord(i)<=57) could be written as 49 <= ord(i) <= 57 (one of Pythons strengths!). But... I'd rather write

outr = re.sub(r'[0-9]+', '#', j)

Giving us

def calc_nrfinal(inp):
    for j in nr:
        yield re.sub(r'[0-9]+', '#', j)
nrfinal = calc_nrfinal(nr)

But now, the whole generator-function is a bit annoying, and I'd like to switch to ... (drumroll)

Generator comprehensions

Defining lots of separate generator functions can be really annoying, especially when the body of the generator is quite small. There's a solution for that: generator comprehensions.

def f(iterable):
    for val in iterable:
        yield g(val)
k = f()

Can be rewritten as

k = (g(val) for val in iterable)

It even supports multiple fors and ifs inside the loops.

Anyway, I disgres. What I mean is:

nrfinal = (re.sub(r'[0-9]+', '#', j) for j in nr)

And, nrfinal will take almost no memory at all, because all the values are evaluated just-in-time. The downside is you can not iterate twice (because it is not stored).

Continuing in similar fashion:

Here I did the same for a couple of the pieces.

# -*- coding: utf-8 -*-
from __future__ import print_function
import os, codecs, re, string, mysql
import mysql.connector

'''Reading files with txt extension'''
y_ = ""
for root, dirs, files in os.walk("/Users/Documents/source-document/part1"):
    for file in files:
        if file.endswith(".txt"):
            x_ = codecs.open(os.path.join(root,file),"r", "utf-8-sig")
            for lines in x_.readlines():
                y_ = y_ + lines
#print(tokenized_docs)

'''Tokenizing sentences of the text files'''

from nltk.tokenize import sent_tokenize
raw_docs = sent_tokenize(y_)

tokenized_docs = [sent_tokenize(y_) for sent in raw_docs]

'''Removing stop words'''

stopword_removed_sentences = []
from nltk.corpus import stopwords
stopset = stopwords.words("English")
for i in tokenized_docs[0]:
    tokenized_docs = ' '.join([word for word in i.split() if word not in stopset])
    stopword_removed_sentences.append(tokenized_docs)

''' Removing punctuation marks'''

regex = re.compile('[%s]' % re.escape(string.punctuation))
nw = []
for review in stopword_removed_sentences:
    new_review = ''
    for token in review:
        new_token = regex.sub(u'', token)
        if not new_token == u'':
            new_review += new_token
    nw.append(new_review)

lw = (i.lower() for i in nw)
nr = (re.sub(r'[^\[\]]+(?=\])', '#', j) for j in lw)
nrfinal = (re.sub('[0-9]+', '#', j) for j in nr)
'''Inserting into database'''
def connect():
    for j in nrfinal:
        conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
        cursor = conn.cursor()
        cursor.execute("""INSERT INTO splitted_sentences(sentence_id, splitted_sentences) VALUES(%s, %s)""",(cursor.lastrowid,j))
        conn.commit()
        conn.close()
if __name__ == '__main__':
    connect()

Unnecessary looping

Here I got a bit lost, due to the double loop in nw and new_review... For this, I first need to understand the contents of stopword_removed_sentences. Let's look a few lines up:

stopword_removed_sentences = []
from nltk.corpus import stopwords
stopset = stopwords.words("English")
for i in tokenized_docs[0]:
    tokenized_docs = ' '.join([word for word in i.split() if word not in stopset])
    stopword_removed_sentences.append(tokenized_docs)

What this tells me:

stopwords_removed_sentences is a list.
The value of each of the lists is a string (' '.join(...) must be a list).

Ok, for now I know enough. This tells me:

review is a string.
token is a 1-character substring of review.

Looking back to the troublesome code:

regex = re.compile('[%s]' % re.escape(string.punctuation))
nw = []
for review in stopword_removed_sentences:
    new_review = ''
    for token in review:
        new_token = regex.sub(u'', token)
        if not new_token == u'':
            new_review += new_token
    nw.append(new_review)

This means we call regex.sub for all characters of review.

I have three different solutions:

new_review = regex.sub(u'', review)

Which reads very nice! Or

new_review = ''.join(token for token in review if token in string.punctuation)

Which is probably a bit more expensive due to the looping in Python (instead of C). Or,

new_review = review.translate(None, string.punctuation)

Which also saves us pre-compiling a regex. More readable, I think. Any are fine, but I think the review.translate is the easiest to look at.

Using that:

# -*- coding: utf-8 -*-
from __future__ import print_function
import os, codecs, re, string, mysql
import mysql.connector

'''Reading files with txt extension'''
y_ = ""
for root, dirs, files in os.walk("/Users/Documents/source-document/part1"):
    for file in files:
        if file.endswith(".txt"):
            x_ = codecs.open(os.path.join(root,file),"r", "utf-8-sig")
            for lines in x_.readlines():
                y_ = y_ + lines
#print(tokenized_docs)

'''Tokenizing sentences of the text files'''

from nltk.tokenize import sent_tokenize
raw_docs = sent_tokenize(y_)

tokenized_docs = [sent_tokenize(y_) for sent in raw_docs]

'''Removing stop words'''

stopword_removed_sentences = []
from nltk.corpus import stopwords
stopset = stopwords.words("English")
for i in tokenized_docs[0]:
    tokenized_docs = ' '.join([word for word in i.split() if word not in stopset])
    stopword_removed_sentences.append(tokenized_docs)

nw = (j.translate(None, string.punctuation) for j in stopword_removed_sentences)
lw = (i.lower() for i in nw)
nr = (re.sub(r'[^\[\]]+(?=\])', '#', j) for j in lw)
nrfinal = (re.sub('[0-9]+', '#', j) for j in nr)
'''Inserting into database'''
def connect():
    for j in nrfinal:
        conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
        cursor = conn.cursor()
        cursor.execute("""INSERT INTO splitted_sentences(sentence_id, splitted_sentences) VALUES(%s, %s)""",(cursor.lastrowid,j))
        conn.commit()
        conn.close()
if __name__ == '__main__':
    connect()

Quadratic run-time in the number of sentences.

Look at this code:

raw_docs = sent_tokenize(y_)

tokenized_docs = [sent_tokenize(y_) for sent in raw_docs]

First, you get the sentences from y_. Then, you again get the sentences from y_, but as many times as there are sentences in y_. Then, you only use the first item from the second set.

raw_docs = sent_tokenize(y_)

tokenized_docs = [sent_tokenize(y_) for sent in raw_docs]

'''Removing stop words'''

stopword_removed_sentences = []
from nltk.corpus import stopwords
stopset = stopwords.words("English")
for i in tokenized_docs[0]:
    tokenized_docs = ' '.join([word for word in i.split() if word not in stopset])
    stopword_removed_sentences.append(tokenized_docs)

Becomes

raw_docs = sent_tokenize(y_)

tokenized_docs = [sent_tokenize(y_) for sent in raw_docs]

'''Removing stop words'''

stopword_removed_sentences = []
from nltk.corpus import stopwords
stopset = stopwords.words("English")
for i in raw_docs:
    tokenized_docs = ' '.join([word for word in i.split() if word not in stopset])
    stopword_removed_sentences.append(tokenized_docs)

And now switch to generators again.

But, we also want generators

raw_docs = sent_tokenize(y_)
stopword_removed_sentences = (' '.join(word for word in i.split() if word not in stopset) for i in raw_docs)

Now this becomes a bit bulky, though. The inner text is quite long. Let's make that a function.

def strip_stopwords(sentence):
    return ' '.join(word for word in sentence.split() if word not in stopset)

stopword_removed_sentences = (strip_stopwords(sentence) for sentence in raw_docs)

Recognizing a pattern.

Now, we end up with

...
stopword_removed_sentences = (strip_stopwords(sentence) for sentence in raw_docs)
nw = (j.translate(None, string.punctuation) for j in stopword_removed_sentences)
lw = (i.lower() for i in nw)
nr = (re.sub(r'[^\[\]]+(?=\])', '#', j) for j in lw)
nrfinal = (re.sub('[0-9]+', '#', j) for j in nr)
...

Let's see if we can make that more readable...

actions = [
    strip_stopwords,
    lambda sentence: sentence.translate(None, string.punctuation),
    str.lower,
    lambda blob: re.sub(r'[^\[\]]+(?=\])', '#', blob),
    lambda blob: re.sub(r'[0-9]+', '#', blob),
]

def apply_all_actions(val):
    for action in actions:
        val = action(val)
    return action

nrfinal = (apply_all_actions(val) for val in raw_docs)

(Here we abuse the fact that str.lower is the same as lambda f: f.lower() if it is certain that f is a string.)

Now it is really clear that nrfinal is constructed from raw_docs by a sequence of simple transformations on the elements. If you want, you can define functions for all of the separate actions, given

actions = [
    strip_stopwords,
    remove_punctuation,
    lowercase,
    (some magic name, I don't know what),
    squash_numbers_to_hash,
]

But, this is a matter of choice.

Connection management.

Now, for something completely different.

def connect():
    for j in nrfinal:
        conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
        cursor = conn.cursor()
        cursor.execute("""INSERT INTO splitted_sentences(sentence_id, splitted_sentences) VALUES(%s, %s)""",(cursor.lastrowid,j))
        conn.commit()
        conn.close()

Let's read what this does:

for every sentence in nrfinal, do the following:
** Create a connection to a mysql host.
** Create a cursor.
** Insert a value.
** Commit the connection.
** Close the connection.

Connecting is expensive. Why not do that outside the loop?

def connect():
    conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
    for j in nrfinal:
        cursor = conn.cursor()
        cursor.execute("""INSERT INTO splitted_sentences(sentence_id, splitted_sentences) VALUES(%s, %s)""",(cursor.lastrowid,j))
        conn.commit()
    conn.close()

I'm hesitant to do this for the cursor, because that might break things. Why, you ask? Because of the cursor.lastrowid. Before a statement has been made, it is None. So we must mimic that.

def connect():
    conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
    cursor = conn.cursor()
    for j in nrfinal:
        cursor.execute("""INSERT INTO splitted_sentences(sentence_id, splitted_sentences) VALUES(%s, %s)""",(None,j))
    conn.commit()
    conn.close()

In fact, I think you want to make sentence_id an AUTO_INCREMENT. Then, write

def connect():
    conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
    cursor = conn.cursor()
    for j in nrfinal:
        cursor.execute("""INSERT INTO splitted_sentences(splitted_sentences) VALUES (%s)""",(j,))
    conn.commit()
    conn.close()

Executing many statements

The mysql.connector allows executemany.

nrtuples = ((j,) for j in nrfinal)
def connect():
    conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis' )
    cursor = conn.cursor()
    cursor.executemany("""INSERT INTO splitted_sentences(splitted_sentences) VALUES (%s)""", nrtuples)
    conn.commit()
    conn.close()

That should take care of the memory usage.

Loading all the files

y_ = ""
for root, dirs, files in os.walk("/Users/Documents/source-document/part1"):
    for file in files:
        if file.endswith(".txt"):
            x_ = codecs.open(os.path.join(root,file),"r", "utf-8-sig")
            for lines in x_.readlines():
                y_ = y_ + lines

You load all files into memory at once. This is expansive. Rather not. Let's assume that there are no cross-file sentences going on (at least I hope not!).

def get_sentences():
    for root, dirs, files in os.walk("/Users/Documents/source-document/part1"):
        for file in files:
            if file.endswith(".txt"):
                x_ = codecs.open(os.path.join(root,file),"r", "utf-8-sig")
                yield x_.read()

If you also know that there are no cross-line sentences, you can use

def get_sentences():
    for root, dirs, files in os.walk("/Users/Documents/source-document/part1"):
        for file in files:
            if file.endswith(".txt"):
                x_ = codecs.open(os.path.join(root,file),"r", "utf-8-sig")
                for lines in x_.readlines():
                    yield lines

I'm not that big a fan of this deep nesting, and would prefer to also write a generator which yields the .txt files. But I hope you can continue from here.

Also, maybe you should use with codecs.open(....) as x_, that way the file gets closed when the iteration is done.

Further remarks.

There are certain style guidelines.

Keep your imports at the top of the file.

First a module-level docstring (if present).
Then, the imports from the standard library. (preferably sorted).
Then, imports from other libraries.
Then, imports from other parts of the project.
Then class/function definitions (in whatever order you please)
Finally, only a if __name__ == '__main__': block. Preferably containing only a function-call to main() in the module.

docstrings are no comments. Comments are no docstrings.

In the code you have ''' some useful text'''. But you actually want to use a comment: # some useful text. Know to disambiguate between those.

Multi-line comments? Just start every line with #.


An implementation of Levenshtein Distance algorithm in modern C++

Invalid access

There are several occurrences of out-of-range access as 1201ProgramAlarm's comment pointed out:

for (std::size_t k{ 0 }; k <= size_2; ++k) costs[k] = k;

costs[j + 1]

return costs[size_2];

This problem can be fixed by increasing the size of costs by one.

Usage of the standard library

std::vector<std::size_t> costs(size_2);
for (std::size_t k{ 0 }; k <= size_2; ++k) costs[k] = k;

Use std::iota:

std::vector<std::size_t> costs(size_2 + 1);
std::iota(costs.begin(), costs.end(), std::size_t{0}); // or 0_zu; see below

auto t{ upper < corner ? upper : corner };
costs[j + 1] = (costs[j] < t ? costs[j] : t) + 1;

Use std::min:

costs[j + 1] = std::min({upper, corner, costs[j]}) + 1;

auto

When you want the type of a variable to be deduced, auto is handy, because you don't have to write the type or expression twice.  When you want the type of a variable to be fixed, however, auto becomes cumbersome — so feel free to write

std::size_t i = 0;

An alternative is to use a user-defined literal: (there's a proposal P0330 Literal Suffix for (signed) size_t to add builtin literals for std::size_t)

namespace util_literals {
    constexpr std::size_t operator""_zu(unsigned long long number)
    {
        return static_cast<std::size_t>(number);
    }
}

So you can write:

using namespace util_literals;
auto i = 0_zu;

Also, instead of

for (const auto& itr_1 : string_1)

it is more common to access characters by value.  Also, itr is a misleading name for characters:

for (char c_1 : string_1)

Simplification

This check is redundant:

if (size_1 == 0) return size_2;
if (size_2 == 0) return size_1;

because the algorithm works well with empty strings.

Here's my version:

#include <algorithm>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <string_view>
#include <vector>

std::size_t Levenshtein_distance(std::string_view string_a, std::string_view string_b)
{
    const auto size_a = string_a.size();
    const auto size_b = string_b.size();

    std::vector<std::size_t> distances(size_b + 1);
    std::iota(distances.begin(), distances.end(), std::size_t{0});

    for (std::size_t i = 0; i < size_a; ++i) {
        std::size_t previous_distance = 0;
        for (std::size_t j = 0; j < size_b; ++j) {
            distances[j + 1] = std::min({
                std::exchange(previous_distance, distances[j + 1]) + (string_a[i] == string_b[j] ? 0 : 1),
                distances[j] + 1,
                distances[j + 1] + 1
            });
        }
    }
    return distances[size_b];
}

int main()
{
    std::string string_a;
    std::string string_b;
    while (std::cin >> std::quoted(string_a) >> std::quoted(string_b)) {
        std::cout << Levenshtein_distance(string_a, string_b) << '\n';
    }
}

Input:

kitten sitting
corporate cooperation
123 ""
"" ""

Output:

3
5
0
0

(live demo)


Get Minimum of four and maximum up to a limit

First impressions

Obviously, the code needs to be indented properly.  (Is that really how you wrote the code, or an artifact of the posting process?  The easiest way to post code on Stack Exchange is to paste it, select it all, and hit CtrlK on the entire block.)  In addition, you need to pick a consistent brace style.  (Your if-statements use K&R braces, but the function definition and the for-loops use a different convention.)

Don't omit "optional" braces:

if((sum-a[0])<=x)
big = sum-a[0];
else if((sum-a[1])<=x)
big = sum-a[1];
else if((sum-a[2])<=x)
big = sum-a[2];
else
big = small;

By omitting braces, someday, you will contribute to a coding mishap, and it will be your fault.  (If you use K&R braces, the braces will hardly take up any extra space.)

In modern C, you should avoid overwhelming declarations like this:

int x,a[4],i,j,n,temp,big,small,sum=0;

I have no idea what these variables are, or where they will be significant.  Since the challenge used terminology r and x, I would use those names instead of making up new ones.

Validation and output

Near the end, you wrote:

if(big == small){
    return 0;
}

That check doesn't make much sense to me.  First of all, the specification calls for two numbers to be output.  You shouldn't decide to omit one of them.  (Note that if big is over budget, then so is small.)  In the absence of any guidance on how to handle these special cases, I wouldn't bother checking for these conditions, except perhaps to write a comment or assertion.

Algorithm

The messiest part of the program is this bubble-sort-and-sum loop:

for(i=0;i<n;i++)
{
    for(j=i;j<(n);j++)
    {
        if(a[i]>a[j]){
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
    sum+=a[i];
}

I don't think that sorting is necessary to solve this challenge, but if it were, I would recommend writing a function to do sorting.

Suggested solution

#include <stdio.h>

int sum(int a[], size_t len) {
    …
}

int max(int a[], size_t len) {
    …
}

int main() {
    // Read input r1, r2, r3, r4, and x.  Note that r[0] holds r1.
    int r[4], x;
    for (int i = 0; i < sizeof(r) / sizeof(r[0]); i++) {
        if (!scanf("%d", &r[i])) return 1;
    }
    if (!scanf("%d", &x)) return 1;

    // Sum of all four
    int total = sum(r, sizeof(r) / sizeof(r[0]));

    // Sum of three smallest r (assumed to be within budget)
    int least = total - max(r, sizeof(r) / sizeof(r[0]));

    int most = least;
    for (int i = 0; i < 4; i++) {
        int other_sum = total - r[i];
        if (most < other_sum && other_sum <= x) {
            most = other_sum;
        }
    }
    printf("%d %d\n", least, most);
}


You code looks pretty good to me. Some notes:

do |node| and then node[0], node[1]: You should unpack in the block: dp |val1, val2|
Instead of mixing logic with I/O, first build the table string, then print it.

I'd write:

data = {
  numbers:   1..10,
  letters:   %w(a b c d e f g h i j),
  notes:     %w(do re mi fa so la ti do),
  phonetic:  %w(alpha bravo charlie delta echo),
  rainbow:   %w(red orange yellow green blue indigo violet)
}

header = data.keys.map { |k| k.to_s.capitalize }
table = data.values.first.zip(*data.values.drop(1)).map do |row|
  row.zip(header).map do |value, header_name|
    value.to_s.rjust(header_name.size)
  end.join(" ")
end

puts(([header.join(" ")] + table).join("\n"))


filter date for a specific hour and minute

Try something like this:

for i in dates:
    if i.hour == selected_hour:
        print i
    elif i.hour == (selected_hour - 1) % 24 and i.minute > 45:
        print i
    elif i.hour == (selected_hour + 1) % 24 and i.minute <= 15:
        print i

The biggest technique I used to condense your code basically was "Don't repeat yourself"! You have a lot of redundant if statements in your code which can be simplified.

Another thing that makes my code more understandable is that it's flat, not nested. Ideally, you'd want to minimize the number of logic branches.

Edit: As @Dougal mentioned, my original code wouldn't work on the special case of midnight. I added in a modulus operator on my two elif conditions so that the selected_hour test wraps in a 24 digit circle, just like real time.


Best way to include image_tag inside link_to

You could create a helper to keep your views less bloated. For example:

app/helpers/application_helper.rb

...
def image_link_to(image_path, url, image_tag_options = { }, link_to_options = { })
  link_to url, link_to_options do
    image_tag image_path, image_tag_options
  end
end
...

app/views/pages/show.html.haml

...
= image_link_to "buckminsterfullerene.png", my_url_helper, { size: '210x60', alt: 'Molecular structure of Buckminsterfullerene' }, { title: 'Buckminsterfullerene', rel: 'tooltip', relative: true }
...


Code Improvement: Copy Regex named capture groups to strongly typed object

By seeing the structure of your code structure i assume that all those if staements can easily be changed by a 'switch case' - which obviuosly is a code smell. I think you need to refactor your code. For further details please visit this link


Scala mastermind solver, which is the most scala-ish

All this zipping and unzipping looks really convoluted. I think the problem here is getting too much enamored with what you can do with a Scala collection instead of focusing on the problem at hand.

One way of decreasing zip cost is to do it on a view. This way, no intermediary collection is created -- though that depends a bit on the methods being called. At any rate, zip is one of these methods.

It wouldn't work on your case, however, because you then go on to partition and unzip -- I'd be wary of calling such methods on a view, because they may end up being more expensive, not less.

I think the map approach is better, because it avoids the O(n log n) sorting. A HashMap can be built in O(n), and looked up in constant time. This is how I'd do it:

object Mastermind {
  def check(guess: Symbol*)(secret: Symbol*): (Int, Int) = {
    val numOfGoodPairs = guess.view zip secret count { case (a, b) => a == b }
    val guessesForSymbol = guess.groupBy(identity).mapValues(_.size)
    val secretsForSymbol = secret.groupBy(identity).mapValues(_.size)
    val unorderedGuesses = for {
      symbol <- guessesForSymbol.keys.toSeq
      secrets <- secretsForSymbol get symbol
      guesses = guessesForSymbol(symbol)
    } yield secrets min guesses
    val numOfMisplaced = unorderedGuesses.sum - numOfGoodPairs
    (numOfGoodPairs, numOfMisplaced)
  }
}

The first line should be pretty fast -- it will iterate once through both guess and secret, counting each time they are equal.

Computing both maps is more expensive, but it should be cheaper than sorting. Note that mapValues return a view of the values -- it does not copy any data. This is particularly interesting because it will only compute the size of map elements for keys present in both guess and secret. It is a small optimization, but you gain it almost for free.

We avoid most of the complexity by simply subtracting the number of correct guesses from the number of unordered guesses.


Extracting a list of objects from a repository as JSON

Anonymous types are going to be your friend here.  You don't need to have list or dictionary at all.

First you don't need to call ToList() from your repository.

Now we can just project out the properties you want like so

wards.Select(w => new
{
     ward_id = w.ward_id.ToString(),
     w.ward_name
})

JsonConvert will serialize an IEnumerable as an array.  this will get your square bracket around the "Wards" and have the two properties you would like and having the Id converted to a string.

Now you just need the "data" object to contain the IEnumerable.  Again making an anonymous type.

var data = new
{
    data = wards.Select(w => new
    {
        ward_id = w.ward_id.ToString(),
        w.ward_name
    })
};

var json = JsonConvert.SerializeObject(data);

That's it.  That should get you what you want.


It would be much easier to give feedback if we saw your actual code, for those 5 js files.

Regardless, I tend to organize differently:

controllers/
  user.js
views/
  user.js
models/
  user.js

So anything that does not fit controller/user.js or views/user.js goes into models/user.js.

I want a specific controller to have it's own file (Same goes with services, filters and directives). There is no good enough reason to do this, keep controllers and views together, and do not split up everything.


hash_next_n_bytes can return None in case of EOF
You close the remaining files at the end of group_duplicate_files, but you just del file_handle_map[f] in the while loop. You don't have to close the files, their __del__ method will take care of it when the function returns.
Instead of

while True:
    terminate = True
    ...
    if terminate:
        break

you can do

terminate = False
while not terminate:
    terminate = True
    ...

No need to make file_handle_map a defaultdict, it can be just dict.

Some optimization suggestions:

You can initialize the hash with sizes of files. That way, you will avoid comparing large files with many common leading bytes.
It might just be faster to calculate some simple checksum (MD5 or so) of a larger portion of the file. Alternately reading 10 bytes from many different files and calling hash on each result will likely be inefficient.


The following is imho easier to read and should give you best performance.

<?php

/**
 * Get a sorted list of client accepted languages.
 *
 * @staticvar array $examined
 *   Used to cache the sorted list for <var>$accept_languages</var> strings.
 * @param boolean $list [optional]
 *   Whether to get a sorted list or the language with the highest preference, defaults to FALSE and
 *   the language with the highest preference will be returned.
 * @param string $accept_languages [optional]
 *   The client submitted accept languages string in the format defined in RFC 2616.
 * @param string $default [optional]
 *   The default ISO 639-1 alpha-2 language code to use if no other language could be determined, defaults to
 *   "en".
 * @return array|string
 *   Associative array where the key is the language code or locale and the value the preference if <var>$list</var>
 *   is set to TRUE, otherwise the ISO 639-1 alpha-2 code or locale of the language with the highest
 *   preference.
 */
function get_client_preferred_language($list = false, $accept_languages = null, $default = "en") {
  static $examined = array();

  // Either use the supplied string or use the string from server input, this construct ensures highest performance
  // because a positive check is performed.
  $accept_languages || ($accept_languages = filter_input(INPUT_SERVER, "HTTP_ACCEPT_LANGUAGE", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH));

  // Only examine this string if we haven't done so in the past.
  if (empty($examined[$accept_languages])) {
    // Prepare default fallback in our cache for this string.
    $examined[$accept_languages] = array($default => 1.0);

    // Only continue if we have a string to examine.
    if ($accept_languages) {
      // Prepare array for collecting the preferred languages.
      $languages = array();

      // Extract all languages from the accept languages string, the format is defined in RFC 2616.
      preg_match_all("/([a-z]+(?:-[a-z]+)?)\s*(?:;\s*q\s*=\s*(1|0?\.[0-9]+))?/i", $accept_languages, $matches);

      // Only go through all extracted languages if we have any.
      if (!empty($matches[1])) {
        foreach ($matches[1] as $delta => $code) {
          // Empty means highest preference.
          $languages[$code] = empty($matches[2][$delta]) ? 1.0 : (float) $matches[2][$delta];
        }

        // Sort the accepted languages by preference, if sorting fails use default.
        if (arsort($languages, SORT_NUMERIC) === true) {
          $examined[$accept_languages] = $languages;
        }
      }
    }
  }

  return $list ? $examined[$accept_languages] : array_values($examined[$accept_languages])[0];
}

// ----------------------------------------------------------------------------------------------------------------- Test

function get_client_preferred_language_test() {
  assert(array(
    "en-US" => 1.0,
    "en"    => 1.0,
    "en-AU" => 0.8,
    "fr"    => 0.6,
    "en-GB" => 0.4,
  ) === get_client_preferred_language(true, "en,en-US,en-AU;q=0.8,fr;q=0.6,en-GB;q=0.4"));
}

get_client_preferred_language_test();


Shorthand expansion exercise from K & R C (ex 3-3)

Here are some comments regarding your code:

Using s1[i+2] and s1[i-1] can possibly refer to memory locations outside of allocated memory
Inside of expand() you use the restriction of MAXLEN which is not conveyed in the parameters, which should be like char s1[MAXLEN] (which also introduces different strange aspect of the c-language). As your code stands now you can easily call it with char fails[2]; expand(fails, fails)
You should also test for null before accessing input parameters, currently you can call expand(input, 0) and it will happily try to do something which will fail
You are better of to always include braces around blocks within if-else statements to avoid erroneous indentation errors
Give s1 and s2 proper names to indicate what they are
You'll possibly get into problems or unwanted behaviour, with input like z-0, a-00--a, Z-0, --[
The range a-a will give count = DOWN, and behave somewhat strangely

Regarding the brace comment, consider the following code snippet:

int a = 13; int b = 5;
if (a < b)
   a = a + 10;
   if (a > b)
      a = 5;
else
   b = 6;

What will a and b hold now? Correct answer is a=5, b=5. If surrounding the blocks with braces the code would behave like you possibly read it, indicating the correct response of a=13, b=6. This is a constructed example, but it does happen way to often in real life that someone indents the code wrongly and strange things happen.

Here is the code example again, using starting braces on the same line, many prefer them to be on a new line. Choose a style, and stick to it.

int a = 13; int b = 5;
if (a < b) {
   a = a + 10;
   if (a > b) {
      a = 5;
   }
} else {
   b = 6;
}


Setting the smallest number so far from user input

Overall, this looks pretty good. It's straightforward and readable, which is great.
Naming
One of the most important things in programming is naming things so that anyone reading the code can figure out the meaning. You've done a pretty good job, but I think you could improve it. Calling a variable x is kind of useless. You could name it something like userValue, or even input so someone reading the code at least knows from the name that it's something that's input by the user.
Your constant names are OK, but could be better. (It's great that you're using named constants at all, though!) It would be nice to add that your converting from cm or in to meters. And there are some common conventions for constants, too. Some people prefer constants to be all capital letters, and others prefer to prefix them with the letter "k" (like it's a mathematical constant). So you could name them CM_TO_METERS or kInToMeters, etc. That way if you add other types of conversions in the future (like converting to Imperial), then you might add kCmToInches or whatever.
Finding the Min and Max
You ask if there's a good constant to initialize the minimum to. I usually use the constant DBL_MAX in this case. (It's defined in <cfloat>.) If you're looking for only positive numbers, then you can use 0 as the start value for the maximum value. Then any number entered will automatically be greater than that.
Potential Problem
I see one thing that could be a problem. You declare x as a double, but the first thing you do with it is cast it to a char and check if it equals |. That seems really odd, error prone, and hard to understand. If it were me, I would probably refactor this to prompt the user to tell me what they want to do (convert another value, or quit), then after they've told me they want to enter a number, get the numeric input into x.
A Better Loop
You say you don't like having the initial prompt outside of the loop, and I agree. It's good to remind the user what input you're expecting each time through the loop. I'd probably rewrite the loop like this:
bool done = false;
do {
    cout << "What would you like to do?\n";
    cout << "1) Convert a value\n";
    cout << "2) Quit\n";
    char action;
    cin >> action;
    if (action == '2')
    {
        done = true;
    }
    else
    {
        // Your code for getting and converting a number
    }
} while (!done);

Now it will prompt the user each time through the loop, and when they decide to quit, they can simply enter "2" at the prompt.


Verifying and reducing Latin squares with Python 3

You can make few minor improvements like:-

For comparing types use isinstance instead of comparing types using is. is won't work in case of multiple-inheritance. Plus for comparing against multiple types you can do isinstance(n, (str, int)). Read: Differences between isinstance() and type() in python

The elif and else block in is_latin function look redundant to me, you only need to check for mismatch there. Plus if line != valid_combination is more readable than: if not(line == valid_combination).
The else block in reduce_latin is also unreachable and you can remove it too.
Your code has couple of PEP 8 errors that you could check here: http://pep8online.com/


It's not ideal to call sort() for each element.  The first call already gives you the sorted vector, so each additional call just needlessly overwrites it.  This approach would also be very slow if the vector were much larger.

Since you're already returning a vector, you just need to sort once and then print once:

int main()
{
    std::vector<int> a = { 17, 12, 1, 20, 4, 6, 94 };

    a = sort(a);

    for (auto& iter : a)
    {
        std::cout << iter << "\n";
    }
}

There's also no need for the typedef.  To help ensure you're using the proper type, you can use auto instead.  You should also replace the ints in sort() with auto.  Having higher compiler warnings would've alerted you to this type mismatch.


stopWatch = Stopwatch.StartNew();
stopWatch.Stop();

If you want to create a Stopwatch that's stopped, use the constructor instead of StartNew() and then immediately stopping it.

timer1

The autogenerated WinForms names don't make much sense. If you have only one timer and there is no need to name it, call it just timer.

Also, consider creating the Timer in code, so that I don't have to look at the designer to find out for example what the period of timer is (or to change it).

if (state == WatchState.Stopped)
{
    OnStart();
} else if (state == WatchState.Started)
{
    OnLap();
}

This is an unusual bracing style. The normal .Net style would be to have the else if on a new line.

TimeSpan newitem = new TimeSpan(item.Hours, item.Minutes, item.Seconds);
timesToString.Add(newitem.ToString());

What is the purpose of this code? Is it to get rid of the "milliseconds" part in the output? Are you aware that it also removes the "days" part? If you're doing this just to get the format you want, consider using a custom format string (.Net 4+ only).

string elapsedTime;

There is no reason to declare this variable early.

String.Format("{0:00}:{1:00}:{2:00}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)

Why are you using two different approaches to get TimeSpans formatted in the same way (here and using the new TimeSpan() approach above)? Considering encapsulating the formatting into a common method.


Increment up the build number in AssemblyInfo.cs on every build

Why not use Regex.Match instead of using those confusing joins/splits? Unless you are purposely trying to code golf this, doing it using regular expression is much easier to follow logically.

After taking into account delegates used with Regex.Replace (as explained in svick's comment), here is a functionally superior solution to the previous answer I posted. This eliminates much of the unnecessary lambda pieces. The original solution is arguably not a good use of LINQ because of the changes being made to the collection (ie. not a very strong use of queries, despite lambdas having that functionality).

static void Main()
{
    string file = "AssemblyInfo.cs";
    if (File.Exists(file))
        File.WriteAllText(file,
            Regex.Replace(
                File.ReadAllText(file),
                @"(?<=\[assembly: AssemblyFileVersion\(""[0-9]*.[0-9]*.)[0-9]*(?=.[0-9]*""\)\])",
                m => (Convert.ToInt16(m.Value) + 1).ToString()
            )
        );
    }
}

Still only one semi-colon, but at least it's possible to look at it and recognize each piece for what it does. Note I split the parentheses onto separate lines here for parameter readability, but some programmers disagree with this style of line-breaking.

It basically works similar to your original solution, but it basically finds and replaces the Regex.Match with an incremented value.


Deprecation warning

This code works in both Python 2 and 3.  However, in Python 3, unittest.assertEquals() is deprecated in favour of .assertEqual(), so use .assertEqual() for better compatibility.

Length check

valid_length_cc would be better written as return 15 <= len(cc_candidate) <= 16.  It should also be moved further down, near the definition of is_valid_cc, since it has nothing to do with the Luhn algorithm code.

However, I recommend dispensing with the function altogether.  The expected length varies according to the card type.  You could just use the regex check to do the length validation for you.

Regex check

Your regex allows optional hyphens, but nowhere else in the code do you handle hyphens gracefully.

You incorrectly allow the second character of a card number that starts with 3 to be a comma.

Support for Discover cards appears to be incomplete.

The leading ^ anchor is redundant if you use re.match().

As previously mentioned, the regex should vary completely according to the card type.  I would therefore write it this way for clarity:

def check_regex(candidate):
    PATTERN = re.compile(r'(4(?:\d{12}|\d{15})'   # Visa
                         r'|5[1-5]\d{14}'         # Mastercard
                         r'|6011\d{12}'           # Discover (incomplete)
                         r'|7\d{15}'              # Petroleum and misc.
                         r'|3[47]\d{13}'          # American Express
                         r')$')
    return bool(PATTERN.match(candidate))

Luhn algorithm check

In my opinion, is_luhn_valid() would be better named check_luhn(), to be consistent with check_regex().

find_check_digit() would be better named compute_check_digit().  You'll never "find" the check digit by looking for it.  I'm not sure that it's a useful function to have at all, though, as is_luhn_valid() should be good enough.

Rather than slicing the string in is_luhn_valid(), I recommend feeding it intact to check_sum(), since it's really part of the same checksumming kind of operation.  For compatibility with your existing code, I've introduced an includes_check_digit mode to check_sum() that defaults to False.

For simplicity, the sum_digits() function could be replaced by a lookup table.

When calling sum(), you only need a generator expression, not a list comprehension.  You can therefore write sum(… for …) instead of sum([… for …]).

Suggested implementation

import re

def check_sum(numeric_string, includes_check_digit=False):
    if not includes_check_digit:
        numeric_string += '0'
    EVEN_VALUES = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
    evens = numeric_string[:-1][::-2]
    odds = numeric_string[::-2]
    return sum(int(i) for i in odds) + sum(EVEN_VALUES[int(i)] for i in evens)

def find_check_digit(numeric_string):
    return 9 * check_sum(numeric_string) % 10

def check_luhn(candidate):
    return candidate.isdigit() and check_sum(candidate, True) % 10 == 0

def check_regex(candidate):
    PATTERN = re.compile(r'(4(?:\d{12}|\d{15})'      # Visa
                         r'|5[1-5]\d{14}'            # Mastercard
                         r'|6011\d{12}'              # Discover (incomplete?)
                         r'|7\d{15}'                 # What's this?
                         r'|3[47]\d{13}'             # American Express
                         r')$')
    return bool(PATTERN.match(candidate))

def is_valid_cc(candidate):
    return check_regex(candidate) and check_luhn(candidate)


If you want a lazy sequence, this may be a good example of using Python-style generator functions.  An example:

(defn concat-gen    ; concat a list of collections
  [& collections]
  (lazy-gen
    (doseq [curr-coll collections]
      (doseq [item curr-coll]
        (yield item)))))

(defn concat-gen-pair
  [& collections]
  (lazy-gen
    (doseq [curr-coll collections]
      (doseq [item curr-coll]
        (yield-all [item item])))))

(def c1 [1 2 3])
(def c2 [4 5 6])
(def c3 [7 8 9])

(is= [1 2 3 4 5 6 7 8 9]                            (concat-gen       c1 c2 c3))
(is= [1 1  2 2  3 3  4 4  5 5  6 6  7 7  8 8  9 9]  (concat-gen-pair  c1 c2 c3))


Moving an element from one unordered_map to another

Unused Includes
The code is not using std:vector, nor is it using anything from utilities. It might be better not to include these, that can improve your compile time and decrease the size of the generated code.

Don't Repeat Yourself
There are two obvious functions that can be written to shorten the code in main(). One function prints the contents of an unordered map and the other moves the contents from one map to the other. When you see code repeating itself in a function that is a good indication that you can create a function to reduce the amount of code in the function to make it simpler.

Program Exit Status
In this particular program it isn't necessary to have return 0; in main() C++ will generate it for you. When you have programs that might fail it might be better to include cstdlib and use the symbolic constants EXIT_SUCCESS and EXIT_FAILURE to indicate success or failure to the calling program.


More elegant way to count anagrams in Python?

Performance (Language independent)

The permutations scale factorially with the word length and your loop code squares quadratically with the number of words.
Both are really bad scaling factors.
The nice thing to realize, that all equivalent anagrams map to the same multiset.
There are python libraries for multisets, but already with the built-in tools you can go a long way.
Two strings are equivalent, under "Anagram-relation", if they are the same after sorting. We will treat the sorted string as representation of our Anagram equivalence class. Since strings are immutable you can even use these represantions directly as dictionary keys.

Your code becomes then quite short

from collections import defaultdict

def count_anagrams(words):
    result = defaultdict(list)
    for word in words:
        result[''.join(sorted(word))].append(word)
    return dict(result)

This scales linearly with word number and (n * log(n)) with word length. (Under the assumption that dictionary insertion is O(1) and sorted uses a reasonable sorting algorithm.).

The output of

count_anagrams(['stop', 'test', 'post'])

is then

{'opst': ['stop', 'post'], 'estt': ['test']}

You can change it to your needs by transforming it to your desired output with len etc.

If you want to convert it to the exact same form as you have it, one example function would be:

def convert_output(words_in_anagram_class):
    return {word: len(words)
            for words in words_in_anagram_class.values()
            for word in words}

Then you can call convert_output(count_anagrams(words)). If you want to, you can combine these two functions into one.
(Although this is IMHO a far less useful representation of your data.)

Small stuff (Python nitpicks)

map can and should be replaced with comprehensions. Especially if you cast the result into a list.
[f(x) for x in iterable] is far nicer to read than list(map(f, iterable)).
If you really want a generator, there are also generator expressions
(f(x) for x in iterable).


The function does not preserve object identity. Zeros of other types get replaced with an integer:

>>> nonzero([0, 0.0, 0j])
[0, 0, 0]

If the input only ever contains integers, then this isn't a problem, but it's worth remembering that Python has several different types of number.
The docstring is not quite right. "push all the zeros to the end" implies that the input array is modified, but that's not true: a new array is created and returned.
There's a neat trick for implementing this:

def nonzero(a):
    """Return a copy of the iterable a with all zeros at the end."""
    return sorted(a, key=lambda x: x == 0)

This works because False compares less than True, and because Python's sort is guaranteed to be stable: it never changes the relative order of elements with the same sort key.


Contentwise considerations

Use const wherever possible, otherwise let. Avoid var.
Match the version number only once (see code below) and employ the ? operator to save redundancy: v_?[0-9].
(The latter might actually be disputable, I personally find both versions easy to read.)

Your code would be shorter and much easier to reason about if it was more functional.
However, as JS is missing some functional concepts other languages take for granted (array comprehension, min/max in array by key function), this would require helper functions being a new, but onetime overhead. Are you using a third-party library like Lodash by accident? Then you already got many functional polyfills.

Which methods does the Enumerator you are using from SharePoint support apart from the iterative query interface with moveNext(), get_current()? If there is no built-in support, I'd suggest writing a generator function:

function *getTemplateIterator(templates) {
  const templateEnum = templates.getEnumerator();
  while (templateEnum.moveNext()) {
    yield templateEnum.get_current();
  }
}

function ApplyTemplate() {
  return [...getTemplateIterator(this.templates)]
    .filter(template => template.get_title().includes('espace_projet'))
    .map(template => {
      const version = /v_?([0-9]+)/.match(template.get_title());
      return {
        version: (version !== null) ? parseInt(version[1], 10) : -1
        template: template
      };
    })
    .reduce((highestVersionedTemplate, template) =>
      (template.version > highestVersionedTemplate) ? template : highestVersionedTemplate,
      { version: -1, template: null }
    );
    // In contrast with an array max/min function suporting a key extracting function
    // (e.g. like in Python: https://docs.python.org/3.8/library/functions.html#max)
    previousChainOfFunctions.maxOrDefault(template => template.version, { version: -1, template: null });
}

Stylistic considerations

Your variable names are self-explanatory and consistently written, that's fine!
Use consistent braces in blocks (function, if, many more), e.g. function { or function[newline]{, but do not mix both.
Always use braces around if, else, for, while.


Drag and drop GUI with native JavaScript

Events
Instead of adding 3 (permanent) EventListener, you could just keep the first one: square.addEventListener('mousedown'... and when this is triggered, add the 2 other events mouseup and mousemove on the document (it will also enalbe the user to move quickly)
The mouseup event should then simply remove the 2 event listeners (you will need to keep a trace of the EventListeners).
You can then get rid off the pushed variable.
The square.addEventListener could be moved inside the constructor.
moveCursor
In the method moveCursor instead of moving only if the new position is completely in the area, you could separately check the X and Y coordinates (It will then be easier to move near the edges).
Naming
I don't find the name Cursor to be very expressive... maybe Draggable is a better name?


Your description of the problem indicates that each event type can have multiple listeners, but the code only implements one listener for each event. Is this intended?

The params awkwardness is a "feature" of go....

Because Go is

statically compiled
does not have function signature overloading (you can't have multiple functions with the same name, and differentiate them based on the signature)

You cannot avoid having the param input arguments to the Fire function. This is a "drawback" of Go. When you become more comfortable with the language you avoid constructs like you have, because they are hard to maintain (anything requiring reflect is probably a bad idea).

Additionally, your sync usage is broken - you need to manage the lock on both the Fire call, and the On call. Your On call is also broken because it has a race condition....

Note that reads on the map also need to be sync'd, not just writes.

So, this code:

func (t *trigger) On(event string, task interface{}) error {
    if _, ok := t.functionMap[event]; ok {
        return errors.New("event already defined")
    }
    if reflect.ValueOf(task).Type().Kind() != reflect.Func {
        return errors.New("task is not a function")
    }
    t.mu.Lock()
    defer t.mu.Unlock()
    t.functionMap[event] = task
    return nil
 }

should be:

func (t *trigger) On(event string, task interface{}) error {
    // Lock the mutex before reading it.
    t.mu.Lock()
    defer t.mu.Unlock()

    if _, ok := t.functionMap[event]; ok {
        return errors.New("event already defined")
    }
    if reflect.ValueOf(task).Type().Kind() != reflect.Func {
        return errors.New("task is not a function")
    }
    t.functionMap[event] = task
    return nil
 }

Additionally, the Fire should also have a mutex control (perhaps the t.read(...) function has a lock?)

func (t *trigger) Fire(event string, params ...interface{}) ([]reflect.Value, error) {
    f, in, err := t.read(event, params...)
    if err != nil {
        return nil, err
    }
    result := f.Call(in)
    return result, nil
 }


I assume you are trying to do something like:

def blur(n)
  blurred = Image.new(self).arr.transform
  (n-1).times do
    blurred = blurred.transform
  end
  blurred
end

And getting an error like:

`block in blur': undefined method `transform' for #<Array:0x00000002d51ba8>

The reason is that transform is a instance method of Image, which is why you need to convert back into an image before calling it.

There are a couple of way this can be handled.  I've chosen to make transform a static method that only works on arrays.  The instance methods transform and blur call the static method as needed

class Image
  attr_accessor :arr

  def initialize(arr)
    @arr = arr
  end

  def transform
    result = Image.arr_transform(@arr)
    Image.new(result)
  end

  def self.arr_transform(array)
    cloned = array.map(&:clone)

    #scan original array for 1; map crosses into clone if found
    array.each.with_index do |row, row_index|
      row.each.with_index do |cell, col|
        if cell == 1
          cloned[row_index][col+1] = 1 unless col+1 >= row.length #copy right
          cloned[row_index+1][col] = 1 unless row_index+1 >= cloned.length # copy down
          cloned[row_index][col-1] = 1 unless col.zero? # copy left
          cloned[row_index-1][col] = 1 unless row_index.zero? #copy up
        end
      end
    end
    cloned
  end

  def blur(n)
    blurred = @arr
    (n).times do
      blurred = Image.arr_transform(blurred)
    end
    Image.new(blurred)
  end

end

Testing:

image = Image.new([[0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,1,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0]])

require 'pp'
pp image.blur(3)

Returns:

#<Image:0x00000002e9fb40
 @arr=
  [[0, 0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 1, 0, 0, 0, 0],
   [0, 0, 0, 1, 1, 1, 0, 0, 0],
   [0, 0, 1, 1, 1, 1, 1, 0, 0],
   [0, 1, 1, 1, 1, 1, 1, 1, 0],
   [0, 0, 1, 1, 1, 1, 1, 0, 0],
   [0, 0, 0, 1, 1, 1, 0, 0, 0],
   [0, 0, 0, 0, 1, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0, 0]]>


Review
You have posted one method for review, but that method has multiple responsibilities.
Good code follows the "Single Responsibility Principle". Your method does the following things:

it creates a random number generator
it generates a random number
it opens and reads data from a file and then closes it.
it generates another random number
it opens and reads data from another file, and then closes it.
it generates yet another random number
then another
it builds a string value from a number of components.
sets the value of the name field to this string

That is a lot of things happening in one method.
Additionally, your code has a number of magic numbers: 300 star names, 11 Greek letters, 1000 random values, and 4 letters. Each of these values are coded as magic numbers.
The File names are 'magic' too.
In that list, I can see the following bad practices:

two repeated items - selecting a random string from a file

a set method (setName) that does not take a value to set (setters should take a value, not generate a value)

You create a new Random instance each time

you repeatedly open/read/close multiple files.

you throw an IOException on a method which does not have a particularly IO-sounding name.

The above things should all be resolved.....
Alternative
Create a class that generates the names for you. Consider this class:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;

public class PlanetaryGenerator {

    private static final class RandomLine {
        private final List<String> lines;
        private final Random random = new Random();

        public RandomLine(String filename) throws IOException {
            this.lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8);
        }

        public String getRandom() {
            return lines.get(random.nextInt(lines.size()));
        }

    }

    private static final String[] SUFFIXES = {"a", "b", "c", "d"};

    private static final int MAXNUMBER = 1000;

    private final RandomLine stars;
    private final RandomLine greekletters;
    private final Random random;

    public PlanetaryGenerator(String starsfile, String greekfile) throws IOException {
        this.stars = new RandomLine(starsfile);
        this.greekletters = new RandomLine(greekfile);
        this.random = new Random();
    }

    public String generateName() {
        String prefix = stars.getRandom();
        String greek = greekletters.getRandom();
        int number = random.nextInt(MAXNUMBER);
        String suffix = SUFFIXES[random.nextInt(SUFFIXES.length)];

        // append to class name
        return String.format("%s %s-$d%s", prefix, greek, number, suffix);

    }
}

Then, in your existing code you can create a single instance of this, and just call it when you need a new name:
static PlanetaryGenerator ....

// get a new name:
String name = generator.generateName();


Find the word in a string that has the most repeated characters

I liked that you split the string into words using a regular expression.  That helps a lot.

Your code formatting (indentation and braces) is haphazard.  It shouldn't be that hard to follow the standard conventions for code formatting, and it will make things easier for yourself if you do.

I think your function tries to do too much.  It would help to break down the problem.  I've extracted part of the problem into a self-contained task:

  Given a word, how many times does the most frequent character appear?

For that, you can write a function, and test it (e.g. mostFrequentCount('hello') should return 2).

/**
 * Given an array (or a string), returns the number of times the most frequent
 * element (or character) appears.
 */
function mostFrequentCount(elements) {
    var bins = {};
    for (var i = 0; i < elements.length; i++) {
        bins[elements[i]] = (bins[elements[i]] || 0) + 1;
    }
    var max = 0;
    for (var c in bins) {
        max = Math.max(max, bins[c]);
    }
    return max;
}

That should simplify the main code.  Rather than commenting each line (in effect writing everything once for the computer and once for other programmers), I've tried to make the code read like English by using very human-friendly variable names.

function wordsWithMaxRepeatedCharacters(string) {
    var maxRepeatedCharacters = 0, wordsWithMaxRepeatedCharacters = [];

    var words = string.split(/\W/);
    for (var w = 0; w < words.length; w++) {
        var word = words[w];
        var numRepeatedCharacters = mostFrequentCount(word);

        if (maxRepeatedCharacters < numRepeatedCharacters) {
            maxRepeatedCharacters = numRepeatedCharacters;
            wordsWithMaxRepeatedCharacters = [word];
        } else if (maxRepeatedCharacters == numRepeatedCharacters) {
            wordsWithMaxRepeatedCharacters.push(word);
        }
    }
    return wordsWithMaxRepeatedCharacters;
}


Well, I cannot tell why it's so slow, but this should solve your problem:

$sites = Get-SPOSite -Limit all -Detailed

-Detailed switch will cause Get-SPOSite to load all properties. It makes iterating all sites to get title unnecessary.


Simple boolean gate with two TriState inputs

The readability can be improved by using explanatory variables, (of course changing the variable names as they make sense to you).

public static boolean isDummy(TriState a, TriState b) {
    boolean oneOfTheInputsIsZero = a.is(ZERO) || b.is(ZERO);
    boolean oneOfTheInputsIsNull = a.is(NULL) || b.is(NULL);
    return oneOfTheInputsIsZero && oneOfTheInputsIsNull;
}

First one makes it obvious that the function is commutative, in the second one you have to check the LHS and RHS are indeed the mirror image of each other.

Although the two functions may evaluate the same thing they don't say the same thing.
First one says "There is at least one zero and there is at least one null."
Second one says "There is one zero and the other one is null." (which matches the javadoc)

But the comments sometimes also lie. To check the veracity of the comment consider how would you write the function if it took more parameters.

They still say what they say before but now they don't evaluate the same coincidentally.

public static boolean isDummy(TriState a, TriState b, TriState c) {
    return (a.is(ZERO) || b.is(ZERO) || c.is(ZERO))
        && (a.is(NULL) || b.is(NULL) || c.is(NULL));
}

public static boolean isDummy(TriState a, TriState b, TriState c) {
    return a.is(ZERO) && b.is(NULL) && c.is(NULL)
        || a.is(NULL) && b.is(ZERO) && c.is(NULL)
        || a.is(NULL) && b.is(NULL) && c.is(ZERO);
}


Suggestion:

public static Integer[] removeDuplicates(Integer[] arr) {
  return new HashSet<Integer>(Arrays.asList(arr)).toArray(new Integer[0]);
}

Another solution might be:

public static int[] removeDuplicates(int[] arr) {
  Set<Integer> alreadyPresent = new HashSet<Integer>();
  int[] whitelist = new int[0];

  for (int nextElem : arr) {
    if (!alreadyPresent.contains(nextElem)) {
      whitelist = Arrays.copyOf(whitelist, whitelist.length + 1);
      whitelist[whitelist.length - 1] = nextElem;
      alreadyPresent.add(nextElem);
    }
  }

  return whitelist;
}

Here you only iterate once via arr.