Are you sure that solution is correct? By your description of the problem, I would have expected the result for an input [1, 6, 4, 7, 6, 6, 5] to be 3, but your solution produces 5.

Your solution is interesting -- that drew me to this question. I find that code looking at adjacent elements when iterating and accumulating an optimal value is a code smell in algorithms. It typically makes a solution significantly more difficult to read and debug. Usually, you should only look at as few values in each iteration as possible -- and I believe it's sufficient to look only at the current value whilst keeping the previous handy.

        if array[i-1] < array[i] and array[i] > array[i+1]:

This confers the additional benefit of removing the random access requirement for the input; that is, removing the __getitem__ dependency (array[i] is actioned as type( array ).__getitem__( array, i )). Whilst you've indicated that the input should be an array by the parameter name, one of Python's strengths is its duck-typing. There's no fundamental reason why the algorithm could not, or should not, apply more generically to any Iterable[int]. My solutions below will additionally work with input (contrived, I grant you) ( x for x in ( 0, 1, 0 ) ). If your minimum Python version requirement is sufficiently high, I would personally add a type hint to the argument, but that's usually deemed overkill.

            if len(array) == 3:  # special case
                return 3

A special case that isn't an edge-value of a data-type (e.g. 0 for an unsigned integer) is an immediate code smell.

    for i in range(1, len(array) - 1):

Skipping the end (and usually the start) of a sequence in an accumulation/optimisation problem is a smell. Avoid if possible.

The problem can be modeled by a state-machine. On each iteration of the array elements, you begin in one of four states: starting, floor, climbing, descending. You begin in the starting state and once the first element is seen immediately transition to floor. The floor represents a state in which you're neither climbing nor descending. This occurs when you've reached some plateau and haven't climbed out of it. The climbing state is self-descriptive. You begin descending once you have passed a peak having made a climb. The longest seen peak can only end whilst in a descending state. You seemed in your solution to try and defer the recalculations of the longest seen peak until you've left the peak. This isn't necessary -- if you descend further downwards, you can always carry on increasing the value of the longest seen peak.

Here is a descriptive algorithm:

import enum

class TrekState( enum.Enum ):
    Begin   = 0
    Floor   = 1
    Climb   = 2
    Descend = 3

class Trek:
    def __init__( self ):
        self.state = TrekState.Begin
        self.counter = 0
        self.longest = 0

    def advance( self, i ):
        # update new state of our trek
        if self.state == TrekState.Begin:
            self.state = TrekState.Floor
            self.counter = 1
        else:
            previous = self.previous

            if self.state == TrekState.Floor:
                if previous < i:
                    self.state = TrekState.Climb
                    self.counter += 1
            elif self.state == TrekState.Climb:
                if previous < i:
                    self.counter += 1
                elif previous > i:
                    self.state = TrekState.Descend
                    self.counter += 1
                else: # previous == i
                    self.state = TrekState.Floor
                    self.counter = 1
            elif self.state == TrekState.Descend:
                if previous < i:
                    self.state = TrekState.Climb
                    self.counter = 2
                elif previous > i:
                    self.counter += 1
                else: # previous == i
                    self.state = TrekState.Floor
                    self.counter = 1

        # update longest and previous
        if self.state == TrekState.Descend:
            self.longest = max( self.counter, self.longest )
        self.previous = i

def updatedLongestPeak( seq ):
    trek = Trek()
    for i in seq:
        trek.advance( i )
    return trek.longest

. A more concise version of the above, replacing object constructs with a more unstructured style, and some manual optimisations:

def verboseLongestPeak( seq ):
    state = counter = longest = 0

    for i in seq:
        counter += 1
        if state == 0:
            state = 1
        elif state == 1:
            if previous < i:
                state = counter = 2
        elif state == 2:
            if previous > i:
                state = 3
            elif previous == i:
                state = 1
        elif state == 3:
            if previous < i:
                state = counter = 2
            elif previous == i:
                state = 1

        if state == 3:
            longest = max( counter, longest )
        previous = i

    return longest

. If you were to go for a solution of the latter's style, it would be essential to provide comments on the meaning of each state value.

Neither solution is verified to be correct.


Welcome to Code Review!

Most of my suggestions are stylistic, but still something to care about in the Python world.  (PEP8 Style Guide)  I did catch a fairly major bug since you are only accepting 1 - 3999 as valid numbers, so we fix that too.

Redundant Parentheses

Unlike in C or C++ (or even Java to some level) you don't have to wrap conditionals in parentheses typically.  There are some cases where you would need to, but your if conditions are not complex enough to need that.

BUG: If an integer less than 0 is passed, there is no warning about being too small a number

Therefore, if a negative number is passed in at runtime, it outputs nothing and no errors.  We can fix this in one line of code - we just change your == check to a <= check (less than or equal to):

if num <= 0:
    return "Number too small"

Descriptive Parameters

Normally, you should name an parameter for a function in a more descriptive way.  While n can be assumed to be a number, it would be better to have num instead of n as an parameter name for getRomanNumerals to better describe what that is.

My two cents, of course, but in more complex functions where n could lose meaning, you'd be better off with a more descriptive parameter name so you don't lose track of what n does.

Rogue Semicolon!

On line 47, you have a rogue trailing semicolon.  While this doesn't affect running of your program, such semicolons are not necessary.

Style: Function names should be lowercase; multiword names separated with underscores

From the PEP8 (linked above):

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.

  mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

Therefore, your function names should be renamed as follows:

digitToRomanSym becomes digit_to_roman_sym
getRomanNumerals becomes get_roman_numerals

Style: Parameter variable names usually are lowercase

While not explicitly defined in PEP8 as far as I can tell, most of the time, arguments within a function (for example, symList in digitToRomanSym in your code) tend to be lowercase and if multiword, are underscore-separated.

Style: Local variable names should be lowercase, multiword separated with underscores

Just like function definitions, local variables should be lowercase.  That is, variables within the scope of a single function.

Your code after my changes:

(Filename: int2roman.py)

import sys

symbols1 =     [(1,   "I"), (5,   "V"), (10,   "X")]
symbols10 =    [(10,  "X"), (50,  "L"), (100,  "C")]
symbols100 =   [(100, "C"), (500, "D"), (1000, "M")]

symList = [symbols1, symbols10, symbols100]

def digit_to_roman_sym (digit, sym_list):
    """ Converts a single digit into its roman symbols """
    one =  sym_list[0][1]
    five = sym_list[1][1]
    ten =  sym_list[2][1]

    switcher = {
        1: one,
        2: one + one,
        3: one + one + one,
        4: one + five,
        5: five,
        6: five + one,
        7: five + one + one,
        8: five + one + one + one,
        9: one + ten,
    }
    return switcher.get(digit, "")

def get_roman_numerals(num):
    """ Converts a num between 1 and 3999 into Roman numerals """
    max_number = symList[-1][-1][0] * 4 - 1 # A symbol can be repeated max 3 times e.g. MMM for 3000

    if num > max_number:
        return "Number too big"

    if num <= 0:
        return "Number too small"

    i = 0
    roman_str = ""
    while num > 0 and i < len(symList):
        roman_str = digit_to_roman_sym(num % 10, symList[i]) + roman_str
        num /= 10
        i += 1

    if num > 0:
        biggest_symbol = symList[-1][-1][1]
        roman_str = (num * biggest_symbol) + roman_str

    return roman_str

if len(sys.argv) == 2:
    number = int(sys.argv[1])
    print(get_roman_numerals(number))
else:
    print("Wrong number of arguments")


Determine added, removed and kept items between two lists

First, let's look at the naive implementation using sets:

def diff_set(before, after):
    b, a = set(before), set(after)
    return list(a - b), list(b - a), list(a & b)

This is (so much more) readable and understandable than your code. The question is, is this significantly slower than your code?

Here are timings of your three example cases:

             Input                     diff             diff_set         diff_counter
 ------------------------------ ------------------- ------------------- -------------------
  [], []                         1.72 µs ± 29.9 ns   1.21 µs ± 5.34 ns   9.91 µs ± 91.4 ns
  [1,2,3], [4,3,2]               3.16 µs ± 183 ns    1.57 µs ± 28.4 ns   12 µs ± 180 ns
  ['foo','bar'], ['baz','bar']   2.77 µs ± 83.4 ns   1.56 µs ± 37.7 ns   11.5 µs ± 240 ns

The set implementation is faster in all three cases. But what about the scaling behavior? First lets set up some random test data of increasing length. Note that I scaled the number of available values up with the size of the lists, so that set(before), set(after) does not become trivial and so that there are both added and removed values. The only way in which this might be unrealistic is that both before and after are always of the same size.

import random
random.seed(42)
random_data = [([random.randrange(2*n) for _ in range(n)], [random.randrange(2*n) for _ in range(n)]) for n in range(1, 10000, 100)]

Here also the set implementation wins:

In other words: always try the naive approach first and then test to see if the more complicated approach actually improves anything.

For reference, here the implementation of diff_counter I used:

from collections import Counter

def diff_counter(before, after):
    c = Counter(after)
    c.subtract(before)
    return list(+c), list(-c), [elem for elem, count in c.items() if count == 0]


Conversion of a simple Python Neural Network to a Haskell implementation

You often switch between matrices and lists in the dotp function. Since that is an essential part of your code called every iteration and your data is a matrix, you should be using matrices everywhere.

In the documentation is noted, that there is a functor instance. That means you can use the function fmap on the matrix, which (in this case) maps a function over every cell. This means you can swap map (map fromIntegral) with fmap fromIntegral. The equivalent to zipWith (zipWith ..) is called elementwise.

The generations function doesn't seem to be called: you can avoid having dead code by compiling with warnings enabled, -Wall. The flipSign function is predefined and called negate.

I have changed nonlin to make the variable explicit, otherwise it wouldn't be clear what this Bool actually does. Furthermore, I have added some comments.

Finally, I have changed nextGeneration as there is no need to carry the l1 variable if it isn't needed by the next step. I've extracted that into a function (and so have to take the 9999th iteration in main).

Here is my version of the code:

import System.Random (randoms, mkStdGen)
import Data.Matrix

-- | input dataset
sample :: Matrix Double
sample = fmap fromIntegral $ fromLists
    [ [0,0,1]
    , [0,1,1]
    , [1,0,1]
    , [1,1,1]
    ]

-- | output dataset
answers :: Matrix Double
answers = transpose (fmap fromIntegral output)
    where
        output = fromLists [[0,0,1,1]]

-- | sigmoid function
nonlin :: Bool -> Double -> Double
nonlin derivative x = if derivative then x * (1.0 - x)
                                    else 1.0 / (1.0 + (exp (negate x)))

layer1 :: Matrix Double -> Matrix Double -> Matrix Double
layer1 l0 syn0 = fmap (nonlin False) (multStd l0 syn0)

nextGeneration :: Matrix Double -> Matrix Double
nextGeneration syn0 = new_syn0
    where
        -- forward propagation
        l1 = layer1 sample syn0

        -- how much did we miss?
        l1_error = elementwise (-) answers l1

        -- multiply how much we missed by the
        -- slope of the sigmoid at the values in l1
        l1_delta = elementwise (*) l1_error (fmap (nonlin True) l1)

        -- update weights
        new_syn0 = elementwise (+) syn0 (multStd (transpose sample) l1_delta)

main = do
    putStrLn "Output After Training:"
    print (layer1 sample result)
        where
            start = fromList 3 1 (randoms (mkStdGen 42))
            generations = iterate nextGeneration start
            result = generations !! 9999


T-SQL Pbdfk2 (Rfc2898 SHA2_256) Implementation

I took a very, very wild swing at this. I also couldn't get it down to something entirely set-based, but I was able to get it to an inline TVF with a recursive CTE (two of them, unfortunately). With 1000 iterations, I needed a MAXRECURSION of at least 998 to get it to finish.

I wouldn't trust this as a cryptographically secure implementation. I strongly suspect that the optimizer could do something funny here that would enable timing attacks; likely some very aggressive query hinting would be needed to ensure a stable join order and methodology. With some digging, I think we would have to do the following (at a minimum) to make it cryptographically secure. All of these are to prevent timing attacks:

Force LOOP joins; HASH joins use hash tables, which have known timing attack vulnerabilities, and MERGE joins will sort, which will be impacted by the available data.
Force a join order (OPTION( FORCE ORDER )); if the optimizer knows something about the cardinality of the data set and re-orders as a result we'll also see different numbers.
Disable parallelism (OPTION( MAXDOP 1 ))

Throughout all of this I'm heavily relying on the behavior of the APPLY operator where it evaluates the right-hand side for each row of the left-hand side. This was vital to get some of these complicated calculations, and I suspect is the path towards a non-recursive implementation (if there is one).

The first thing I had to do was re-create your outer loop calculations, which I did with something like this. You might need more in the counter in the middle (just keep CROSS APPLYing to sys.all_objects), but this was fine for my test cases.

SELECT uAOuter.Hash UA,
       uAOuter.Hash UB,
       OuterLooper.Counter
  FROM ( SELECT TOP (( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength )
                ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) [Counter],
                @salt + CAST(ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) AS binary(4)) U
           FROM sys.all_objects
           ORDER BY [Counter] ASC ) OuterLooper
    CROSS APPLY dbo.Hmac( @password, OuterLooper.U ) uAOuter

After that I got really stuck on how to calculate @uA in terms of itself; I still think that there is probably some really, really clever APPLY wizardry to get this, but I spent a few hours going nowhere on that one. Instead, I ultimately settled on a recursive CTE to get the base case and then do the calculation.

WITH InnerLoopRecursive AS
(
  SELECT tA.Hash uA,
         tB.Hash uB,
         OuterLoop.Counter OuterCount,
         1 [Counter]
    FROM ( SELECT uAOuter.Hash UA,
                  uAOuter.Hash UB,
                  OuterLooper.Counter
             FROM ( SELECT TOP (( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength )
                           ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) [Counter],
                           @salt + CAST(ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) AS binary(4)) U
                      FROM sys.all_objects
                      ORDER BY [Counter] ASC ) OuterLooper
               CROSS APPLY dbo.Hmac( @password, OuterLooper.U ) uAOuter ) OuterLoop
      CROSS APPLY dbo.Hmac( @password, OuterLoop.UA ) tA
      CROSS APPLY ( VALUES (
                      -- unrolled loop to XOR uA and uB
                      CAST(SUBSTRING( tA.Hash, 1, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 1, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 9, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 9, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 17, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 17, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 25, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 25, 8 ) AS bigint) AS binary(8)))) tB ( [Hash] )
  UNION ALL
  SELECT tA.Hash uA,
         tB.Hash uB,
         InnerLoopRecursive.OuterCount,
         InnerLoopRecursive.Counter + 1
    FROM InnerLoopRecursive
      CROSS APPLY dbo.Hmac( @password, InnerLoopRecursive.uA ) tA
      CROSS APPLY ( VALUES (
                      -- unrolled loop to XOR uA and uB
                      CAST(SUBSTRING( tA.Hash, 1, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 1, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 9, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 9, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 17, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 17, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 25, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 25, 8 ) AS bigint) AS binary(8)))) tB ( [Hash] )
    WHERE InnerLoopRecursive.Counter + 1 < @iterations
)

After that I was really hoping to get away with just an aggregate (or maybe a window function), but apparently you can't do that with varbinary(MAX), so I had to do another recursive CTE.

, DerivedKeyPerOuterLoop AS
(
  SELECT CONVERT( varbinary(MAX), '' ) DerivedKey,
         0 [Counter]
  UNION ALL
  SELECT DerivedKeyPerOuterLoop.DerivedKey + CONVERT( varbinary(MAX),
                                                      CASE WHEN DerivedKeyPerOuterLoop.Counter = (( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength ) THEN LEFT(InnerLoopRecursive.uB, @derivedKeyLength - ((( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength ) - 1 ) * @hmacLength)
                                                           ELSE InnerLoopRecursive.uB END ) DerivedKey,
         DerivedKeyPerOuterLoop.Counter + 1
    FROM DerivedKeyPerOuterLoop
      INNER JOIN InnerLoopRecursive
        ON ( DerivedKeyPerOuterLoop.Counter + 1 ) = InnerLoopRecursive.OuterCount
    WHERE InnerLoopRecursive.Counter = @iterations - 1
)

Throughout the recursive CTEs the JOINs get pretty funky as we're trying to handle a potential granularity explosion, but it should work okay-ish.

Once we have that final CTE, then we just need to get the result from the last iteration:

CREATE OR ALTER FUNCTION dbo.Pbkdf2_modified
(
  @password         varbinary(8000),
  @salt             varbinary(7996),
  @iterations       int = 1000,
  @derivedKeyLength int = 32,
  @hmacLength       int = 32
)
RETURNS table
AS
  RETURN ( WITH InnerLoopRecursive AS
           (
             SELECT tA.Hash uA,
                    tB.Hash uB,
                    OuterLoop.Counter OuterCount,
                    1 [Counter]
               FROM ( SELECT uAOuter.Hash UA,
                             uAOuter.Hash UB,
                             OuterLooper.Counter
                        FROM ( SELECT TOP (( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength )
                                      ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) [Counter],
                                      @salt + CAST(ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) AS binary(4)) U
                                 FROM sys.all_objects
                                 ORDER BY [Counter] ASC ) OuterLooper
                          CROSS APPLY dbo.Hmac( @password, OuterLooper.U ) uAOuter ) OuterLoop
                 CROSS APPLY dbo.Hmac( @password, OuterLoop.UA ) tA
                 CROSS APPLY ( VALUES (
                                 -- unrolled loop to XOR uA and uB
                                 CAST(SUBSTRING( tA.Hash, 1, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 1, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 9, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 9, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 17, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 17, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 25, 8 ) ^ CAST(SUBSTRING( OuterLoop.UB, 25, 8 ) AS bigint) AS binary(8)))) tB ( [Hash] )
             UNION ALL
             SELECT tA.Hash uA,
                    tB.Hash uB,
                    InnerLoopRecursive.OuterCount,
                    InnerLoopRecursive.Counter + 1
               FROM InnerLoopRecursive
                 CROSS APPLY dbo.Hmac( @password, InnerLoopRecursive.uA ) tA
                 CROSS APPLY ( VALUES (
                                 -- unrolled loop to XOR uA and uB
                                 CAST(SUBSTRING( tA.Hash, 1, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 1, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 9, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 9, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 17, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 17, 8 ) AS bigint) AS binary(8)) + CAST(SUBSTRING( tA.Hash, 25, 8 ) ^ CAST(SUBSTRING( InnerLoopRecursive.uB, 25, 8 ) AS bigint) AS binary(8)))) tB ( [Hash] )
               WHERE InnerLoopRecursive.Counter + 1 < @iterations
           ),
                DerivedKeyPerOuterLoop AS
           (
             SELECT CONVERT( varbinary(MAX), '' ) DerivedKey,
                    0 [Counter]
             UNION ALL
             SELECT DerivedKeyPerOuterLoop.DerivedKey + CONVERT( varbinary(MAX),
                                                                 CASE WHEN DerivedKeyPerOuterLoop.Counter = (( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength ) THEN LEFT(InnerLoopRecursive.uB, @derivedKeyLength - ((( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength ) - 1 ) * @hmacLength)
                                                                      ELSE InnerLoopRecursive.uB END ) DerivedKey,
                    DerivedKeyPerOuterLoop.Counter + 1
               FROM DerivedKeyPerOuterLoop
                 INNER JOIN InnerLoopRecursive
                   ON ( DerivedKeyPerOuterLoop.Counter + 1 ) = InnerLoopRecursive.OuterCount
               WHERE InnerLoopRecursive.Counter = @iterations - 1
           )
           SELECT DerivedKeyPerOuterLoop.DerivedKey
             FROM DerivedKeyPerOuterLoop
             WHERE DerivedKeyPerOuterLoop.Counter = (( @derivedKeyLength + @hmacLength - 1 ) / @hmacLength ));


Even if looping from 2 to sqrt(number) is an optimization as suggested by palacsint, you would run better by looping as long as number > 1:

for (int i = 2; number > 1; i++) {
    ...
}

Since you are only working on relatively small numbers (Integer.MAX_VALUE or less), you should also consider using a prime number table instead of trying each and every divisor from 2 to sqrt(number). There are roughly 4.800 prime numbers less than sqrt(Integer.MAX_VALUE), which cover all possible factors. Keeping them in an array of ints and testing only those numbers as possible factors should also gain some performance.

Better factorizing algorithms than this brute force approach are not known.


Perform n mongodb updates at a time using SemaphoreSlim

I see two issues with the provided code:

You are using a queue, however I only see a single call to retrieve items from the queue, when you start the application. Does this mean all the jobs are there when Run() is called?
You want to process 20 jobs at a time, but can _uploadService.Upload actually handle unlimited simultaneous requests? Or does it silently peak at something like 2 * number of cores or the size of the thread pool?


Porting stemming algorithm from Java to Python

Specific suggestions:

Python will throw an IndexError if you try to access an element past the end of a list, so you don't need to check index >= len(s) or offset > len(s).
After the simplification above I would inline the __check methods as assertions.
Throwing an exception and catching it again within the same context is a code smell - it's too much like goto. Why not just return instead? Or let the user know the input could not be processed?
You don't actually use any OOP in your code, so apply might as well not be within a class
In the same way I think you could just use a List[str] for dest.
Checking the type of an argument is unpythonic. Basically you're responsible for passing some value which can be used by the code. And with type checking (below) you could even enforce this at a test or linting stage.
Abbreviations make code harder to read. I would expand things like destination, position and command.
Magic values like R and D should be named constants to improve readability.

General suggestions:

black can automatically format your code to be more idiomatic.
isort can group and sort your imports automatically.
flake8 with a strict complexity limit will give you more hints to write idiomatic Python:

[flake8]
max-complexity = 4
ignore = W503,E203

That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place. Conversely, on an ugly old piece of code I wrote without static analysis support I recently found the complexity reaches 87!)
I would then recommend adding type hints everywhere and validating them using a strict mypy configuration:

[mypy]
check_untyped_defs = true
disallow_untyped_defs = true
ignore_missing_imports = true
no_implicit_optional = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_ignores = true

As a Java developer I'm sure you'd appreciate the clarity this lends to the code.


As written by Jonathan and

Always put a blank line after every }
Always use { } even for single line if/for/while. There is a class of errors where you add a second line in the if but it isn't "in" the if, it is outside. Something like:

if (1 == 1)
   do something

and then you change it in

if (1 == 1)
    do something
    do something else

the do something else isn't in the if, even if you spaced it like it was :-)

If you don't want to use the {} a good style that solves it is to put the second part of the instruction in the same line

if (1 == 1) do something

I don't like it very much (because it makes the line longer to the right) but it is more difficult you make the "bad" error of missing {}

The strlen can be pre-calculated once.

The if (isdigit(*s)) can be put before the malloc.

If you malloc a block of memory and then return NULL you should free the block of memory, otherwise you cause a memory leak.

Please, don't use the pre-fix/post-fix increment operator in the middle of other instructions, they make the code less readable.

This

temp[j++] = s[i++];

is the same as

temp[j] = s[i];
i++;
j++;

but the second is much more readable, because you don't have to think to the order of the operations.

If you have to decompress the string (from a4bd2g4 to aaaabddgggg) the buffer size is too much small.

Considering the compression and decompression are quite different, I would do it in two passes:

first pass: sum all the digits and count all the characters. If the sum is zero the it's compression, do it in function 1. If sum <> 0 it is decompression. With the sum of the digits and the count of the characters you know the size of the buffer you'll need.

If you want to impress your teacher, you should make it work for aaaaaaaaaa (it is 10x a)... It would compress to a9a and aaaaaaaaaaa (11x a) a9a2.


I'm pretty sure I don't understand the usage of your script, but I'll assume you have a good reason for performing this comparison.

I see that you are declaring/calling $ngram_rta = getNgrams($valor) inside your inner loop.  This means that for each word in your question string, you are asking php to do the same job to produce the same output.  You must not ask php to repeat itself.  Since $ngrame_rta is not mutated inside of the inner loop, you should generate the data inside the outer loop and count its length before entering the inner loop.

In your posted script, if($i > ($n - 2)) { is never satisfied on the first iteration.  I'll urge you to have a re-think about this condition.  Perhaps you want to make the 2 dynamic and perhaps you want to change the comparison to >=.  You decide how to avoid performing an usable iteration.

If the idea here is to break a word into an array of strings with $n length starting from each offset in the string then this seems cleaner:

(Demo)

for ($pos = strlen($match) - $n; $pos >= 0; --$pos) {
    $nGrams[] = substr($match, $pos, $n);
}

I guess your script could boil down to something like this:

(Demo)

function getNgrams($match, $n = 2) {
    $nGrams = [];
    for ($pos = strlen($match) - $n; $pos >= 0; --$pos) {
        $nGrams[] = substr($match, $pos, $n);
    }
    return $nGrams;
}

$question = 'happy birthday';
$questionNGrams = array_map("getNgrams", explode(' ', $question));

$rta = ['today', 'happy', ' tomorrow ', 'monday', 'birthda'];

foreach ($rta as $value) {
    $rtaNGram = getNgrams($value);
    $rtaNGramCount = count($rtaNGram);
    foreach ($questionNGrams as $questionNGram) {
        if (count(array_intersect($rtaNGram, $questionNGram)) / $rtaNGramCount >= 0.8) {
            echo "{$value}
";
            break;  // prevent further iteration of inner loop after $value qualifies
        }
    }
}

Output:

happy
birthda

I do find my eyes going a bit crossed as I continue to read your code because I don't relate $question and $rta to the data they contain.  Perhaps be more accurate/intentional about the variable naming.


About Version 1:

GCD(a, b) has a time complexity of \$ O(min(a, b))\$ and requires an
array for intermediate storage. You could get rid of the array by
iterating over the possible divisors in reverse order, so that you
can early return if a common divisor is found.

About Version 2:

LCM(x , y) has a time complexity of \$ O(xy)\$ and requires two
arrays for intermediate storage, so this worse than version 1.
You could improve this by pre-computing only the multiples of one number,
and then test the multiples of the other number (in reverse order)
until you find a common multiple, and then early return.

Common issues:

LCM should always return a number, your code returns the string
"0" in some cases.
Both functions take integer arguments (according to the docstring
) but do not produce sensible results for negative input.
The usage of whitespace in your code is inconsistent. Examples:

if x==0 or y == 0:
i =2

More PEP8 coding style
violations (most of them related to spacing) can be detected by checking
your code at PEP8 online.

A better algorithm

The "Euclidean Algorithm" is a well-known method for computing the greatest common
divisor, and superior to both of your approaches.

It is already available in the Python standard library:

>>> from fractions import gcd   # Python 2
>>> from math import gcd        # Python 3
>>> gcd(123, 234)
3

This should be used as the basis for implementing an LCM
function.

Have a look at https://rosettacode.org/wiki/Greatest_common_divisor#Python,
if you want to implement the GCD yourself (for educational purposes),
for example

def gcd_iter(u, v):
    while v:
        u, v = v, u % v
    return abs(u)

This is short, simple, needs no additional space, and fast:
the time complexity is (roughly) \$ =O(\log(max(a, b))\$
(see for example What is the time complexity of Euclid's Algorithm).


Assigning width and height to specify image dimension using jQuery

The reason GTMetrix complains is that the browser can render the page faster if it knows the size of the image.

Setting the size after the browser has rendered is not going to make your page faster, it will only make the warning go away and fractionally make your page load slower.

This means you will have to declare the height and width of the image on the server side, or ignore the warning of GTMetrix.


Fastest way to "Replace" "auto fill" and then loop in Excel VBA

Just indenting the code and removing the excessive whitespace you have yields something significantly more readable (after also fixing the compile-error with the non-comment after Calculate):

Sub Macro1()

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayStatusBar = False

    For i = 1 To 50
        Do
            Sheets("Sheet1").Select

            'Range("Q1:Q6").Value are random generated number using randbetween (=RANDBETWEEN(3,103))
            'save the random created value to Range("U1:U6")
            Sheet1.Range("U1:U6").Value = Sheet1.Range("Q1:Q6").Value

            Range("AA1").Select

            'Column u1 to u6 are random values generated using =RANDBETWEEN(3,103).
            'example of  Range("aa1") Pre-entered formula: =a5+b95+c48+d29+e62+f29
            'replace the "a5" in range("aa1") with "a?", with the "?" being the random number in U1.
            Selection.Replace What:="a" & Range("t1") & "+", Replacement:="a" & Range("u1") & "+", LookAt:=xlPart, _
                              SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                              ReplaceFormat:=False

            'replace the "B95" in range("aa1") with "a?", with the "?" being the random number in U2.
            Selection.Replace What:="b" & Range("t2") & "+", Replacement:="b" & Range("u2") & "+", LookAt:=xlPart, _
                              SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                              ReplaceFormat:=False

            'replace the "C48" in range("aa1") with "a?", with the "?" being the random number in U3.
            Selection.Replace What:="c" & Range("t3") & "+", Replacement:="c" & Range("u3") & "+", LookAt:=xlPart, _
                              SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                              ReplaceFormat:=False

            'replace the "D29" in range("aa1") with "a?", with the "?" being the random number in U4.
            Selection.Replace What:="d" & Range("t4") & "+", Replacement:="d" & Range("u4") & "+", LookAt:=xlPart, _
                              SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                              ReplaceFormat:=False

            'replace the "E62" in range("aa1") with "a?", with the "?" being the random number in U5.
            Selection.Replace What:="e" & Range("t5") & "+", Replacement:="e" & Range("u5") & "+", LookAt:=xlPart, _
                              SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                              ReplaceFormat:=False

            'replace the "F29" in range("aa1") with "a?", with the "?" being the random number in U6.
            Selection.Replace What:="f" & Range("t6") & ",", Replacement:="f" & Range("u6") & ",", LookAt:=xlPart, _
                              SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                              ReplaceFormat:=False

            'Autofill the modified formula in aa1 to aa1301.
            Range("AA1").AutoFill Destination:=Range("AA1:AA1301")
            'Manual re-calulate the autofills.
            'Manual re-generate the random number

            Calculate

            'Copy the number from U1:U6 (the =randbetween(3,103) to T1:T6 to save the random generated number.
            Sheet1.Range("T1:T6").Value = Sheet1.Range("U1:U6").Value

        Loop Until Range("ac3") = 1 And Range("h8") >= 8 And Range("o3") = 0 And Range("o4") <> 0
    Next i

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.DisplayStatusBar = True

    Beep
End Sub

Let's start with this.

The next step is breaking this into more manageable chunks:

Private Sub EnablePerformanceOptimizations()
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayStatusBar = False
End Sub

Putting this together with the other block at the end of your current Macro1 we get:

Private Sub PerformanceOptimizations(ByVal enable As Boolean)
    Application.Calculation = IIf(enable, xlCalculationManual, xlCalculationAutomatic)
    Application.ScreenUpdating = Not enable
    Application.EnableEvents = Not enable
    Application.DisplayStatusBar = Not enable
End Sub

Now that this is finished we can "reimagine" Macro1 as the following

Public Sub Macro1()
    PerformanceOptimizations(True)

    GenerateAndCopyRandomNumbers()

    PerformanceOptimizations(False)
End Sub

Suddenly we can see "exactly" what Macro1 does. It does performance optimizations before generating random numbers and then disables the optimizations again.

The next step is to optimize that number generation.

The code you posted here does never use the loop variable of the For Next loop. We can just completely drop that loop, which already should reduce the runtime to \$\frac{1}{50}\$ of the current runtime...

The next step is optimizing these Replace calls.

The first step towards that would usually be to get rid of Selection because that's slow. I'll ignore that for now and just reformat the code (again) just to see what's actually going on:

Private Sub GenerateAndSaveRandomNumbers()
    Do
        Sheets("Sheet1").Select

        'Range("Q1:Q6").Value are random generated number using randbetween (=RANDBETWEEN(3,103))
        'save the random created value to Range("U1:U6")
        Sheet1.Range("U1:U6").Value = Sheet1.Range("Q1:Q6").Value

        Range("AA1").Select

        'Column u1 to u6 are random values generated using =RANDBETWEEN(3,103).
        'example of  Range("aa1") Pre-entered formula: =a5+b95+c48+d29+e62+f29
        'replace the "a5" in range("aa1") with "a?", with the "?" being the random number in U1.
        Selection.Replace What:="a" & Range("t1") & "+", _
                          Replacement:="a" & Range("u1") & "+", LookAt:=xlPart, _
                          SearchOrder:=xlByRows, MatchCase:=False, _
                          SearchFormat:=False, ReplaceFormat:=False

        'replace the "B95" in range("aa1") with "a?", with the "?" being the random number in U2.
        Selection.Replace What:="b" & Range("t2") & "+", _
                          Replacement:="b" & Range("u2") & "+", LookAt:=xlPart, _
                          SearchOrder:=xlByRows, MatchCase:=False, _
                          SearchFormat:=False, ReplaceFormat:=False

        'replace the "C48" in range("aa1") with "a?", with the "?" being the random number in U3.
        Selection.Replace What:="c" & Range("t3") & "+", _
                          Replacement:="c" & Range("u3") & "+", LookAt:=xlPart, _
                          SearchOrder:=xlByRows, MatchCase:=False, _
                          SearchFormat:=False, ReplaceFormat:=False

        'replace the "D29" in range("aa1") with "a?", with the "?" being the random number in U4.
        Selection.Replace What:="d" & Range("t4") & "+", _
                          Replacement:="d" & Range("u4") & "+", LookAt:=xlPart, _
                          SearchOrder:=xlByRows, MatchCase:=False, _
                          SearchFormat:=False, ReplaceFormat:=False

        'replace the "E62" in range("aa1") with "a?", with the "?" being the random number in U5.
        Selection.Replace What:="e" & Range("t5") & "+", _
                          Replacement:="e" & Range("u5") & "+", LookAt:=xlPart, _
                          SearchOrder:=xlByRows, MatchCase:=False, _
                          SearchFormat:=False, ReplaceFormat:=False

        'replace the "F29" in range("aa1") with "a?", with the "?" being the random number in U6.
        Selection.Replace What:="f" & Range("t6") & ",", _
                          Replacement:="f" & Range("u6") & ",", LookAt:=xlPart, _
                          SearchOrder:=xlByRows, MatchCase:=False, _
                          SearchFormat:=False, ReplaceFormat:=False

        'Autofill the modified formula in aa1 to aa1301.
        Range("AA1").AutoFill Destination:=Range("AA1:AA1301")
        'Manual re-calulate the autofills.
        'Manual re-generate the random number

        Calculate

        'Copy the number from U1:U6 (the =randbetween(3,103) to T1:T6 to save the random generated number.
        Sheet1.Range("T1:T6").Value = Sheet1.Range("U1:U6").Value

    Loop Until Range("ac3") = 1 And Range("h8") >= 8 And Range("o3") = 0 And Range("o4") <> 0
End Sub()

Now since Replace has quite a bunch of optional arguments, and you're overwriting most of them with defaults or unhelpful values, let's drop them:

MatchCase defaults to False
MatchByte isn't used in your code
SearchFormat would boil down to a Falsey if you didn't pass it
ReplaceFormat same considerations as for SearchFormat apply.

Interestingly we can even go so far as to abuse the fact that LookAt, SearchOrder and MatchCase (as well as MatchByte) are "saved" between invocations to collapse all this into the following replacement calls:

        'Column u1 to u6 are random values generated using =RANDBETWEEN(3,103).
        'example of  Range("aa1") Pre-entered formula: =a5+b95+c48+d29+e62+f29
        'replace the "a5" in range("aa1") with "a?", with the "?" being the random number in U1.
        Selection.Replace What:="a" & Range("t1") & "+", _
                          Replacement:="a" & Range("u1") & "+", LookAt:=xlPart, _
                          SearchOrder:=xlByRows, MatchCase:=False

        'replace the "B95" in range("aa1") with "a?", with the "?" being the random number in U2.
        Selection.Replace What:="b" & Range("t2") & "+", _
                          Replacement:="b" & Range("u2") & "+"

        'replace the "C48" in range("aa1") with "a?", with the "?" being the random number in U3.
        Selection.Replace What:="c" & Range("t3") & "+", _
                          Replacement:="c" & Range("u3") & "+"

        'replace the "D29" in range("aa1") with "a?", with the "?" being the random number in U4.
        Selection.Replace What:="d" & Range("t4") & "+", _
                          Replacement:="d" & Range("u4") & "+"

        'replace the "E62" in range("aa1") with "a?", with the "?" being the random number in U5.
        Selection.Replace What:="e" & Range("t5") & "+", _
                          Replacement:="e" & Range("u5") & "+"

        'replace the "F29" in range("aa1") with "a?", with the "?" being the random number in U6.
        Selection.Replace What:="f" & Range("t6") & ",", _
                          Replacement:="f" & Range("u6") & ","

Continued simplfications include not using Selection and using a With block:

With Sheet1.Range("AA1")
    .Replace What:="a" & Range("t1") & "+", _
             Replacement:="a" & Range("u1") & "+", LookAt:=xlPart, _
             SearchOrder:=xlByRows, MatchCase:=False
    'replace the "B95" in range("aa1") with "a?", with the "?" being the random number in U2.
    .Replace What:="b" & Range("t2") & "+", Replacement:="b" & Range("u2") & "+"

    'replace the "C48" in range("aa1") with "a?", with the "?" being the random number in U3.
    .Replace What:="c" & Range("t3") & "+", Replacement:="c" & Range("u3") & "+"

    'replace the "D29" in range("aa1") with "a?", with the "?" being the random number in U4.
    .Replace What:="d" & Range("t4") & "+", Replacement:="d" & Range("u4") & "+"

    'replace the "E62" in range("aa1") with "a?", with the "?" being the random number in U5.
    .Replace What:="e" & Range("t5") & "+", Replacement:="e" & Range("u5") & "+"

    'replace the "F29" in range("aa1") with "a?", with the "?" being the random number in U6.
    .Replace What:="f" & Range("t6") & ",", Replacement:="f" & Range("u6") & ","

This should give you another performance boost and will continue to work, even if the user changes the Selection during the execution of the macro.


Improving JavaScript - using objects vs. just functions

If this is already your entire code, then you won't benefit much from namespacing your functions. Namespacing is basically assigning stuff to an object property. Accessing object properties is a minor overhead, but an overhead nevertheless.

Also, it doesn't look like anything else is accessing the code made for click and hover, so I'd rather place them directly into the handler instead.

You should be fine with simple functions in this case.

I'd rather concentrate more on reducing redundant code. Here's what I have done:

//$(document).ready(fn) can be shortened to $(fn)
$(function () {

  //declare variables in a function block up top
  //this is how the compiler sees them, so to avoid unexpected behavior
  //just follow suit
  var open = false
    , peek = false
    , helpBar = $(".help-bar")
    , helpIcon = $(".help-icon")
    , help = helpBar.add(helpIcon)
    ;

  //as explained, namespacing isn't an advantage at this level of code
  //and so, I have removed the functions and placed the code into the handlers

  //you can modify "this" in a function by using .call() or .apply()
  //in this case, element argument is removed and will be passed as "this"
  //this method will be explained later
  function changeRightValue(amount, speed) {
    this.animate({
      right: amount
    }, speed);
  }

  function toggleArrow(direction) {
    helpIcon.css("background", "url('/images/buttons/zapp/arrow" + direction + ".png') no-repeat 0px 50%");
  }

  //here we have our merged functions

  helpBar.on('click',function () {

    //if blocks that call the same functions but differ in parameters are messy
    //what I did here is made ternary ifs to pick arguments, not pick invocations
    //the calls will be made later
    var changeRightParams = open ? [0, 'slow'] : [280, 'fast']
      , direction = open ? 'Open' : 'Close'
      //this is a very short way to toggle booleans in the same variable
      , open = !open
      ;

    //here we call the functions with the "picked" arguments

    //here we use .apply to set the invoked function's this as help
    //and the arguments as the picked arguments
    //it's the same as calling "help.changeRightValue(amount,speed)
    changeRightValue.apply(help, changeRightParams);
    toggleArrow(direction);

  }).on('hover',function () {

    //like above, declare variables up top to avoid unexpected behavior
    var changeRightParams;

    //here we use the "early return" pattern, to avoid nesting ifs
    //since nothing executes when open is true, we return early
    //we saved 1 indent level in the code
    if (open) return;

    //code after the early return assumes "open" is false
    //it would be similar to if(!open){/*stuff here*/}

    help.stop();

    //same as above, we pick arguments, toggle the boolean, call with the selected
    changeRightParams = peek ? [0, 'fast'] : [5, 'slow'];
    peek = !peek
    changeRightValue.apply(help, changeRightParams);

  });
});


String permutation iterative improvements?

Descriptive naming

Set<String> perm(String input)

I would call this

Set<String> permute(String input)

When I see perm, my first thought is someone making straight hair curly.  My second thought is that it might be short for permanent.  Well after that I realize that in this context, you are permuting things.  In my opinion, the extra three letters increases readability greatly.

   Set<String> perm = new HashSet<String>();

Ignoring the confusion with naming a variable the same as the method using it, I'd go with

    Set<String> permutations = new HashSet<>();

Now I know what's supposed to be in there.

Unless you are compiling against an old Java version, you don't need to write out String the second time.  The compiler will figure it out.

Avoid casts

    char[] arr = input.toCharArray();

While this often helps when processing something character by character, I don't think it does so here.

    perm.add(String.valueOf(arr[0]));

This could be

    permutations.add(input.substr(0, 1));

So rather than converting from a String to a character array, then getting one character, then converting that character to a String, we just take a single character substr which returns the String that we want.  Since a String is immutable, this can use the original backing array to hold the data.  The other version would likely allocate new memory because it's not obvious that it's just taking a substring.

But even better might be

   permutations.add("");

Then we can simplify the gating test to just check for null.  And we can put the rest of the logic in the loop.

    for (char current : input.toCharArray())
    {
        permutations = permute(current, permutations);
    }

Yes, I did change the name of findPerm, and I changed it to take a character rather than a String.  I didn't like the name findPerm because you aren't finding anything.  You are generating permutations.

If we change the first parameter to be a character rather than a String, we can use it as a character later.

The other version may be slightly more efficient, but at the cost of additional coding complexity.

And now we are processing the String character by character, so we convert it to a character array.  We don't need i, as we can work with the characters directly.

Don't do unnecessary work

You have

    Set<String> perms = new HashSet<String>(perm);

and

        perms.remove(each);

But if you change the first to

    Set<String> permutations = new HashSet<String>();

Then you don't need the second line.  There is no reason to put the partial permutations in the results.

Don't Repeat Yourself (DRY)

        perms.addAll(addAtEachIndex(each, next));

So addAtEachIndex creates a Set just to return it and add to another Set.  Why bother?

        addAtEachIndex(each, next, permutations);

If we pass the Set into the method, we can add to it directly.  So we check for duplicates once, not twice.

Choose your datatype

        finalPerms.add(each.substring(0,i+1) + next +each.substring(i+1, each.length()));

You are doing a lot of String manipulation in this section and it's not really necessary.  Consider what happens if you leave next as a character rather than a String.

    StringBuilder permutation = new StringBuilder(each);
    permutation.append(next);

    permutations.add(permutation.toString());
    for (int i = each.length(); i > 0; i--)
    {
        permutation.setCharAt(i, permutation.charAt(i - 1));
        permutation.setCharAt(i - 1, next);
        permutations.add(permutation.toString());
    }

This also works with a StringBuilder rather than a String.

Now, rather than copying two substrings and a single character String into a new String, we only copy once.  We do three character operations rather than five String operations.  And we can keep reusing the same StringBuilder as a base.

Summary

public static Set<String> permute(String input)
{
    Set<String> permutations = new HashSet<String>();
    if (input == null)
    {
        permutations.add(input);
        return permutations;
    }

    permutations.add("");

    for (char current : input.toCharArray())
    {
        permutations = _permute(current, permutations);
    }

    return permutations;
}

private static Set<String> _permute(char next, Set<String> partials)
{
    Set<String> permutations = new HashSet<String>();

    for (String partial : partials)
    {
        addAtEachIndex(partial, next, permutations);
    }

    return permutations;
}

private static void addAtEachIndex(String partial, char next, Set<String> permutations)
{
    StringBuilder permutation = new StringBuilder(partial);
    permutation.append(next);

    permutations.add(permutation.toString());
    for (int i = partial.length(); i > 0; i--)
    {
        permutation.setCharAt(i, permutation.charAt(i - 1));
        permutation.setCharAt(i - 1, next);
        permutations.add(permutation.toString());
    }
}

I also made all the methods static as they weren't using any object state.

Time complexity

If we call the outer permute once, we call the inner _permute about \$n\$ times, where \$n\$ is the length of the input.

The first time we call the inner _permute, it calls addAtEachIndex once.  The second time, once.  The third time, twice.  So on the \$i\$th time, we call it \$(i-1)!\$ times if there are no duplicate characters in the String.  If there are duplicate characters, we call it fewer times.

The first time that we call the inner _permute, each call to addAtEachIndex iterates 0 times.  The second time, one time.  The third time, twice.  The fourth time, six iterations.  Yep, \$(i - 1)!\$ again.

Perhaps the simplest way to think about this are that there are \$n+1\$ steps to find the permutations.  On the \$i\$th step, we generate \$(i-1)!\$ permutations.  So for a given input length of \$n\$, we generate \$ \sum_{i=0}^{n} i! \$ permutations.  But that's just \$\mathcal{O}(n!)\$ because it is smaller than \$ (n+1)!\$ which is \$\mathcal{O}(n!)\$.

This is as efficient as we can get asymptotically, as there are \$n!\$ results.  And we must generate each one.


Calculating multiple car prices from a file

Your ArrayList and HashMap declarations are missing type arguments. Assuming if you're developing on Java 7 then all you're missing is just the diamond operator, e.g. ArrayList<>().

Company t = new Company();
t.setName("Benz");
t.setPrice(10000);
trn.add(t);
t = null;
t = new Company();
t.setName("BMW");
t.setPrice(3000);
trn.add(t);
t = null;
t = new Company();
t.setName("Benz");
t.setPrice(1000);
trn.add(t);
t = null;
t = new Company();
t.setName("Toyota");
t.setPrice(500);
trn.add(t);

This is an odd way of adding four objects into your List. Assuming if your Company object has the following simple constructor, you should do it as such:

trn.add(new Company("Benz", 10000));
trn.add(new Company("BMW", 3000));
trn.add(new Company("Benz", 1000));
trn.add(new Company("Toyota", 500));

Instead of a nested for loop and skipping entries that already exist in the result map, you can consider retrieving the existing calculated sum from the map, if any, and add the current price to that. Also, why is map created as Map<String, String> and not Map<String, Integer> or Map<Company, Integer>?

One more thing, you can consider putting this particular comparison as a method in your Company class: com.getName().equalsIgnoreCase(name).


Thread-safe stack in Java with fixed capacity

Looks good to me on a cursory glance. It's pretty much the exact same code as in java.util.concurrent.locks.Condition JavaDoc.

The only definitive problem I see is the catching and logging of InterruptedException. The code acts towards the caller as if the operation succeeded while nothing was done.

Not providing a way to set the maximum wait time will be a limitation in a library intended for generic use.

Stylistically, private int max should be final to emphasize that it must not be changed after initialization (as changing it when threads are waiting would cause serious problems).

Another thing, which may be a matter of taste, is the stack.size() == max comparison. I always like to use >= where a size is compared to a maximum limit (with a comment, of course). This gives an extra safeguard against infinite loops in the case where a programming error causes the collection to exceed maximum size.


Java program that relaunches itself in OS's terminal application

A few empty lines here and there would do wonders to the readability.

This will also relaunch the application if it was started from a terminal without arguments.

String path = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();

String os = System.getProperty("os.name").toLowerCase();
...
if(os.contains("mac")){

Unfortunately that is a quite fragile way to detect the current operating system, but it will do.

On nay other operating system, you simply start reading commands (or not), are you aware of that?

You should have the command reading in an else branch.

System.exit(0);

Please stop sprinkling your code with those. System.exit makes the JVM exit immediately, it is like a SIGKILL on UNIX. That means that not even final branches are being run when invoked.

while(true)
    nextCommand();

I assume that there is a "quit" command which calls System.exit, that might be a bad idea. A better idea would be to have something like this:

while(commandExecutor.isActive()) {
    commandExecutor.readAndExecuteCommand());
}


Select records between the first and last time the speed was positive

First of all a style comment: Please use longer descriptive names. Stuff like $q3, $q2, is just ugly, and confusing.

You could simplify your query either by using subqueries in the WHERE clause, or by creating a temporary table in the FROM clause. You could use the BETWEEN operator, but some think BETWEEN is evil as it is somewhat unclear from the wording whether the range is inclusive or exclusive. In addition if used on date fields, you could have various interesting rounding errors. So it better to stick with ordinary operators.

I've commented upon the fact that you'll have a potential issue related to order, and I haven't compensated for that in the following code, only assuming that rows are indeed ordered by id. This could/should possibly be enforced. Here is the SQL code to get your rows in one go:

SELECT tableX.* FROM tableX,
  ( SELECT min(id) as startId, max(id) as endId FROM tableX
     WHERE speed > 0 AND date = '2015-01-01' ) tmp
 WHERE id >= tmp.startId AND id <= tmp.endId

Note that in the temporary table select I chosen a given date, instead of ordering by date (which most likely would throw of the id part quite easily. Another option could be to specify a double order like in ORDER BY date, id.

Untested version translated into php-code:

$speed_query = $db_connection->prepare(
   "SELECT tableX.* FROM tableX,
     ( SELECT min(id) as startId, max(id) as endId FROM tableX
        WHERE speed > 0 AND date = '$date' ) tmp
   WHERE id >= tmp.startId AND id <= tmp.endId ");
$speed_query->execute();
while($row = $speed_query->fetch()) {
   ... do something useful with $row ...
}

The advantage of this method is that you now get all of your data from one single query, and one roundtrip from your code base to the database engine. Using subqueries like this shouldn't be to expensive, and at least when comparing to making several roundtrips it is a way better solution.

PS! You could consider using heredocs or other variations to get the
multiline string in your query. But do try to break it over multiple lines
to enhance the readability of the SQL query. See
PHP string doc for
various option on how to use strings in PHP.


Finding the first and last IP in an IP range string

The first thing that jumps out at me is that this is a single function, with no classes and only one possible use. But without context, I couldn't comment on whether or not that's good. Since the snippet is so short and limited, your only motivation for changing it is that you might want to use it in a larger context. So I'm going to assume a larger context which may or may not apply.

The second thing, then, is that there are no comments. I can look at this code, see the ipV is 4 or 6, see "Start IP" and "End IP", and figure out that this is computing an IP address range for IPv4. But the function name doesn't really tell me that. Just for maintainability sake, you might want to do something about that.

The third thing that jumps out at me is that this function does nothing useful. It has two (conditionally 3) print statements as side effects, which means that you can't use these results. You might want to separate the computation of the range from the printing of the results. This is where I have to assume a larger context. If you just want to print those 2 or 3 lines, why bother modifying working code to begin with other than to maybe add some comments for the future. What if you want to accept ranges (10.0.1.5-50)? Heck, what if you want ranges with holes (10.0.5-10.2-100)?

Fourth, your variable i is the index of item in the loop, which is used in a lot of logic in your function. See https://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops for some discussion on that. Specifically, don't manage your own loop index variable. I see why you are doing so; to loop the necessary times between 1.* and 1.1.*. You can do this a few different ways. Statically, you need 4 parts to your IPv4 addresses. You could iterate over the range 4 and generate these 4 parts. You could iterate over your input parts and append the missing parts as needed once complete. I don't actually have a strong opinion of the right way, only that your way looks funny to me.

Fifth, tempSIP. important? used?

Punchline without assuming a larger context: Add a comment about usage. Add a comment about the program logic. Rename the function to have IP in the name. Delete tempSIP.


Find matching dictionary words given a Scrabble tray

The way to use a trie here is to sort the letters of each dictionary word:

[ AD, ADD, DAD ] becomes A > D [ ad ] > D [ add, dad ]

Then walk the trie and stop descending when isWordInTray returns false.

Worst-case complexity is unchanged (arguably worse, since sorting time is not linear); actual runtime is greatly improved.


Tentative answer...

First of all, it looks like you didn't include the source of the full Author class. Where is the list of Books for that author, for instance?

Second: you seem to want methods to sort this inner list of books for a given author; why, then, pass the id of the author as an argument? You should have a lookup method for an Author given its id -- but this lookup method should not be a method of one Author instance; at worst, it should be a static method in the Author class. What is your backend like? How do you look up an author by its id eventually?

Third: the JDK has Collections.sort(); and given that you want to have a sorted list of books according to several criteria, you want to write several Comparators for that book. See below for a solution to that.

Fourth, and not the least: you should not operate on the list in the Author class itself, but on a copy of that list.

Given these four points above, here are some code extracts...

First: how to return a List<Book> from an author -- don't return the list itself but at least an unmodifiable version of it:

// in class Author; it is supposed that the list has name "bookList" in the class
public List<Book> getBookList()
{
    return new Collections.unmodifiableList(bookList); // not modifiable!
}

Second: you want book lists sorted in various ways; one solution is to create an enum:

public enum BookSort
{
    BY_NAME (new Comparator<Book>()
    {
        @Override
        public int compare(final Book a, final Book b)
        {
            return a.getName().compareTo(b.getName());
        }
    }),
    // other values

    private final Comparator<Book> comparator;

    BookSort(final Comparator<Book> comparator)
    {
        this.comparator = comparator;
    }

    // Return a sorted copy of books
    public List<Book> sort(final List<Book> list)
    {
        final List<Book> ret = new ArrayList<Book>(list);
        Collections.sort(ret, comparator);
        return ret;
    }
}

Then, in your code:

final List<Book> sorted = BookSort.BY_NAME.sort(original);

But all this code is moot to begin with if you do not provide the full code of both the Author and Book class; along with the existing mechanism to grab instances of these two classes.


Which is a better implementation of a stack data structure (based on an array)?

push() and pop() have an asymmetry that should be reconciled.  push() does not indicate any thing special when the stack is full and a push is attempted.  It silently does not do the push.  Yet when an pop of an emty stack occurs, a NULL is returned (versus a pointer to int) allowing the calling routine to take evasive action.  A symmetric solution would both do something special - or not - on full/empty.
A function to inspect the top of stack, without popping, could be added.  This IMO would be useful.  Additional routines to report current stack depth or stack space left are something to consider.
Using unsigned int is OK, especially if the fixed array size is known to always be less than UINT_MAX.  I favor size_t for array indexing as it has better portability for large arrays.
A way to deal with popping or inspecting an empty stack is, as part of initialize(), to pass an int as the bottom-of-stack.  This value does not actually ever get "popped off".
The names of the functions are too generic ("initialize") and could well collide with other code.  Suggest something like Stack_initialize(), and Stack_push().
The OO part of me wants to see a copy and destructor function too.  The destructor could simple do count = max = 0;


Welcome to CodeReview.  What you are trying to do is simple enough that your LINQ implementation is okay.  Let's face it, with dominoes you are not going to have a million players with a million bones, so no need to worry about performance issues with a fairly small set.

You didn't ask explicitly for review of other parts of code, but I will offer them anyway.

Name could be a read-only property set only in the constructor.

You have Bones as a field, not a property.  It could be exposed as a public IReadOnlyList, and it probably should be a property.

Bone could be a struct or a class since it only has 2 int properties.  I do not like the names X and Y as I tend to think of Cartesian coordinates and therefore a location.  I would prefer to see names like Square1 and Square2.  I would probably keep this as a class and make the properties readonly as well.  You may consider adding extra properties such as IsDouble, and even override ToString() with $"{Square1}-{Square2}", and maybe even Pips which is a sum of both squares.

As you are new to CR, since I have posted an answer, do NOT alter your code in your question or else a moderator will roll it back.


Game of Life search program for Herschel-generating baits

Iterations

The pythonic way to iterate is to use the for keyword, usually without bothering about indices. I suggest you have a look at the presentation : Ned Batchelder: Loop like a native: while, for, iterators, generators (PyCon US) (video on Youtube/text with slides).

In your case, most loops can be rewritten. For instance :

n = 0
while n < testrect[2]:
    m = 0
    while m < testrect[3]:
        o = 0
        while o < len(stillLifes):
            testReaction(n + testrect[0], m + testrect[1], o)
            o += 1
        m += 1
    n += 1

could be written :

for n in range(testrect[2])
    for m in range(testrect[3]):
        for o, _ in enumerate(stillLifes):
            testReaction(n + testrect[0], m + testrect[1], o)

Also, the for loop accepts an optional else block after it which is called when the loop exited with no break (just because the thing we are iterating over has been fully consumed). This can be useful to rewrite :

i = 0
while i < 301:
    g.step()
    for y in herschels:
        if g.getcells(g.getrect()) == y:
            break
    i += 1
if i == 301:
    g.show("No result found at x:" + str(xpos) + ", y:" + str(ypos) + ", still life " + str(sli))

in a more straightforward way (and without repeating 301 in 2 places) :

for i in range(300)
    g.step()
    for y in herschels:
        if g.getcells(g.getrect()) == y:
            break
else:
    g.show("No result found at x:" + str(xpos) + ", y:" + str(ypos) + ", still life " + str(sli))

Disclaimer for the snipper above: I may have misread your original code so this might be wrong.

User input

At the moment, there are a few issues with the way you deal with user input.

you have to provide "HRF v0.1" several times.

You could write a function to hide implementation details and remove duplicated logic :

def get_user_string(prompt, initial):
    title = "HRF v0.1"
    return g.getstring(prompt, initial, title)

You are calling lower() on the same string multiple times. If only the lowercase version of the string is interesting to you, you could simple do : addAnother = get_user_string("Add another result desired? (y|n)", "n").lower().
You have logic to ask boolean input and check it in multiple places
Your program stops in case of invalid logic, it might be better to ask the user to re-input something.

In order to fix these issues, you could define something like :

def get_user_string(prompt, initial):
    title = "HRF v0.1"
    return g.getstring(prompt, initial, title)

def get_user_bool(prompt, initial):
    while True:
        string = get_user_string(prompt, initial).lower()
        if string == "n":
            return False:
        elif string == "y":
            return True
        else:
            golly.error("Invalid input.")

That you could use like this :

    addAnother = get_user_bool("Add another result desired? (y|n)", "n")
    if not addAnother:
        break

or this :

if get_user_bool("Debug mode? (y|n)", "n"):
    g.autoupdate(True)

This shows a better Separation of concerns.

Code organisation

Instead of dealing with global variables, it would be cleaner to try to find alternatives. In your case, using function argument and return values should make things clearer.

You could define :

def get_user_still_lifes():
    stillLifes = []
    while True:
        stillLife = get_user_string("What still life to test for? (RLE)", "2o$2o!")
        stillLifes.append(g.parse(stillLife))
        if not get_user_bool("Add another still life? (y|n)", "n"):
            break
    return stillLifes

def get_user_desired_results():
    herschels = []
    while True:
        herschelDesired = get_user_string("What result to find? (RLE)", "3o$obo$obo!")
        herschels.append(g.parse(herschelDesired))
        if not get_user_bool("Add another result desired? (y|n)", "n"):
            break
    return herschels

and use it like this :

stillLifes = get_user_still_lifes()
herschels = get_user_desired_results()

Also it is a good habit to put the part of your code actually doing things behind an if __name__ == "__main__" guard.

Style

Python has a style guide called PEP 8. It is an interesting read and it is probably worth trying to follow it if you don't have a good reason not to. For instance, your code does not follow the naming convention. You'll find various tools to check your code compliancy to PEP 8.

Final (untested) code

The following code has not been tested, feel free to edit it to fix errors and typos I may have introduced.

import golly as g
from sys import exit

def get_user_string(prompt, initial):
    title = "HRF v0.1"
    return g.getstring(prompt, initial, title)

def get_user_bool(prompt, initial):
    while True:
        string = get_user_string(prompt, initial).lower()
        if string == "n":
            return False:
        elif string == "y":
            return True
        else:
            golly.error("Invalid input.")

def get_user_rectangle():
    while True:
        rect = g.getselrect();
        if rect == []:
            golly.error("Select the area where the still life is placeable!")
        elif g.empty():
            g.error("There is no pattern to add bait!")
        else:
            return rect

def get_user_still_lifes():
    still_lifes = []
    while True:
        stillLife = get_user_string("What still life to test for? (RLE)", "2o$2o!")
        still_lifes.append(g.parse(stillLife))
        if not get_user_bool("Add another still life? (y|n)", "n"):
            break
    return still_lifes

def get_user_desired_results():
    herschels = []
    while True:
        herschelDesired = get_user_string("What result to find? (RLE)", "3o$obo$obo!")
        herschels.append(g.parse(herschelDesired))
        if not get_user_bool("Add another result desired? (y|n)", "n"):
            break
    return herschels

def test_reaction(still_lifes, herschels, xpos, ypos, sli):
    orig = g.getcells(g.getrect())
    g.putcells(still_lifes[sli], xpos, ypos)
    this = g.getcells(g.getrect())
    oldgeneration = g.getgen()
    for i in range(300)
        g.step()
        for y in herschels:
            if g.getcells(g.getrect()) == y:
                break
    else:
        g.show("No result found at x:" + str(xpos) + ", y:" + str(ypos) + ", still life " + str(sli))
    g.clear(0)
    g.clear(1)
    if i == 301:
        this = g.putcells(orig)
    else:A
        g.show("Found reaction!")
        g.putcells(this)
    g.setgen(oldgeneration)

if __name__ == "__main__":
    testrect = get_user_rectangle()
    still_lifes = get_user_still_lifes()
    herschels = get_user_desired_results()
    if get_user_bool("Debug mode? (y|n)", "n"):
        g.autoupdate(True)

    for n in range(testrect[2])
        for m in range(testrect[3]):
        for o, _ in enumerate(still_lifes):
            test_reaction(still_lifes, herschels, n + testrect[0], m + testrect[1], o)


Before dealing with your main question here, which concerns the SVG rectangles, here are some advices:

Use an ordinal scale for the colors: instead of manipulating document.styleSheets and using classes, as you're doing right now, just create a proper ordinal scale...

var colorScale = d3.scaleOrdinal(d3.schemeCategory10);

... and use it to fill your rectangles, with style("fill", ...) method.
Don't call your scales x and y. Use more descriptive names, like xScale and yScale. Doing that, you avoid confusion with the x and y methods which are very common in D3, like in line generators or area generators, for instance.
Use d3.max in your yScale domain:

.domain([0, d3.max(transformedData, function(d) {
    return d.cumT
})])

The default domain in a D3 linear scale is ([0, 1]). Therefore, you don't need to set it in your yScale.

Back to your main issue:

Using a stack generator is "messy", according to you. However, "messy" is quite opinion based: for instance, I don't see anything messy here (except for those classes, which you don't need if you follow my advice about the color scale).

But if you still feel that using a stack generator creates a messy code here is my solution, using your non-stacked data array. First, pass your data array directly to the <g> elements as the data:

var g = maing.selectAll('g')
    .data(transformedData)
    .enter()
    .append('g');

Then, create the lower and upper rectangles using a each:

g.each(function(d, i){
    //code here
});

Inside the each you need two selections, one for the upper rectangles and other for the lower rectangles:

//these are the upper rectangles
var upperRect = d3.select(this).append("rect")
    .attr("x", function() {
        return xScale(d.cumT - d.t)
    })
    .attr("y", yScale(0))
    .attr("width", function() {
        return xScale(d.t)
    })
    .attr("height", function() {
        return yScale(d.p / d.t)
    })
    .style("fill", function() {
        return colorScale(i)
    })
    .style("opacity", .8);

//and these are the lower rectangles
var lowerRect = d3.select(this).append("rect")
    .attr("x", function() {
        return xScale(d.cumT - d.t)
    })
    .attr("y", yScale(d.p / d.t))
    .attr("width", function() {
        return xScale(d.t)
    })
    .attr("height", function() {
        return yScale(d.h / d.t)
    })
    .style("fill", function() {
        return colorScale(i)
    })
    .style("opacity", .6);

And here is the demo with those modifications:

var body = d3.select('body');
var svg = body.append('svg').attr('height', 200).attr('width', 500);
var maing = svg.append('g');

var inputData = JSON.parse('{"a":[20,10],"b":[50,0],"c":[45,60],"d":[10,40]}')

// generate class
var colorScale = d3.scaleOrdinal(d3.schemeCategory10);

// convert to flattened array
var vals = Array("p", "h");
var cumT = +0
var transformedData = Object.keys(inputData).map(function(d, i) {
  let o = {};
  o.mp = d;
  inputData[d].forEach(function(d, i) {
    o[vals[i]] = d
  })
  o.t = o.p + o.h;
  return o;
}).sort(function(a, b) {
  return b.t - a.t
}).map(function(d, i) {
  let o = d;
  o.cumT = cumT += d.t
  return o;
});

var g = maing.selectAll('g')
  .data(transformedData)
  .enter()
  .append('g')

var xScale = d3.scaleLinear()
  .domain([0, d3.max(transformedData, function(d) {
    return d.cumT
  })])
  .range([0, 100]);
// TODO: use d3.max here
var yScale = d3.scaleLinear()
  .range([0, 140]) // some predefined height

g.each(function(d, i) {
  var upperRect = d3.select(this).append("rect")
    .attr("x", function() {
      return xScale(d.cumT - d.t)
    })
    .attr("y", yScale(0))
    .attr("width", function() {
      return xScale(d.t)
    })
    .attr("height", function() {
      return yScale(d.p / d.t)
    })
    .style("fill", function() {
      return colorScale(i)
    })
    .style("opacity", .8);

  var lowerRect = d3.select(this).append("rect")
    .attr("x", function() {
      return xScale(d.cumT - d.t)
    })
    .attr("y", yScale(d.p / d.t))
    .attr("width", function() {
      return xScale(d.t)
    })
    .attr("height", function() {
      return yScale(d.h / d.t)
    })
    .style("fill", function() {
      return colorScale(i)
    })
    .style("opacity", .6);
})
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>

The colors are different from your snippet because, in your snippet, you're creating the array first and sorting later. But this is easy to change, if you want:

var body = d3.select('body');
var svg = body.append('svg').attr('height', 200).attr('width', 500);
var maing = svg.append('g');

var inputData = JSON.parse('{"a":[20,10],"b":[50,0],"c":[45,60],"d":[10,40]}');

// generate class
var colorScale = d3.scaleOrdinal(d3.schemeCategory10);

// convert to flattened array
var vals = Array("p", "h");
var cumT = +0
var transformedData = Object.keys(inputData).map(function(d, i) {
  let o = {};
  o.mp = d;
  inputData[d].forEach(function(d, i) {
    o[vals[i]] = d
  })
  o.t = o.p + o.h;
  return o;
}).sort(function(a, b) {
  return b.t - a.t
}).map(function(d, i) {
  let o = d;
  o.cumT = cumT += d.t
  return o;
});

colorScale.domain(Object.keys(inputData));

var g = maing.selectAll('g')
  .data(transformedData)
  .enter()
  .append('g')

var xScale = d3.scaleLinear()
  .domain([0, d3.max(transformedData, function(d) {
    return d.cumT
  })])
  .range([0, 100]);
// TODO: use d3.max here
var yScale = d3.scaleLinear()
  .range([0, 140]) // some predefined height

g.each(function(d, i) {
  var upperRect = d3.select(this).append("rect")
    .attr("x", function() {
      return xScale(d.cumT - d.t)
    })
    .attr("y", yScale(0))
    .attr("width", function() {
      return xScale(d.t)
    })
    .attr("height", function() {
      return yScale(d.p / d.t)
    })
    .style("fill", function(d) {
      return colorScale(d.mp)
    })
    .style("opacity", .8);

  var lowerRect = d3.select(this).append("rect")
    .attr("x", function() {
      return xScale(d.cumT - d.t)
    })
    .attr("y", yScale(d.p / d.t))
    .attr("width", function() {
      return xScale(d.t)
    })
    .attr("height", function() {
      return yScale(d.h / d.t)
    })
    .style("fill", function(d) {
      return colorScale(d.mp)
    })
    .style("opacity", .6);
})
<script src="https://d3js.org/d3.v4.min.js"></script>

Finally, have in mind that the stack generator, despite being complicated, is the best approach if you have several rectangles per column. In my solution, I have two selections inside the each... however, if you had 5 rectangles per column, we would have 5 selections inside the each, and so on, which is a lot of duplicated code.


I found a list a few things that you could improve, but nothing that would significantly change the way your sorts work:

At the end of the counting sort, you could use std::move instead of std::copy to move the elements to the original collection. For simple integers, it shouldn't change anything but it could make a significant difference if you try to sort big integers.
There is a more idiomatic way to compute sizeof(typename Iter::value_type)*CHAR_BIT in the standard library thanks to std::numeric_limits::digits, so you can actually rewrite rdx_sort as follows:

template <typename Iter>   // range of input not known, just use max ex. 32 bits for ints
void rdx_sort(Iter begin, Iter end) {
    int bits {std::numeric_limits<typename Iter::value_type>::digits};
    rdx_sort(begin, end, bits);
}

Any number library (like a big number library) is allowed to specialize std::numeric_limits and every decent numbers library does so, so I shouldn't make your code less portable. By the way, the returned value is not always int, so the best thing you could do is to use a type alias to make things clearer:

template <typename Iter>   // range of input not known, just use max ex. 32 bits for ints
void rdx_sort(Iter begin, Iter end) {
    using value_type = typename Iter::value_type
    value_type bits {std::numeric_limits<value_type>::digits};
    rdx_sort(begin, end, bits);
}

Be careful of wild assumptions:

const long long mask; // 0..63 bitfield to test against

long long is not guaranteed to be a 64-bit integer, even if it is more often the case than not. If you want to avoid problems, you should use std::int64_t from <cstdint>. This type only exists if the architecture actually has a 64-bit integer, bug I guess that you will have more problems anyway if your implementation does not.

const std::int64_t mask; // 0..63 bitfield to test against

It seems that you are using using namespace std;, which is something you should really avoid in a header-only library like yours. Using this directive will import every name from std:: into the global namespace for anyone using your library and you will for sure end with name clashes at some point. Consider std::-qualifying everything from the C and C++ standard libraries (except macros of course), even std::size_t: some implementations don't import the names from the C standard library into the global namespace.
Dropping random vowels from function names isn't going to help anymore. Consider using full names like counting_sort and radix_sort instead.


Since the code is only reading the contents of the file to see if there are contents in the file, an optimization for both speed and memory usage would be to use the filesize() function and not read the contents. Reading the contents of the file consumes both time and memory.
Rather than writing the contents read in, copy or move the original file to the new location using either rename() or move_uploaded_file().


Namespace std
Stop doing this:
using namespace std;

See every other C++ code review and Why is “using namespace std;” considered bad practice?
Monolithic Functions
Break your code into multiple smaller functions. A good rule of thumb is no more than a dozen lines. If you give your function meaningful names then your code becomes self documenting.
Global Variables
Global variables are a bad idea. It makes testing hard. It makes debugging hard. You don't the result of the function biased on its inputs (it also depends on some other external global state that other functions may mutate while you are not watching.
Pass parameters to functions that should be the only state the worry about.
Objects
This looks like it should be an object:
map<string, food> foodMap_prot;
map<string, food> foodMap_carb;
map<string, food> foodMap_fat;

How about
class FoodMap
{
    typedef  std::map<std::string, Food>  FoodMap;

    FoodMap   protein;     // avoid the temptation to shorten names
    FoodMap   carbs;       // unless like this they are hard to spell.
    FoodMap   fat;
};

// Note on naming conventions.
// User defined types (usually) start with an Uppercase letters.
// Object usually start with a lowercase letter.
// This makes it easy to spot types over objects.

Looks like all the code in your main is designed to correctly fill up the map. So this should really be part of the FoodMap class. The class should be the only thing defining where things go internally. If you let functions (like main) fill up the map you have no control to validate input.


Is this a good way of writing contains method in Java?

Neither is best. The best would be:
boolean contains(Topic t){
    return t != null && t.equals(root);
}

Using equals is better than using the properties of Topic, because of Single Responsibility Principle
If that was too fast for you:
Step 1:
if (t.x == root.x && t.y == root.y)

Using t.equals(root) is better. It is likely that you want to do this comparison in more than one method between two variables of Topic, in which case you don't want to duplicate code.
Step 2:
if (condition)
    return true;
else
    return false;

condition is a boolean. You return a boolean. You might as well just return condition directly.
Now, using single-line if-statements without braces can lead to bugs when you suddenly introduce a new line without remembering to add braces. Apple has done this mistake, and so can you.
With the steps taken so far we have:
boolean contains(Topic t) {
    if (t == null) {
        return false;
    }
    return t.equals(root);
}

Final step:
Use boolean short-circuiting && operator to return in only one line, while still having it readable (at least readable for those who are somewhat experienced with boolean logic, which most programmers hopefully are)
So again, the best version:
boolean contains(Topic t) {
    return t != null && t.equals(root);
}


Elegantly exclude part of an operation for the last iteration in a loop

If you are just doing a single-shot printing of a container, just print the first element and then print delim-value pairs.  This reduces the iterator requirements to being equality comparable, dereferenceable, and incrementable.

if (!vec.empty()) {  // invert to return immediately if this is a function
    auto first = vec.cbegin();
    std::cout << *first;

    while (vec.cend() != ++first) {
        std::cout << ", " << *first;
    }
}

There is also a stateful approach that reduces the operation strength from branching on whether to print the delimiter to a pointer assignment.

auto actual_delim = ", ";
auto delim = "";

for (const auto& elem : vec) {
    std::cout << delim << elem;
    delim = actual_delim;
}

See infix_iterator where this stateful approach is used.


A function that replicates DLookup, and can use parameterized queries

I'm going to cover other points that aren't covered...

Unnecessary recordset movement

You have this:

If rs.RecordCount Then
    rs.MoveFirst
    rs.MoveLast
    rs.MoveFirst
    ...
End If

This is totally unnecessary and also problematic:

RecordCount is not the most idiomatic way of checking for an empty. EOF is more common and is usually effective. It also works in both DAO and ADO; I'm a big advocate of writing code that is portable and consistent; it means less thing to remembers and less surprises when one quirky thing that works in one library doesn't in other.
MoveLast in order to get a count. You already know that RecordCount doesn't return accurate count until you've accessed all records in the recordset. But the more important question to ask yourself is: Did you really need that? I assert that 99% of time you don't. You have two options at your disposal:

1) Use GetRows method to extract an array out of recordset.

2) Use either a VBA.Collection or Scripting.Dictionary and stop caring about how many records there are; just use a Do Until rs.EOF loop and insert it into the dynamic collection variable.

The point being, you do not need to know the count of the records to do what you need. Eliminate that from your procedure and it becomes much more simpler and also less error-prone.

Do loop instead of For loop

In similar vein you have this code:

For i = 0 To rs.RecordCount - 1
    out(i) = rs.Fields(0).Value
    rs.MoveNext
Next

You need to stop caring about how many iterations you need to do. This is much less verbose and easier to understand:

Do Until rs.EOF
    'do something
    rs.MoveNext
Loop

No local variables is needed just to iterate; nor do you need to care about count to iterate. You just keep iterating until.... you get to the end!

Unnecessary branching

Others already commented on the need to extract functionality into smaller functions and I fully agree. I want to call your attention to this:

    If rs.RecordCount > 1 Then
        If rs.Fields.count > 1 Then
            ReDim out(rs.RecordCount - 1, rs.Fields.count - 1)
            For i = 0 To rs.RecordCount - 1
                ...
            Next
        Else
            ReDim out(rs.RecordCount - 1)
            For i = 0 To rs.RecordCount - 1
                ...
            Next
        End If
        ...
    Else
        If rs.Fields.count > 1 Then
            ReDim out(rs.RecordCount - 1, rs.Fields.count - 1)
            For i = 0 To rs.RecordCount - 1
                ...
            Next
            ...
        Else
            ...
        End If
    End If

Note how all branch, except for very last one basically do the same thing. In fact, the last one is only special since it's only one column. But do we really care? I say no. All you really want to do is this:

Do Until rs.EOF
    For Each fld In rs.Fields
       ...
    Next
    rs.MoveNext
Loop

This does the same thing as the above branches would have done and does so in much less verbose manner and will work whether there's only one column or several, only one records or several records. Heck, it even works even if there's no records!

So in short, you've been a victim of being obliged to hold the compiler's hand and painstakingly tell it each individual step it must do instead of stepping back and see what you are really trying to do, and convey it to the compiler in most idiomatic manner. It's literally the compiler's job to make sense of the above instructions into machine operations which are mind-numbingly detailed well beyond the point of boredom. In fact, it's also the database engine's job to figure out what you want and how to get it to you in most efficient manner. So you want to step back and be a bit more "declarative"1 in your programming.

Legacy Support

You have this section:

If argIsFilterString Then
    Set rs = qry.OpenRecordset(dbOpenSnapshot)
    rs.filter = argParameters
    Set rs = rs.OpenRecordset(dbOpenSnapshot)
Else
    ...
End If

Which you already indicated is there for backward compatibility. But as others have alluded to, that only add noise and make it hard to understand your function. Note that even if you're the only one writing and reading this code, future you won't know what the hell past you were doing/thinking. So if you don't want your future you to go back and kill the past you, you owe it to your future you to make it easy to ready. One easy way to set up for legacy support would be to do something akin to this:

Public Function Everything(A As Foo, B As Bar) As Baz
  If B Then
    Everything = EverythingLegacy(A, B)
  Else
    Everything = EverythingCurrent(A)
  End If
End If

Private Function EverythingLegacy(A As Foo, B As Bar) As Baz
...
End Function

Private Function EverythingCurrent(A As Foo) As Baz
...
End Function

This gives you two big wins:

1) The code for Everything function is immediately much easier to read and make sense. The B parameter which is only used for legacy becomes more obvious.

2) It's now easy to test the individual functions without having to change the implementation and you know that changes you make won't break the legacy implementation when you tweak your current implementation. When you've finished removing all the legacy implementation, then it's easy to delete the legacy implementation and make EverythingCurrent the new Everything.

--

1 Technically speaking, that's inaccurate because VBA is an imperative language whereas SQL is a declarative language, so I use the term loosely in the sense that you need to focus on describing the problem rather than outlining the steps yourself and getting lost in the forest of details.


From a once over:

This code does not work, you did not provide $y_1, I am assuming you meant scroll_function
I built a JsBin for this : http://jsbin.com/sihoj/1/edit, because you keep calling scroll_function, you can actually prevent the user from reaching the navigation links again, that's not a good approach
As James Khoury mentioned, why not use <a href="#elementid"> or scrollTo ?
You should use lowerCamelCase
This :

if (position_of_target > max_scroll) {
    position_of_target = max_scroll;
}

could be

position_of_target = Math.min( position_of_target , max_scroll );

I feel this reflects better what you are trying to accomplish

Naming

I would much rather see

//Distance from currrent position
distance = target - window.pageYOffset;

than

distance_from_current_position = target - window.pageYOffset;

your code becomes a bit unwieldy when you have too many long variable names

If you have target and would have distance , then I would also go for offset, y_offset looks ugly.

Also here

position_of_target = document.getElementById(this.getAttribute('data-y')).offsetTop;

you should have some deep thoughts about the variable name, position implies usually an x/y coordinate, but you are really dealing here with an offset from the top.

Finally : up_or_down is a terrible name, there is no logical connection for 1 being up, and 0 being down. At the very least you should consider
var UP = true, DOWN = false or var UP = 1, DOWN = 0 if you don't want to use booleans.

Magic Constants

/ 3 <- That 3 should be a well named constant
target - 5 <- That 5 should be a well named constant

Fake Booleans

This:

    if (window.pageYOffset < position_of_target) {
        up_or_down = 1
    } else {
        up_or_down = 0
    }

is letting up_or_down be a fake boolean, you should go for

    up_or_down = (window.pageYOffset < position_of_target)

especially since you are doing falsey comparisons to up_or_down any way.

DRY

This:

        if (up_or_down) {
            if (y_offset < target - 5) {
                window.scroll(0, y_offset + (distance_from_current_position / 3))
            } else {
                window.scroll(0, y_offset + 1)
            }
            if (y_offset < position_of_target - 1) {
                scroll_function(target);
            }
        } else {
            if (y_offset > target + 5) {
                window.scroll(0, y_offset + (distance_from_current_position / 3))
            } else {
                window.scroll(0, y_offset - 1)
            }
            if (y_offset > position_of_target + 1) {
                scroll_function(target);
            }
        }

could be

    var vector = up_or_down ? -1 : +1;

    if (y_offset < target + 5 * vector ) {
        window.scroll(0, y_offset + (distance_from_current_position / 3))
    } else {
        window.scroll(0, y_offset - vector)
    }
    if (y_offset < position_of_target + vector) {
        scroll_function(target);
    }