I've only got a minor amount of suggestions to offer. Your code already does what it needs to do the proper way.
Missing headers
Consider including the specific header of the types you use instead of depending on other headers including them.

Requires <cstddef> for std::size_t.
Requires <type_traits> for std::enable_if<>
Requires <tuple> for std::tuple<> and std::get<>. This one  is actually needed, otherwise you get an undefined reference to std::get<>.

Printing
Consider...

Changing your condition to I == sizeof...( Tp ) - 1 instead of I == sizeof...( Tp ). Will the compiler optimize away the last extra empty function call? Probably, but there's no reason to have it to begin with.
Using the _t post-fix type traits for conciseness: std::enable_if_t<> over typename std::enable_if<>::type.
The default type alias of std::enable_if<> is already void, there's no need to explicitly write it.

By applying those suggestions, we go from this:
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
print(std::ostream&, std::tuple<Tp...> const&)
{ }

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
print(std::ostream& s, std::tuple<Tp...> const& t)
{
    s << std::get<I>(t);
    print<I + 1, Tp...>(s, t);
}

To this:
template<std::size_t I = 0, typename... Tp>
inline std::enable_if_t<I == sizeof...( Tp ) - 1>
print( std::ostream& s, std::tuple<Tp...> const& t )
{
    s << std::get<I>( t );
}

template<std::size_t I = 0, typename... Tp>
inline std::enable_if_t<I < sizeof...( Tp ) - 1>
print( std::ostream& s, std::tuple<Tp...> const& t )
{
    s << std::get<I>( t );
    print<I + 1, Tp...>( s, t );
}

Using the array pack-expansion trick to avoid recursion, the use of std::tuple<> and indexing.

By using that trick, the print() function can be simplified into:
template <class OutputStream, class... Args>
void print( OutputStream& os, Args&&... args )
{
    using expander = int[];
    expander{ ( (void) ( os << std::forward<Args>( args ) ), 0 )... };
}

You can apply the same trick to the buildStringFromParts() function. This will allow you to separate printing from building the string.
To compensate for some standard warning flags that most people have turned on by default (-Werror -Wunused-value) we need to force a use of the temporary. So extract the first element as a return value:
template<typename... Args>
int print(std::ostream& s, Args&... args)
{
    using Expander = int[];
    return Expander{ 0, ((s << std::forward<Args>(args)), 0)...}[0];
}


List of previous and upcoming months to a given date (year and month)

Be aware that in some scenarios, strtotime() may have a limitation.  Furthermore using property DateTime objects will provide greater utility if you decide to extend functionality in the future.

This task is well-suited for DatePeriod.  It will serve you up a collection of date objects that you can format however you wish.

Code: (Demo)

function rangeOfMonths($prior, $ahead, $baseYear = null, $baseMonth = null) {
    $baseYear = $baseYear ?: date('Y');
    $baseMonth = $baseMonth ?: date('m');

    $rangeStart = new DateTime($baseYear . '-' . $baseMonth . '-01 23:59:59');
    $rangeEnd = clone($rangeStart);

    $rangeStart->modify("-{$prior} month");
    $rangeEnd->modify("+{$ahead} month +1 day");

    $period = new DatePeriod($rangeStart, new DateInterval('P1M'), $rangeEnd);
    $monthsList = [];
    foreach ($period as $i => $dateObject) {
        $monthsList[] = [
            'year'       => $dateObject->format('Y'),
            'nr_month'   => $dateObject->format('n'),
            'month_name' => $dateObject->format('M'),
            'current'    => $i == $prior
        ];
    }
    return $monthsList;
}

var_export(rangeOfMonths(5, 6));

Instead of bloating the function declaration syntax with an array type argument which has two elements (with potentially falsey / non-date-oriented values), write these optional values as individually served arguments and write them as the final arguments.  This will allow you to call this function without needing to pass the array structure.  If your incoming data is already an indexed array with upto two elements, just ... (splat operator) the array when calling the function.
Either way, using any falsey default values will benefit your script by allowing you to leverage the brief ?: (elvis operator).

+1 day is to make the date range inclusive of the final month.

*Timezone impact was not included in my review, you may want to investigate fringe cases and set the timezone per your application's requirements.


google.maps.event.addListener(marker, 'drag', fgetAddressComponents);

And you don't need to add it twice. No need to add it in the click handler again.

Otherwise it's mostly ok, except for the == (instead of ===), I just have styling nitpicks to say about this code.


Don't use global variable

It make things hard to understand and to maintain. In your case, the simple way to do this is to feed your function function() the parameters it needs.

def function(letter_input, number_input, split_letters):

Make your code easier to read

You can ensure you respect PEP 8, the guideline to write Python code. You'll find various tools to help you comply to the usual standards : pep8,  pylint, pyflakes, pychecker.

Also, function is a pretty bad function name, let's pick something better (for instance write_permutation).

Use pythonic loops

Python provides you a clean/safe/concise/way to iterate over pretty much anything : for something in something_iterable. Using the loop index is much more verbose on top of being less efficient.

You can change :

all_combinations_list = list(itertools.permutations(split_letters, number_input))
number_of_combinations = len(all_combinations_list)
for n in range(0,number_of_combinations):
    raw_characters = str(all_combinations_list[n])

to (using the default behavior for range)

all_combinations_list = list(itertools.permutations(split_letters, number_input))
number_of_combinations = len(all_combinations_list)
for n in range(number_of_combinations):
    raw_characters = str(all_combinations_list[n])

then

all_combinations_list = list(itertools.permutations(split_letters, number_input))
for e in all_combinations_list:
    raw_characters = str(e)

then

for e in list(itertools.permutations(split_letters, number_input)):
    raw_characters = str(e)

then (because you don't need to create a temporary list) :

for e in itertools.permutations(split_letters, number_input):
    raw_characters = str(e)

Don't use complicated non-required logic

Converting your tuple in a string you perform logic in in way too complicated on top of not being efficient.
You could just do something like (using what we call "tuple unpacking"):

for e in itertools.permutations(split_letters, number_input):
    a, b, c = e
    out_2 = a+b+c

This can even be more concise by doing the unpacking as part of the loop :

for a, b, c in itertools.permutations(split_letters, number_input):
    print >>output_file, a+b+c

Using with

You can use the with keyword to handle ressources that needs to be "opened" and "closed" such as files. In your case, you can write :

with open('/tmp/list.txt', 'w') as f:
    for a, b, c in itertools.permutations(split_letters, number_input):
        print >>f, a+b+c

and you don't need to close the file manually.

Using the if__name__ guard

It is usually a good habit to put your code behind a guard to have your main code running only if we run your script and not if we import it (because one wants to re-use a function for instance).

No need for list as strings are iterables too

As pointed out in codesparkle's comment, you don't need to build a list.

Once this is done, you code looks like :

import itertools

def main():
    """Main function"""
    split_letters = raw_input(' Type in letters: ')
    number_input = int(raw_input(' Letters per word: '))
    with open('/tmp/list.txt', 'w') as f:
        for a, b, c in itertools.permutations(split_letters, number_input):
            print >>f, a+b+c

if __name__ == "__main__":
    main()

As a final note, your code could be written using a single call to print by using join on the list of permutations but this doesn't bring much so I'll skip that part.


Don't copy the array

A lot of the time spent in your program is just making copies of the game array.  Instead of copying the array, just use the same one.  All you need to do is to undo the move you made after you are done recursing on it.  In other words:

Make the move
Recursively solve
Undo the move

Don't count the number of o's

Another time waster is the part where you count the number of o's on every recursive call.  Instead of doing that, just count the number once, at the very beginning.  Then when you recurse, pass in the new count.  The new count is always one less than the previous count because each move removes one o from the board.

Error check should only happen once

Similarly, this error checking:

    if(game != null && game.length == 0){
        return -1;
    }

only needs to be done once.  Having that code be in every recursive call is just slowing things down.

Memoization

Another thing that could be slowing your program down is the possibility that you are solving the same game states multiple times.  For example, from the starting position, making move A followed by move B might end up in game state S1.  But making move B followed by A might end up in the same state S1.  Right now your program would solve the S1 state twice.

What you could do is to create an array (or Map) to record the answers to any state you have already solved.  Since there are 23 spots, there are \$2^{23}\$ possible game states, or around 8 million.  You can number each game state based on the binary number you get from the board, where - is a 0 and o is a 1.  For example, --------------------o-o would translate to the binary number 00000000000000000000101, or 5.  That would be the "index" of your game state.

After solving for a game state, you record the result in your array or Map.  At the beginning of your function, you check the array/Map to see if the current position has already been solved, and just return the result if it has.

Also you can use bit tricks to compute the new game state index from the previous game state index, so you don't have to recompute it every time.  For example, if the index is index, and you are making a move starting at index i, then the new game state index would be index ^ (0x7 << (20-i)).  This is because you are flipping the board positions at the three bits starting at 20-i.

This memoization is probably going to help speed up your program more than the other tips, because it will cut entire branches off your search space instead of just speeding up your program by a flat percentage.

Sample rewrite

I used the ideas above to rewrite your program.  For the memoization part, I chose to use a HashSet to remember which game states were already visited.  I found that there was no need to actually remember the score for previously visited states (hence the Set and not a Map).

import java.util.HashSet;
import java.util.Scanner;

public class pebble {
    private static final int MAX_GAME_LENGTH = 31;

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int numOfGames = Integer.parseInt(input.nextLine());

        while (numOfGames > 0) {
            char[] values = input.nextLine().toCharArray();

            if (values.length > MAX_GAME_LENGTH) {
                System.out.println("Skipping game: too large");
                continue;
            }
            long startTime = System.nanoTime();
            System.out.println(solve(values));
            System.out.println("Time to finish in ms: " +
                    (System.nanoTime() - startTime) / 1000000);
            numOfGames--;
        }
        input.close();
    }

    private static int solve(char[] game)
    {
        int              gameState = 0;
        int              score     = 0;
        HashSet<Integer> visited   = new HashSet<Integer>();

        // Compute initial game state and score.
        for (int i=0;i<game.length;i++) {
            gameState <<= 1;
            if (game[i] == 'o') {
                gameState |= 1;
                score++;
            }
        }

        return solveHelper(gameState, score, visited, game.length);
    }

    private static int solveHelper(int gameState, int score,
            HashSet<Integer> visited, int gameLength)
    {
        int bestScore = score;

        visited.add(gameState);
        for (int i = gameLength-3; i >= 0; i--) {
            int trio = (gameState >> i) & 0x7;
            if (trio == 0x6 || trio == 0x3) {
                // 0x6: oo- -> --o
                // 0x3: -oo -> o--
                int mask         = ~(0x7 << i);
                int newGameState = (gameState & mask) | ((trio ^ 0x7) << i);
                if (!visited.contains(newGameState)) {
                    int ret = solveHelper(newGameState, score-1, visited,
                                            gameLength);
                    if (ret < bestScore)
                        bestScore = ret;
                }
            }
        }
        return bestScore;
    }
}

Optimizations helped a lot

I ran three programs to solve the difficult board.  The first was the original program.  The second was a variant of my program with the visited set removed to test how much of a difference the memoization made.  The third was my sample rewrite program unmodified.  Here are the results:

Original program : 41000 ms
JS1 (no memo)    :  1460 ms (28x  faster)
JS1 (with memo)  :     3 ms (480x faster than no memo)


@Danninno asked us to close off the question, to be honest I forgot about the request for a bit until recently (I've been using the wrapper quite a lot).

Answer

I see that within my own code I went with Option 4. Mostly for the reasons stated in the question. It turned out to be the better fit of the 5 possible options. Option 5 was/is a close contender as it's more OOP'y but it does generate a crazy class structure to simply hide an implementation detail.

Motivation/Discussion

When I originally asked the question I was hoping for bit of a fight/haggle/explanatory answer (Even if I received an opinionated one i.r.o. the forum rules) or atleast a good argument as to which method was the better/worse one. Mostly so that I could improve my decision making process. I see now that some classes in Python are done by it's developers to showcase certain features (After all they like to play/push the bounds somewhat). In this instance Path is constructed in such a way as to avoid the use of Metaclasses (I might be a bit off here, as it's been a while since I looked at the source for pathlib). Another example of this "playing" is seen in the NamedTuple implementation which essentially evals a string to implement it's class, which eliminates any implied inheritance.


OpenMP loop parallel for loop with function calls and STL vector

The code seems thread-safe to me. All operations are either done with local variables or with data addressed via the loop index, so data races are seemingly absent. Thus, no additional protection like #pragma omp atomic is necessary.

I do not think you can make it "more parallel". Though technically parts of the loop iteration are independent and can be computed in parallel, the overall amount of computation seems rather small, so exploiting that "inner" parallelism is unlikely to bring more performance. If you want to try it though, I would recommend you to use #pragma omp task, not sections.


Return a random line from a file when user enters a specific text

When working with files, you should wrap open calls in a with statement like this:

if search_text in text:
    with open('myquotes.txt') as fh:
        line_fetched = random.choice(fh.readlines())
    print("My quote: ", line_fetched)
else:
    quote()

If you want to make it possible to match any of multiple words like "hello", "hi",
then you'd need a helper function, for example:

def text_contains_any_of(text, words):
    for term in words:
        if term in text:
            return True
    return False

And then change your code to use this:

words = ("hello", "hi")

if text_contains_any_of(text, words):
    with open('myquotes.txt') as fh:
        line_fetched = random.choice(fh.readlines())
    print("My quote: ", line_fetched)

In the above examples I renamed the variable and method names to follow PEP8.


Project Euler problem 530 - GCD function is inefficient

Okay, I've taken another look at the problem, and I have another refinement. It's not a complete solution, though; I suspect that Project Euler 530 is expecting you to have some number-theoretical insight, rather than just a lot of refinements on top of brute force.

The brute-force solution is indeed something like this (in C++ because I like C++ better than Java):

template<typename T>
T f(T n)
{
    T sum = 0;
    const T sqrtn = sqrt(n);
    for (T i = 1; i <= sqrtn; ++i) {
        if (n % i) continue;
        sum += gcd(i, n/i);
        if (i*i != n) sum += gcd(i, n/i);
    }
    return sum;
}

template<typename T>
T F(T k)
{
    T sum = 0;
    for (T i = 1; i <= k; ++i) {
        sum += f(i);
    }
    return sum;
}

By the way, gcd itself is going to be very fast no matter what, as long as you're compiling with optimizations turned on. For my C++ testing, I just used #define gcd std::__gcd, which turned out to be just a hair faster than the naive %-based algorithm and much faster than a "Binary GCD" algorithm I copied from Wikipedia.

This version performs F(1e6) in 7.7 seconds.

The answer at Optimize finding GCD of all pairs of divisors provides a very good algorithmic refinement. It reverses the loops so that you have something like this:

template<typename T>
T F(T k)
{
    T sum = 0;
    const T sqrtk = sqrt(k);
    for (T d = 1; d <= sqrtk; ++d) {
        const T k_over_d = k/d;
        sum += d;
        for (T n = d+1; n <= k_over_d; ++n) {
            const T g = gcd(n, d);
            sum += 2*g;
        }
    }
    return sum;
}

This is basically what you've implemented, except that you compute i*i sqrt(n) times instead of just computing sqrt(n) once, and so on. In other words, you're deliberately pessimizing your code, which is one reason it's hard to identify the real bottlenecks. When doing Project Euler–type speed challenges, you should always eliminate all the inessential inefficiencies that you can, so that if any inefficiencies remain, they'll be essential to your algorithm (and hopefully point the way to a better algorithm).

This version performs F(1e7) in 4.0 seconds.

So, looking at that version, the thing that jumped out at me was that we're computing gcd(n,d) in the inner loop... over a lot of values of n, like, more than d different values of n. And gcd(n,d) is never bigger than d. So we're summing up the same value of gcd(n,d) multiple times (for n equal to n1, and n1+d, and n1+d+d, and so on). So, I thought to myself, let's split that inner loop into d inner loops and compute 1/dth as many GCDs!

template<typename T>
T F(T k)
{
    T sum = 0;
    const T sqrtk = sqrt(k);
    for (T d = 1; d <= sqrtk; ++d) {
        const T k_over_d = k/d;
        for (T n_mod_d = 0; n_mod_d < d; ++n_mod_d) {
            const T g = gcd(n_mod_d, d);
            for (T n = d + n_mod_d; n <= k_over_d; n += d) {
                sum += 2*g;
            }
        }
        sum -= d;
    }
    return sum;
}

This version performs F(1e8) in 6.5 seconds.

I thought Clang (my C++ compiler of choice) was probably smart enough to optimize that inner-inner loop (the one that just adds 2*g a known number of times). Indeed, manually optimizing it to

            const T g = gcd(n_mod_d, d);
            const T iterations = (k_over_d - n_mod_d) / d;
            sum += 2*g*iterations;

didn't produce any further speedup, indicating that the compiler was already doing that optimization for me.

We can rearrange some of the obvious commutative operations, e.g. instead of subtracting d from sum for each d from 1 to sqrtk, we can just subtract (sqrtk+1) * sqrtk / 2 once... that kind of thing. That doesn't change the shape of the nested loops, so it doesn't affect the runtime of the code; but it makes the code a bit shorter and removes some of the inessential inefficiency so that we can see more clearly the essential inefficiency we're still trying to get rid of.

template<typename T>
T F(T k)
{
    T sum = 0;
    const T sqrtk = sqrt(k);
    for (T d = 1; d <= sqrtk; ++d) {
        const T k_over_d = k/d;
        for (T i = 0; i < d; ++i) {
            sum += gcd(i, d) * ((k_over_d - i) / d);
        }
    }
    return (2 * sum) - ((sqrtk + 1) * sqrtk / 2);
}

Aha! Given that i < d, that subexpression ((k_over_d - i) / d) looks suspicious. It can only ever take on one of two values: either int(k_over_d / d) if i <= k_over_d % d, or that-minus-1 otherwise. So we hoist that multiplication out of the loop, and finally we're back to a couple of loops over gcds.

I got another tiny speedup by using a lookup table for gcd(x,y) where x <= y <= 8192; that version performed F(1e8) in 5.0 seconds.

However, you don't need 10x speedups; you need 10000000x speedups, in order to perform F(1e15) in a reasonable amount of time. This implies that there's another algorithmic, number-theoretic, approach that will be the actual solution Project Euler is looking for.

You might think that another possible solution would be to split up the work and use multithreading to get the answer in parallel. But even supposing that you have a 16-core CPU at your disposal, that's only a 16x speedup at most. To beat Project Euler, you'll need another 625000x speedup from somewhere... and the only place to get that is algorithmic leaps.

You might also think that you could speed up the current algorithm by micro-optimizing gcd — by memoizing, or using a lookup table (as I did), or something like that. But notice that with the current algorithm, you'll eventually have to perform gcd(i,d) for each d up to sqrt(1e15), i.e., 31.6 million. Unless your proposed micro-optimization can deal with that many different inputs, it probably won't help.

EDITED TO ADD: I realized this morning that there's yet another rearrangement of the terms that might help. You could look for the sum
\$\sum_{x,y,g} g \cdot\delta(\text{gcd}(x,y)=1 \text{ and } xyg^2 < k)\$.
There happens to be a handy O(k) algorithm for generating all pairs (x,y) < k such that gcd(x,y)==1. Unfortunately, O(k) in your case is O(1e15), which is simply too slow. So this doesn't help. What you need is a way to count those coprime pairs in O(something small), combined with a way to use that information to compute the sum you're looking for.

(And if we had any eggs, we'd have ham and eggs... if we had any ham.)


Is it reasonable to expect this AngularJS function to perform well?

After digging around a bit, it seems the most appropriate approach for this is to create a kind of "fix" for latency resulting from CPU time that will quickly cause inaccuracies in a javascript timer. I wrote the below to demonstrate. As you can see, the setTimeout named timer1 includes a check based on the difference between the start Date object and an updated Date object. Using this value, we can calculate (with better, not perfect, accuracy) how off our incrementing time is. The setTimeout named timer2 does not include this check and, as you will see, the latency begins to accumulate.

<!DOCTYPE html>

    <title>Accurate Timer Test</title>

Corrected Example:<input type="text" value="0" name="correct" id="correct" />

Latency Example:<input type="text" value="0" name="latency" id="latency" />

Start

Stop


Implement test which tries function with diferent params and expected results

A six-fold nesting is not a way to go. Enumerating all possible combinations can be achieved in two loops, no matter how many arrays are contributing:

bool next_combination(int * combination, int * limits, int size) {
    for (int index = 0; index < size; ++index) {
        combination[index] += 1;
        if (combination[index] < limits[index]) {
            return true;
        }
        combination[index] = 0;
    }
    return false;
}

...

int limits[] = { countof(EXPIRY_TEST), countof(STRIKE_TEST), /*etc*/ };
int combination[countof(limits)] = 0;

do {
    result = function(EXPIRY_TEST[combination[0], STRIKE_TEST[combination[1], /*etc*/);
while (next_combination(combination, limits, countof(combination)));

Size of array is better be computed in a type-agnostic way:

#define countof(name) (sizeof(name) / sizeof(name[0]))

The expected results are totally disconnected from the argument sets. It would be very hard to make additional cases.
You must report which test case failed.


Need unique url but require non unique information from other columns

I would do it like this

<?php
#opens conection
include 'conn.php';

echo $_COOKIE["search"];

$search = mysql_real_escape_string($_COOKIE[search]);
$sql    = "SELECT * FROM feedback WHERE url LIKE '%{$search}%' GROUP BY url ORDER BY ratingtime DESC";
#runs the query
$query = mysql_query($sql);
$linecount = 1;

#populates the table with the information
echo '
';
echo '

          URL
          Page Title
          Date Last Modified
          Average Rating

';

while($row = mysql_fetch_array($query)){

        $sqlurl = mysql_real_escape_string($row['url']);

        $feedback_query = mysql_query("SELECT SUM(`rating ) / COUNT(`rating`) AS avg_rating FROM feedback WHERE url = '{$sqlurl}'");
        $feedback       = mysql_fetch_assoc($feedback_query);

        $encodedurl = urlencode($row['url']);

        echo "

                {$row['url']}
                {$row['pagetitle']}
                {$row['ratingtime']}
                ".round($feedback['avg_rating'], 2)."

";
        $linecount++;
}

echo '

';
?>

If improved your query to get the Avg. Rating and added mysql_real_escape_string to prevent the mysql injection vulnerability.


I wanted to post an idea I had to address my concern over the brittleness of my unit test(s).  I realised that since I am performing a string comparison, that I could use Regular Expressions.  Then I can ignore parts of the parse tree string that are not interesting.  So I have this as a potential solution:

[Fact]
public void CanParseAmbiguousIdentifierInVariableDeclaration()
{
    const string variableDeclarationTemplate = "Dim {0} As String";
    const string regexTemplate = @"(\(variableDeclaration.*\(identifier {0}\).*\))";

    CanParseAllAmbiguousIdentifiersRegex(variableDeclarationTemplate, regexTemplate,
        p => p.variableDeclaration());
}

private void CanParseAllAmbiguousIdentifiersRegex(string sourceTemplate, string regexTemplate, Func<VbaParser, ParserRuleContext> rule)
{
    foreach (var id in ambiguousIdentifiers)
    {
        var source = string.Format(sourceTemplate, id);
        var regex = string.Format(regexTemplate, id);

        CanParseSourceRegex(source, regex, rule);
    }
}

private static void CanParseSourceRegex(string source, string regex, Func<VbaParser, ParserRuleContext> rule)
{
    var parser = VbaCompilerHelper.BuildVbaParser(source);

    var result = rule(parser);

    Assert.Null(result.exception);
    Assert.True(Regex.IsMatch(result.ToStringTree(parser), regex));
}


SQL connection in static class and wrapper

The class being static is not the only thing that makes testing more difficult then necessary.

var connectionString = ConfigurationManager.ConnectionStrings["appDatabase"].ConnectionString;

The hardcoded connection string name should be a parameter. You can have default constructor using a default connection string name but it's always a good idea to have another constructor that lets you use another value.

AddClient

If it's a ClientDatabase for CRUD about client objects then I find the client in name AddClient method redundant. Simply Add, Delete etc would be more appropriate.

By following this pattern you can have a single crud-generic interface for all types:

public interface IDataAccess<T>
{
    void Add(T obj);
    void Delete(T obj);
    ..
}

and later

public class ClientDataAccess : IDataAccess<Client>
{
    public void Add(Client obj) {..}
    public void Delete(Client obj) {..}
}


Inverse mapping with bilinear interpolation on an image

I'm sure there are ways to vectorize this, but I've learned from past examples that it's often easier to just use numba.jit in these cases (where "these cases" means entirely numeric operations with simple loops and no complex python object interactions beyond numpy). You technically ask for a better "time complexity", which would require a different algorithm/approach to this problem. That's not so easy to provide, since your current approach fundamentally requires individually processing how each source pixel is represented in each target pixel; that's O(N) or O(H*W) depending on how you want to frame the number of pixels, and I don't see any way around that. This process could be parallelized using a GPU or vectorized code; however, the easiest thing to try first is to make your current code more efficient. If that provides the speedup you require, then you can stop there.

Just naively putting your code through numba.jit, however, doesn't provide any speedup. To figure out why, I used numba.jit(nopython=True), which errors out when doing anything that numba can't convert into efficient C code. This showed a few minor things to change, such as converting np.floor(x).astype(int) to int(np.floor(x)) (which is equivalent, since these are single integers and not arrays). Also, your modification of offset seems like it would only run once and only on the first iteration, if at all, so I moved it outside the loop. Your bounds checking condition can be simplified with a little Python-Fu. And finally, I've modified your variable names to conform to PEP8 style.

The below code produces the same results are your original code, but is able to be efficiently compiled by numba.jit, providing ~20x speedup in my tests.

import numpy as np
from numba import jit

@jit(nopython=True)
def numba_func(img, inv_rot, offset, row, col):
    y_len, x_len, _ = img.shape

    new_matrix = np.zeros((row, col, 3), np.uint8)
    if offset > 0:
        offset *= -1
    for r in range(row):
        for c in range(col):
            pt = np.array([r + offset, c, 1])
            y, x, _ = inv_rot @ pt  #Reverse map by reverse rotation and pick up color.

            #Check the bounds of the inverse pts we got and if they lie in the original image,
            #then copy the color from that original pt to the new matrix/image.
            if 0 <= y < (y_len - 1) and 0 <= x < (x_len - 1):
                x0 = int(np.floor(x))
                x1 = x0 + 1
                y0 = int(np.floor(y))
                y1 = y0 + 1

                Ia = img[y0, x0]
                Ib = img[y1, x0]
                Ic = img[y0, x1]
                Id = img[y1, x1]

                color1 = (x1-x) * (y1-y) * Ia
                color2 = (x1-x) * (y-y0) * Ib
                color3 = (x-x0) * (y1-y) * Ic
                color4 = (x-x0) * (y-y0) * Id

                weighted_avg_color = color1 + color2 + color3 + color4
                new_matrix[r, c] = weighted_avg_color

    return new_matrix

If that's not fast(er) enough, there are other options, but certainly they'll require a more significant re-work of the code. Again, though, due to the nature of the problem, I don't think you'll be able to achieve better "time complexity", just faster code; this doesn't seem like the kind of problem with a better algorithmic approach, just better implementations.


Implementation of Queue using Linkedlist in Java

Formatting

Your indentation is all over the place.  Using a consistent form of indenting that reflects the scoping of statements makes your code much easier to read and makes bugs easier to spot.

Consistency

Be consistent with your interface.  You define enqueue in terms of the data item that is to be stored in the queue.  This is good, because it hides the implementation.  However, you define dequeue as returning a Node.  This is bad, Node is an implementation detail, there's no reason for the caller to need to know it exists.  dequeue should instead be returning an int (as this is the type stored in the queue).

Print statements

Your print statements don't belong in your queue.  Part of the reason that you originally submitted code that didn't allow access to the values stored in the queue is because you put the print statements within it.  Separate the concerns of your classes and test the boundaries.  If you had originally tried to write your print statements in your main is would have become clear that you needed dequeue to return something in order for you to be able to print it.

Mains don't belong in collections

Your main method doesn't belong in the Queue.  It's not part of the Queue, it's part of your test harness.  You should put it in a different class.  This will help to enforce the boundaries between what is the Queue's responsibilities and what is not the Queue's responsibilities.

Returns & Elses

Where possible you want to avoid nesting statements too far.  In your dequeue, you're doing this:

if(front==null && rear==null)
{
    System.out.println("\t Queue is Empty");
    return null;
}
else {

This creates a layer of nesting for the else statement.  You don't need the else.  When the if condition is matched, you return from the function.  The only way you get past the statement is if the condition didn't match, so the else is redundant.

Redundant checks

In enqueue you perform:

else if(rear.next==null)

You don't have an else condition for this check, and if this condition is triggered, it means that rear isn't pointing at the end of the queue and you've got something very wrong with your collection.  Either remove the if check, since it can't happen, or throw an exception when it does, don't just pretend everything is all right.


Simple way to loop through a JavaScript object array?

A short review;

I prefer to use the function keyword
You are using libs like a global, I would pass it in the function
If you don't need both key and value, then you can just use Object.values
Building on that, you might as well use a properly named function parameter and cut the lines in two

function moveLibs(libs, done){
  Object.values(libs).forEach(types => {
    Object.values(types).forEach(srcAndDest  => {
      Object.values(srcAndDest).forEach(value => {
        console.log(`Piped ${value.src} to ${value.dest}`);
      });
    });
  });

  done();
};

libs=
    {
        a: {
          js: [
            {
              src: 'path/from/a1.js',
              dest: 'path/to/a1.js',
            },
            {
              src: 'path/from/a2.js',
              dest: 'path/to/a2.js',
            },
          ],
          css: [
            {
              src: 'path/from/a1.css',
              dest: 'path/to/b1.css',
            },
          ],
        },
        b: {
          js: [
            {
              src: 'path/from/b.js',
              dest: 'path/to/b.js',
            },
          ],
        },
      };

moveLibs(libs, ()=>console.log("Hello World!"));


Javascript querystring to object conversion

The line if (typeof prev[key] === typeof []) { is... weird. If you're checking for a type specifically, check for it: if (typeof prev[key] === 'object') { - the way you're doing it there causes a new array literal to be instantiated needlessly, as well as a superfluous typeof operation, both inefficient and outright unnecessary.

Making an array out of repeating keys is fallacious - if a key is exactly repeated in a query string, only the right-most instance of that query string value will be received by the server. Further, in cases where the query string contains validly structured arrays (test=1&test2[]=2&test2[]=4), your code ends up with a key like test[], which is a nasty to access: results['test2[]'] is the only way to get at it (no dot syntax allowed).

EDIT
To clarify my remarks about duplicating keys, I purhaps mistakenly restricted my comments to Apache(Linux or Windows)/PHP - certainly other languages and platforms are relevant to the discussion. In the PHP language (what I am most familiar with), the query string test=1&test=2 will result in:

var_export($_GET);
/* array (
  'test' => '2',
) */

... as you can see, only the right-most value is the only one passed into the script. The way PHP expects duplicate query string keys is by use of [] in the query: test[]=1&test[]=2

var_export($_GET);
/*array (
  'test' =>
      array (
        0 => '1',
        1 => '2',
  ),
)*/

This behavior is the same for POST data on PHP - you must use name="myField[]" if multiple fields will use the same name, otherwise, only the last item in the form with a given name will be populated in PHP's $_POST data.

I am not set up to confirm the behavior of this in ASP (or other languages), however research has indicated that my assertion is still somewhat valid: https://stackoverflow.com/questions/6395290/how-may-i-add-integer-list-to-route/6396793#6396793. Please confirm if you are able: from what I have gathered the values would be passed to script as a comma-delimited list, but the language itself still rejects working with duplicate keys and a workaround is required.

If you can add some data about handling of duplicate keys in other server languages, please feel free to edit them into this answer. That said, I feel my criticism of this script's handling of duplicate keys stands, as well as the issue with "properly formed" (PHP) arrays in the query string - result['test[]'] is nasty.


There is no need to do the deep abstraction for the Select *. You can simply reference the columns you want and include them in the result...

SELECT JOB_NUM,
       ITEM_NUMBER,
       DATE_COMPLETED,
       QTY_COMPLETED,
       STD_USAGE,
       ACTUAL_USAGE,
       ITEM,
       DESCRIPTION
FROM JOB_ROUTERS
LEFT JOIN ITEM_ATTRIBUTE
       ON JOBS.ITEM_NUMBER == ITEM_ATTRIBUTE.ITEM
WHERE RESOURCE_CODE == "TDWELD"


Python list dictionary items round robin mixing

Using the roundrobin() recipe from itertools is already pythonic. The solve() method could be replaced with more use of itertools.

In particular itertools.groupby() would do the same as your defaultdict and for loop:

>>> import operator as op
>>> g, p, t = [list(v) for k, v in groupby(sample, key=op.itemgetter('source'))]
>>> list(roundrobin(g, p, t))
[{'"serial"': '0', 'source': 'G'},
 {'"serial"': '30', 'source': 'P'},
 {'"serial"': '2', 'source': 'T'},
 {'"serial"': '1', 'source': 'G'},
 {'"serial"': '0', 'source': 'P'},
 {'"serial"': '3', 'source': 'T'},
 {'"serial"': '2', 'source': 'G'},
 {'"serial"': '1', 'source': 'P'},
 {'"serial"': '2', 'source': 'P'},
 {'"serial"': '3', 'source': 'P'}]

You don't really need to unpack as you can make the call to roundrobin() using *, e.g:

>>> x = [list(v) for k, v in it.groupby(sample, key=op.itemgetter('source'))]
>>> list(roundrobin(*x))
[{'"serial"': '0', 'source': 'G'},
 {'"serial"': '30', 'source': 'P'},
...

Note roundrobin() could be rewritten using itertools.zip_longest(), which should be faster for near equal sized iterables e.g.:

def roundrobin(*iterables):
    sentinel = object()
    return (a for x in it.zip_longest(*iterables, fillvalue=sentinel)
            for a in x if a != sentinel)

Did a quick run of a 10000 random items in sample and found the recipe surprisingly slow (need to figure out why):

In [11]: sample = [{'source': random.choice('GPT'), 'serial': random.randrange(100)} for _ in range(10000)]
In [12]: x = [list(v) for k, v in it.groupby(sample, key=op.itemgetter('source'))]
In [13]: %timeit list(roundrobin_recipe(*x))
1 loop, best of 3: 1.48 s per loop
In [14]: %timeit list(roundrobin_ziplongest(*x))
100 loops, best of 3: 4.12 ms per loop
In [15]: %timeit TW_zip_longest(*x)
100 loops, best of 3: 6.36 ms per loop
In [16]: list(roundrobin_recipe(*x)) == list(roundrobin_ziplongest(*x))
True
In [17]: list(roundrobin_recipe(*x)) == TW_zip_longest(*x)
True


Java Crypto library number of padding bytes using PKCS5Padding

"PKCS5Padding" in Java is really PKCS#7 compatible padding. It adds 1 to 16 bytes for a 16-byte-block cipher like AES. If you view those bytes as hexadecimals, e.g. in a debugger, then it may look like 32 characters instead.

ECB mode is almost never secure enough to be used. Use GCM or another authenticated mode (e.g. CCM or EAX).

public byte[] do_decryption(byte[] text) {

For Java we'd use CamelCase starting with a lower case letter (doDecryption or performDecryption).

text is not a good name for a byte array. plaintext for encryption or ciphertext for decryption could be acceptable though.

String key_val = new String("1234567890123456");
byte[] key = key_val.getBytes();

Obviously the key should not be in the source code.

Furthermore, you should almost never use getBytes without specifying the character encoding (e.g. use StandardCharsets.US_ASCII as parameter for the overloaded function.

Variable names except constants should not contain underscores.

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

Already noted in the comments, either the method is badly named or this is plain wrong. Encryption != decryption.

e.printStackTrace();

Please handle exceptions properly.


Optimise runtime of filter character method

Possible performance improvements

w = w[:-1] is probably inefficient since it asks to perform a copy of every element of the list minus one. del w[-1] is the idiomatic way to delete the last element of a list.
You probably have more characters in a string corresponding to isalpha than characters exactly equal to "'" or "-". Therefore, you may notice speed improvements by checking isalpha before the other two conditions.
You could create a table containing all the values of isalpha plus "'" and "*" and then check whether a character is in this table. However, I don't think that it can bring you significant speed improvements, unless you filter with a dedicated str method that may be optimized (replace for example).

Style

A few notes about style:

Please, don't put parenthesis around the while condition, that goes against the Python style guide (PEP8).
Same goes for if.


I'll start with the obligatory:

If you're looking to write a fast interpreter, and you've identified a bottleneck in your memory allocator, a smarter algorithm may save you but at the end of the day rewriting in something lower level is probably the way to go if interpreter speed is that crucial.

The problem with your three snippets is they effectively all do the same thing. By this, I don't mean that the return the same (correct) answer. I mean these three snippets effectively perform the same operations. Just some of the operations are disguised in the second two.

Without having profiling, I can take some guesses about your observed performance. The first is likely fastest because everything is just unrolled into two loops. The second is slowest because of the function call all and the contained generator expression. The third is in the middle because of the (worst case) 256 calls to is_disjoint.

Why are these all the same?

Goes through every index i in range(256), and for each offset from 0 to size checks if it's used (exiting early if it is) returning i if none of them are
Creates a generator that yields an index i (trying 0 to 256) if all indexes from i to i+size are not in used_mem, exiting early when one is) and takes the first yielded i
Goes through every index i in range(256), and checks if every number from i to i+size is not in used_mem (exiting early if one is), returning such an i

Note how these are all just rephrasings of the same algorithm. Your performance isn't going to change much because at the end of the day your algorithm is O(n). Actually, it's a little worse than that. It's really O(n*size), because in the worst case you have to do size comparisons for each of your n "slots" in memory.

You could probably get some mileage out of representing your used_mem as a bitfield where bit i indicates whether slot i is taken (this will be more compact and likely faster to lookup than a set), but...

What you really need is a more efficient algorithm. And fortunately, there is a lot of research in the area of memory allocators. Look through the wikipedia page for many examples of different algorithms for different use cases. One is bound to fit your problem.

One way to reduce your allocator's runtime is with the following simple adjustment: keep track of ranges of memory allocated instead of each slot. So, instead of a set marking each slot as used, maintain a linked list of ranges of slots that are allocated:

used_mem: (start=0, end=10) -> (start=20, end=25) -> (start=30, end=50)
                                    current pointer ^

Additionally, keep a pointer to the last place in the list where you allocated memory.

To allocate memory, start from your current pointer, and see if there is enough space between the last thing allocated (above, slot 25) and the next thing allocated (above, slot 30). If we were allocating 3 slots, we could immediately return slot 26 (and insert (start=26, end=28) into the list, moving the current pointer to after it). If instead, we were allocating something larger (say, 10 slots), then we'd see there's no space between 26 and 30, and we'd move the current pointer to the right and try again.

To reclaim memory, just remove the allocation from the linked list.

This approach has the advantage that of not reconsidering things that have already been allocated (the current pointer), so it typically will find an empty hole faster. Additionally, it considers allocations in chunks, so it can skip large allocations in one loop instead of iterating through each slot individually.


Convert string to double and check for errors

Good use of errno, but can be improved.

The below is decent code for detecting overflow, yet would benefit with improvements.

On overflow, the return value is HUGE_VAL, not necessarily DBL_MAX.  HUGE_VAL may be a large finite or an infinity.

if ((errno == ERANGE && (val == DBL_MAX || val == -DBL_MAX)) || ...) {
    perror("strtod");
    exit(EXIT_FAILURE);
}
// replace with
if ((errno == ERANGE && (val == HUGE_VAL || val == -HUGE_VAL)) || ...) {

Underflow may also raise ERANGE.  Look at the code that attempts to discern that and review the spec.

if (...  || (errno != 0 && val == 0.0)) {
    perror("strtod");
    exit(EXIT_FAILURE);
}

  If the result underflows ..., the functions return a value whose magnitude is no greater than the smallest normalized positive number in the return type; whether errno acquires the value ERANGE is implementation-defined.

OP's code incorrectly assumes 0.0 on underflow.

With so  many options with 1) if errno is set and 2) what value is return, portable code nneds to fix a mess.

Portable code would use the following, yet that gives up useful conversions by some of values in the sub-normal range DBL_TRUE_MIN to DBL_MIN.

if (fabs(val) < DBL_MIN) {
  if (val > 0.0) val = DBL_MIN;
  else if (val < 0.0) val = -DBL_MIN;
  // val is now, DBL_MIN, -DBL_MIN, 0.0, or -0.0

  // pedantic code would also reset errno = 0 if it changed due to `strtod()`
}

A somewhat less portable handing, yet retains sub-normal values - just accept any wee value.

if (fabs(val) < DBL_MIN) {
  // reset errno = 0 if it changed due to `strtod()`
}

No conversion

Good test for no conversion, yet some strtod() set errno in the no conversion case.  To simplify errno processing in the previous block, I'd recommend to do the endptr == str before looking at errno.

Use exponential notation for output

"%f" may print all values of magnitude less than 0.0000005 as 0.000000.  This is not informative.  With large values like DBL_MAX, perhaps hundreds of digits are printed of which past the first 20 or so are rarely of interest.

Instead:

#include <float.h>

printf("strtod() returned %.*g\n", DBL_DECIMAL_DIG, DBL_val);
// or
printf("strtod() returned %.*e\n", DBL_DECIMAL_DIG - 1, val);

Fancier code would assess the length of the argv[1] string for exponential notation and number of digits and then print out in a like-wise fashion.

Tolerate trailing white-space

OP code's alerts with input like "123  ", but not with "  123".  Suggest silence on trailing white-space.

// add
while (issapce((unsigned char) *endptr)) {
  endptr++;
}

if (*endptr != '\0')        /* Not necessarily an error... */
    printf("Further characters after number: %s\n", endptr);

Such non-numeric output may be best done on stderr rather than stdout.

Suggested alternative.

Useful as a basis for some ideas.

// Return status for my_strtod().
// Higher values are more problematic.
typedef enum {
  my_strtod_OK,
  my_strtod_Underflow,
  my_strtod_Overflow,
  my_strtod_ExtraJunk,
  my_strtod_NoConvertableText,
  my_strtod_N
} my_strtod_T;

// Convert a pointer to a string to double and saves its value in *dest.
// Return conversion status.
//
// `errno` is temporarily cleared by this function.  Its value on return:
//   1) Should strtod(*s, ...) set errno, then that is its value.
//   2) Otherwise errno is restored to its original value.
my_strtod_T my_strtod(double *dest, const char *s) {
  char *endptr;

  int errno_original = errno;
  errno = 0;
  *dest = strtod(s, &endptr);
  int errno_my_strtod = errno;
  if (errno == 0) {
    errno = errno_original;
  }

  if (s == endptr) {
    return my_strtod_NoConvertableText;
  }

  while (isspace((unsigned char ) *endptr)) {
    endptr++;
  }
  if (*endptr) {
    return my_strtod_ExtraJunk;
  }

  if (errno_my_strtod == ERANGE && fabs(*dest) == HUGE_VAL) {
    return my_strtod_Overflow;
  }

  if (errno_my_strtod == ERANGE && fabs(*dest) <= DBL_MIN) {
    return my_strtod_Underflow;
  }

  // Note: at this point, errno may be set
  return my_strtod_OK;
}

Selected C specs concerning errno:

/*
 * errno ...  has type int ... the value of which is set to a positive error
 * number by several library functions.  C11dr §7.5 2
 *
 * errno ... is never set to zero by any library function. The value of errno
 * may be set to nonzero by a library function call whether or not there is an
 * error, provided the use of errno is not documented in the description of
 * the function ... C11dr §7.5 3
 *
 * Of course, a library function can save the value of errno on entry and
 * then set it to zero, as long as the original value is restored if errno’s
 * value is still zero just before the return.  C11dr footnote 202
 */


The vec! macro

Before we have a look at including and excluding, we should note that

let mut myvec: Vec<T> = Vec::with_capacity(2);
myvec.push(a);
myvec.push(b);
myvec.push(c);

can be written with the vec! macro as

let myvec: Vec<T> = vec![a,b,c];

This has the nice side-effect that myvec doesn't need to be mut anymore. If we apply this too all your code, we end up with

#[derive(Debug)]
pub struct Dataset {
    pub data: Vec<String>,
}
fn main() {
    //setup test data
    let ds1_data = vec!["a".to_string(), "b".to_string()];
    let ds1 = Dataset { data: ds1_data };

    let ds2_data = vec!["a".to_string(), "c".to_string()];
    let ds2 = Dataset { data: ds2_data };

    let datasets = vec![ds1, ds2];

    let include = vec!["a".to_string()];
    let exclude = vec!["b".to_string()];

    //filter datasets
    for ds in datasets {
        if ds.data.iter().find(|d| include.contains(d)).is_none() {
            continue;
        }
        if ds.data.iter().find(|d| exclude.contains(d)).is_some() {
            continue;
        }

        println!("{:?}", ds);
    }
}

That's a lot less noise, perfect to concentrate on the original problem.

Including and excluding

First of all, instead of find(…).is_some(), we can use any, and instead of find(…).is_none() too. We could use that to simplify the expressions, but we would still traverse the set twice.

for ds in datasets {
    if !ds.data.iter().any(|d| include.contains(d)) {
        //skip not included
        continue;
    }
    if ds.data.iter().any(|d| exclude.contains(d)) {
        //skip excluded
        continue;
    }

    println!("{:?}", ds);
}

Instead, let's think about the elements we have to look at. The answer is all, as exclude might match the last element in our dataset, even if include matched the first.

As we have to look at all elements either way, we might as well traverse them by hand:

    for ds in datasets {
        let mut included = false;
        let mut excluded = false;
        for d in &ds.data {
            if included == false && include.contains(d) {
                included = true;
            }
            if exclude.contains(d) {
                excluded = true;
                break;
            }
        }
        if included == false || excluded == true {
            continue;
        }

        println!("{:?}", ds);
    }

Now that we have this as a blueprint, we can check the iterators for a fitting method. We need to

check that at least one include matches
check that no exclude matches
stop as soon as soon as any exclude matches.

Unfortunately it's not possible to quick exit from a closure, so the last requirement cannot be done with fold or similar. However, we can use inspect and all to get something like our previous loop:

    for ds in datasets {
        let mut included = false;

        if !ds
            .data
            .iter()
            .inspect(|d| {
                if included == false || include.contains(d) {
                    included = true
                }
            })
            .all(|d| !exclude.contains(d))
            || !included
        {
            continue;
        }
        println!("{:?}", ds);
    }

But that's a lot less readable than our previous loop, which did the same. We could increase readablity if we introduced a function, but that's left as an exercise. In the end, we would need a fold-like function that supports an early exit, but such a function does not exist.


Be careful with types. For example, your get_last_word function is meant to return a string but in your error case you return 0. If you want to return an empty string, use return "";

I'm guessing that you might be working under restrictions about what library functions you're allowed to use here, but you don't say so.

If you're allowed to use anything in the standard library, have a look at std::string::find_last_of as a replacement for your first loop.

Similarly, look at std::string::substr as a replacement for your second loop. Building a string one character at a time is generally discouraged because it's quite inefficient. Something like substr will be more efficient because it can, for example, allocate all the memory needed by your string in one go.


The chain of Ajax calls can be set programmatically, instead of being "hardcoded" as in your code. The next snippet shows a possible approach.

However, as Piotr pointed out, you should study your application a bit more to determine whether that is a good solution.

// First generate an array with all the ajax calls than need to be done, in order.
var ajaxCalls = [

    // First ajax
    function(){
        return $.ajax({
            type        : 'POST',
            url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
            datatype    : 'html',
            data        : {subtask:subTask,lessonid:lesson_id,theSubModID:video_id,userid:user_id,prodid:course_id,taskname:taskName}
        });
    },

    // Second ajax
    function(data){
        return $.ajax({
            type        : 'POST',
            url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
            datatype    : 'html',
            data        : {subtask:subTask,lessonid:lesson_id,userid:user_id,prodid:course_id,taskname:taskName}
        });
    },

    ...

    // Last function doesn't need to return a promise
    function(data){
        $(course_box).replaceWith(data);
        $(".accordion").accordion({
            active: false,
            collapsible: true,
            heightStyle: "content"
        });
    }
];

// Every time you run an ajax, you want to set it up so that the next
// ajax will be called as a response. Let's do a function for that:
function callAjax(var index){

    var thisAjax = ajaxCalls[index];

    // Run the ajax
    var promise = thisAjax();

    // Set up next one if necessary.
    var isLastAjax = (index === (ajaxCalls.length - 1));
    if(!isLastAjax){
        promise.done(function(){
            callAjax(index + 1);
        });
    }
}

// Call the first one
callAjax(0);


Just a quick little note: that chunk here, should be parameterized and moved into a separate procedure:

' POS 1
If NUM_REGS >= 1 Then
    Dim udtPOSOne : Set udtPOSOne = New Mapping
    With udtPOSOne
         .strLocalDrive = "P:"
         .strUNCPath = "\\10.0." & STORE_NUMBER & ".101\dpalm"
         .strPersistent = "False"
         .strUsr = "somename"
         .strPas = "somepass"
    End With
    alMappings.add(udtPOSOne)
End If

...instead of being copied over and repeated 3 times with a different strLocalDrive and strUNCPath.


There are few things you can do. Start by encapsulating these lines

if (imageURL.Contains("gfycat.com"))
{
    imageURL = imageURL.Replace("gfycat.com", "zippy.gfycat.com") + ".mp4";
}

if (imageURL.Contains(".gifv"))
{
    imageURL = imageURL.Replace(".gifv", ".mp4");
}

in their own method. Let's call it FixImageUrl (this is C# 7)

public static string FixImageUrl(string imageUrl)
{
    switch (imageUrl)
    {
        case string url when url.Contains("gfycat.com"):
            return imageUrl.Replace("gfycat.com", "zippy.gfycat.com") + ".mp4";

        case string url when url.Contains(".gifv"):
            return imageUrl.Replace(".gifv", ".mp4");

        default: return imageUrl;
    }
}

string[] splitURL = imageURL.Split('/');
int index = splitURL.Length - 1;
string fileName = splitURL[index];

Then you can simplify this a little bit by using the Last extension:

var fileName = imageURL.Split('/').Last();

It probably doesn't matter here but it's a good habit to always dispose objects that are disposable. This means the WebClient requires special care.

You also want to know what went wrong so don't swallow the exception. Print either the message or log the entire exception.

When working with paths you should use the Path.Combine method to avoid any invalid paths like ones with missing \ etc.

try
{
    using (var client = new WebClient())
    {
        client.DownloadFile(imageURL, Path.Combine(userDir, fileName));
    }
}
catch (Exception ex)
{
    Console.WriteLine($"[INFO] ERROR DOWNLOADING FILE: {ex}");
}


Python generate custom combinations of sub lists

What could be improved here?

@thnx Peilonrayz, a generator expression will work better on large inputs

Use a nested generator expression.
DON'T hardcode variables, this will make your code very static.
Make a function, to accept different variables.

def custom_combo(L):
    return (L[i] + L[j] for i in range(len(L)) for j in range(i+1, len(L)))

if __name__ == '__main__':
    a = [[1, 2], [2, 3], [4, 3]]
    print(list(custom_combo(a)))


Add a buffer length parameter and then use strncpy to avoid overflow.
Your testing code hides the usage of the function. It's clearer to put it on a separate line:

for(i = 0; i < sz; ++i) {
    parse_string(input[i], buf)
    printf("Test string \"%s\" => \"%s\", %s\n",
                 input[i], output[i], strcmp(output[i], buf) == 0 ? "passed" : "failed");
}

You missed the out of order cases like >123<


Creating user accounts while avoid SQL injection attacks

Prepared statements (which you use, as you use bindParam) are the correct way to prevent SQL injection.

It is still recommended - but not necessary - to clean input parameters with filter_var, but just as a second (or in this case first) line of defense.

What if you forget to prepare that variable somewhere? Maybe when you retrieve it from the db and use it in a second query? Or what if you echo it somewhere and forget to use proper encoding?

No program is 100% secure, so if you know that you never want special characters in your usernames, then it's a good idea to filter. If you do want those characters, then don't filter.

  all the special characters like (?,/.!() that s/he inputs are removed.

No, they are not. All those characters pass FILTER_SANITIZE_STRING without a problem. It only strips tags and encodes some chars (single and double quotes). The documentation is not very clear on what tags are, but generally it's something like <.*>, although the filter also removes <bar from foo<bar, so you could get problems if you want to allow the < character.


The code looks fine to me but it is a bit odd because the official docs recommend creating a SQLiteOpenHelper subclass to handle database interaction. And if you use one SQLiteOpenHelper instance across your application, it will be thread-safe so there's no need to add your own synchronization logic:

public class DatabaseHelper extends SQLiteOpenHelper {

  private static final String DATABASE_NAME = "location_scout.db";
  private static final int SCHEMA_VERSION = 1;

  // Singleton pattern
  private static DatabaseHelper instance;
  public synchronized static DatabaseHelper getInstance(Context context) {
      if(instance == null) {
          instance = new DatabaseHelper(context.getApplicationContext());
      }
      return instance;
  }

  private DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, SCHEMA_VERSION);
  }

}


I presume that you expected the result to be 20. Unfortunately this code may produce anything from 2 to 20.

Here is a scenario how 2 can be produced:

thread 1 grabs the semaphore (its tmp becomes 1)
thread 1 posts the semaphore in the mid-loop

thread 2 grabs the semaphore (sum is still 0)
thread 2 runs the loop for 9 times (sum becomes 9)
thread 2 posts the semaphore at the loop end

thread 1 takes over and completes its first loop
sum becomes 1
thread 1 posts the semaphore at the loop end

thread 2 takes over; its tmp becomes 2
thread 2 posts the semaphore in the mid-loop

thread 1 takes over and runs to completion

thread 2 (its tmp still 2) completes the second half of the loop
sum becomes 2

In your code the threads sleep while holding the semaphore (so sleeping is pretty much irrelevant). Contexts may only switch in the tiny window between sem_post and sem_wait. Most likely it never happens (scheduler doesn't have to switch threads), which explains why you are getting 20. Try to increase the window, say

    sem_post();
    sleep();
    sem_wait();

and see what happens.


Converting events in an agenda to textual format

This is very hard to read. What's an internal, why are we converting to it? What's an agenda? This is clearly a class method so I'm missing some context but it's not a self explanatory function. You could improve this with proper naming. x and t are meaningless. For instance, if x was appointment_times it would tell me much more.

Likewise, your code is not broken up at all. It's one solid block, which makes it harder to see what each individual section does or even is. Adding whitespace will make it much clearer immediately:

def convert_to_internal(self, agenda):
    x = []
    t = OrderedDict(sorted(agenda['timconf'].items(),
                           key=TimeSerializer.__day_comparator))

   for day, items in t.items():
        day_num = TimeSerializer.DAYS_INVERSE[day]

        for item in sorted(items, key=lambda k: k['begin']):
            for attr in ['begin', 'end']:
                if hasattr('item', attr):
                    item[attr] = item[attr] + day_num*24*60*60

            x.append(TimeItem(**item))

    p = ';'.join(map(str, x))
    return "-t {} -n {} -p '{}'".format(agenda['timeZone'], agenda['locale'], p)


Here's my first analysis. It's not complete, but the VM should be mostly understandable now. I've included some testcases from the homepage in the bottom.

var out,
    stack,
    input_ptr,
    stack_ptr;

function chicken(c, b)
{
    if(b)
    {
        // run once at the beginning of each interpretation
        // after this, chicken is only called recursively with one argument

        if(c == b)
        {
            out = b;
            c = b = input_ptr = 0;
            stack = [undefined, c, 0]
            stack[0] = stack;
            stack_ptr = 2;
            // parse the code
            chicken(1);
            // parsing is done, run the code
            input_ptr = 2;
            stack_ptr++;
        }
        else
        {
            // code is equal to input?!
            stack = [undefined, c, c = b = input_ptr = -( c == (out = b))];
            stack[b++] = stack;
            stack_ptr = ++b;
            chicken(--b);
            input_ptr = ++b;
            stack_ptr++;
        }
    }

    // either one character from the code
    // or a number of chickens to be interpreted as code
    b = out[input_ptr++];

    if(c)
    {
        // parsing
        if(b)
        {
            if(b == '\n')
            {
                // start counting on the top of the stack
                stack[++stack_ptr] = 0;
                return out = chicken(c + 1, 0);
            }
            else
            {
                // call chicken again, if:
                // 1. input it ' ' or '\r'
                // 2. input is 'chicken'
                // In the latter case, increment the top of the stack
                return out =
                    (b == ' ' | '\r' == b) ||
                    ((b == "c" &
                    out[input_ptr++] == "h" &
                    out[input_ptr++] == "i" &
                    out[input_ptr++] == "c" &
                    out[input_ptr++] == "k" &
                    out[input_ptr++] == "e" &
                    out[input_ptr++] == "n") &&
                    ++stack[stack_ptr]) ?
                        chicken(c)
                    :
                        // otherwise, error
                        ["Error on line " + c + ": expected 'chicken'", stack_ptr = c++ -c];
            }
        }
        else
        {
            // parsing is done, continue running the code
            return out = stack;
        }
    }
    else
    {
        // run the code
        // out is the stack at this point
        console.assert(out === stack);

        var top = out[stack_ptr];

        if(b)
        {
            (b = --b? --b? --b? --b? --b? --b? --b? --b? --b?

                /* n push */            stack_ptr++ && --b
                /* 9, BBQ */            : '&#' + top + ';'
                /* 8, fr */             : out[out[--stack_ptr] && (input_ptr += top), --stack_ptr]
                /* 7, peck */           : out[out[top] = out[--stack_ptr], --stack_ptr]
                /* 6, pick */           : out[out[input_ptr++]][top]
                /* 5, compare */        : out[--stack_ptr] == top
                /* 4, rooster (mult) */ : out[--stack_ptr] * top
                /* 3, fox (sub) */      : out[--stack_ptr] - top
                /* 2, add */            : out[--stack_ptr] + top
                /* 1, chicken */        : stack_ptr++ && "chicken");

            // push result on stack
            out[stack_ptr] = b;

            // next instruction
            return out = chicken();
        }
        else
        {
            /* 0, terminate */
            return top;
        }
    }
}

var read = require("fs").readFileSync;

console.assert(chicken("","chicken") === "chicken");
console.assert(chicken("test foo", read("echo.chicken") + "") == "test foo")
console.assert(chicken("", read("hello.chicken") + "") == "&#72;&#101;&#108;&#108;&#111;&#32;&#119;&#111;&#114;&#108;&#100;");


This looks a lot better! Good job!

Nitty-gritty stuff:

better cleanup in the constructor

You hava a lot of the following idiom in the constructor:

if(condition) {
  glDeleteShader(shader_id);
  throw something;
}

This is a little fragile, since should you make the class more complex, that's a lot of places to refactor. The following would be better:

try {
  //most of the constructor in here
  ...
  if(condition) throw something;
  ...
}
catch(...) {
  glDeleteShader(shader_id);
  throw;
}

ifstream can throw its own exceptions if you tell it to

ifstream input_stream;
input_stream.exceptions( std::ios::failbit );
input_stream.open(path, std::ifstream::in | std::ifstream::ate);

Use iterators when converting a vector to a string

std::string info_log(log_output.data());
vs
std::string info_log(log_output.begin(), log_output.end());

The second one is better because it works whether there is a null terminator or not. It also removes a strlen() call from the code, which is a O(N) operation.

That's actually all I've got. Good job once again.


Your class is InterviewQuestion, if it is for an interview, then there's a few other things to consider, in addition to whether or not you get a reasonably efficient solution.  Whilst a bad solution will probably rule you out, a non-optimal solution may be acceptable depending on other factors.

Seperation of concerns

Finding the list of unique product items seems like it's a different concern to printing the list out to the console.  Rather than printing the items out directly, it would be better to return the list of items and then print them from the caller.  Not only does this demonstrate that you're thinking about reuse, but it also makes the code easier to write automated tests (for a given set of inputs, you can test against the expected results).

Naming

Naming is fairly important for readability.  You variable names are mostly appropriate, but a few small things.  Your method getUniqueProduct doesn't return anything, which is misleading.  productRetailer is a collection of mappings, rather than a single product retailer.  Something like productRetailerMappings might be more descriptive.  target refers to a retailer, so targetRetailer would make this clearer, otherwise given the context it might be expected that it's the targetProductId.

Consistency

Modern IDE's can auto-format your code for you.  Inconsistencies suggest that either you don't use your IDE effectively, or that you lack attention to detail.  Both of these are things that interviewers are going to consider.  Two obvious things that stand out are sometimes there's ) { and sometimes there's ){.  A missing space may seem minor, but it is noticeable.  Another is blank line after at the top of the if block.  Sometimes you have one, sometimes you don't.

To continue...or not

if(count[item]>1){
    continue;
}else
    System.out.println(item);

It's almost always preferable to use {} around your if/else clauses.  Doing it for one side of an if, and not for the else, when they're both one-line is unnecessarily confusing.  The else is also redundant in this case, since if the if is triggered, the following code won't be executed anyway, you don't need the else.  Where possible you want to avoid introducing unnecessary nesting.  Since there's nothing else after the println that's executed, inverting the if would also make the code cleaner, since you wouldn't need the branch condition:

if(count[item]==1) {
    System.out.println(item);
}

Constants can help readability

You're using a two dimensional array, with a fixed size.  Have two constants, one for the ITEM_COUNT and one for the RETAILER_ID would help in understanding.  It's not obvious from this line:

if(target == productRetailer[i][1]) {

What '1' is referring to (retailer or item).


Javascript objects listening to their own events

You could do this, but it's not really useful.

This code is just easier to read:

MyModule.prototype.updateBasket = function() {
    var self = this,
        url  = this.options.url;

    $.ajax(url)
        .done(this.done)
        .fail(this.fail)
        .complete(this.complete);
};

MyModule.prototype.done = function(data) {
    // Do something when done
};

MyModule.prototype.fail = function(data) {
    // Do something when request failed
};

MyModule.prototype.complete = function(data) {
    // Do something no matter what
};

And you could give more meaningful names to your methods.

Event emitters are useful when you're playing with different objects that you don't want to link together.


I'm just a beginner myself but I feel like I can point out a few things in this code.

First, I would add some white space at the top of the file here:

#import "ESFlashingErrorBar.h"
#import "ESThemeManager.h"
@implementation ESFlashingErrorBar
#define kNumOfPoints    7
int lastFlash;

Instead I would do this for increased readability:

#import "ESFlashingErrorBar.h"
#import "ESThemeManager.h"

@implementation ESFlashingErrorBar

#define kNumOfPoints    7
int lastFlash;

That is a minor niggle but it's the first thing I noticed.

Next, I would not use #defines but rather do constants.  If you are going to do defines, I would make the variable all capitalized, but from my understanding defines are harder to debug than using a constant like so:

static const int kNumPoints = 7

I don't know why you are defining lastFlash outside of the methods of the class.  I guess just for simplicity?  But it is still confusing what it is doing there and why it starts out without being assigned a value.  Maybe add a comment to explain its purpose?

Many of your variable names need some help. It is not immediately clear what perItemWidth means.  Nor is it clear what mA is or what exPoint means.

It is not good practice to use the dot accessors inside the initialization method, such as this:

 self.backgroundColor = [UIColor clearColor];
 self.points = mA;

Instead access the variable directly like _points.  The reason for this is that the instance of the class may not be fully initialized and this can lead to unexpected behavior.  However, now that I think about it, if self.backgroundColor is part of the superclass, then it is in fact acceptable to access it with the dot accessors, because when you call self = [super initWithFrame:frame];, the superclass is in fact fully initialized at that point and therefore safe.

Personally I would break out everything involving the while loop into another method, rather than doing that work in the initialization.  I'm not totally sure that this is best practice, but I do think it would make the code easier to understand.

Bonus points for overriding the set: methods.  It appears that this simplifies the code compared to what it would take to do this otherwise.  However, when you do this, it may not be clear to someone else using the code that calling .color or .character is going to modify all of the points. Maybe just comments in the header file to indicate that this is what will happen?  I might be totally wrong here though, so take that with a grain of salt.

Speaking of comments, there are absolutely none in the code.  I know that the overuse of comments can be a bad thing, but I think a few comments about the overall flow of what is happening in the class would be helpful for someone else trying to understand it, especially inside of the flashPoint method.

As for making the code simpler overall, I can't think of any ways to do this.  Maybe someone else will be able to provide feedback on that.


According to this jsperf test, there is no consistent difference between parsing a string literal with and without escape sequences.

There are differences depending on what browser you use, but they are quite small, and Chrome even seems to parse strings with escape sequences faster than strings without.


Given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix

Hide implementation details of Trie

root should be private
current search and findWords methods should be private
write public version of search: should take only a String and call the private one
make TrieNode a private static inner class of Trie

Change storage of children

Storing 26 pointers, most of which will be null in regular usage, is wasteful. You should use a more compact data structure; perhaps a TreeMap<Character, TrieNode>. You could even extend TreeMap for a cleaner interface.

Only store characters once

You effectively store each character in two places: explicitly in TrieNode.content, and implicitly by the node's position in its parent's children array (or in the key of the children map if you take my recommendation above). If you grab the character in the previous round of recursion, you should not need the TrieNode.content field at all.

Fix bug using StringBuilder

In findWords if a node is a word and has children, the character will be appended twice.

Minor tweaks

write a Trie(Iterable<String> content) constructor
no need to store '*' in root
use List.forEach() instead of List.stream().forEach()
separate search functionality into findNode and findWords
change if (blah == true) to if (blah)
pass functions instead of using lambdas when possible
fix indentation -- your IDE should do this for you

Finally, variables names can often be shorter if their purpose is clear in context. For example: currentNode vs current. A lot of people say to "use descriptive variables names"; however, brevity can also help with readability as well.

My stab at the changes

class Trie {
    private static class TrieNode extends TreeMap<Character, TrieNode> {
        public boolean isWord;
    }

    private TrieNode root;

    public Trie(Iterable<String> content) {
        this();
        content.forEach(this::insert);
    }

    public Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            current = current.computeIfAbsent(word.charAt(i),
                              k -> new TrieNode());
        }
        current.isWord = true;
    }

    public List<String> search(String word) {
        List<String> results = new ArrayList<>();

        TrieNode node = findNode(word, root, 0);
        if (node == null) {
            return results;
        }

        findWords(node, new StringBuilder(word), results);
        return results;
    }

    private TrieNode findNode(String word, TrieNode current, int index) {
        if (index == word.length()) {
            return current;
        }

        Character ch = word.charAt(index);
        if (!current.containsKey(ch)) {
            return null;
        }

        return findNode(word, current.get(ch), ++index);
    }

    private void findWords(TrieNode current, StringBuilder sb, List<String> results) {
        current.forEach((Character ch, TrieNode child) -> {
            StringBuilder word = new StringBuilder(sb).append(ch);
            if (child.isWord) {
                results.add(word.toString());
            }
            findWords(child, word, results);
        });
    }
}

class TrieTest {
    public static void main(String args[]) {
        Trie trie = new Trie(Arrays.asList(new String[] { "dog", "dee", "deer", "deal" }));

        trie.search("de").forEach(System.out::println);
        System.out.println();

        trie.search("do").forEach(System.out::println);
        System.out.println();
    }
}


Find all triplets in array that add up to a given sum

Arrays.asList(other.x, other.y, other.z) already returns a new list. There is no need to add the result to a new ArrayList you could just use

numbers.containsAll(Arrays.asList(other.x, other.y, other.z));

You creating some unnecessary objects that still need to be cleaned up by the garbage collector. e.g.: this could save you some memory. Instead of:

numbers.addAll(new ArrayList<>(Arrays.asList(x, y, z)));

use

numbers.add(x);
numbers.add(y);
numbers.add(z);

Here you can save one lookup in the HashMap. Instead of:

if (lookup.containsKey(complement)) {
    int indexes[] = lookup.get(complement);
    ...

you can write:

int indexes[] = lookup.get(complement);
if (indexes != null) {
    ...


Implementing Functor Instance for `ITree`

This looks mostly fine to me. If you wrote this code in a real codebase, I would not have any major qualms with it. Here are some nitpicks.

The strangest thing to me was just the way you defined a separate function, iTreeMap, then used that as the definition of fmap. I would just define fmap directly within the body of the instance definition—no need to give it a separate name.
The parentheses around ITree in the instance head are redundant. You could just write Functor ITree instead.
Given that the value inside of a Leaf is a function, the use of the function instance of fmap within the definition of iTreeMap is a bit of genericism that I think is unnecessary. I would probably just use (.) and make the composition explicit, but that’s really personal preference.

With those above changes in place, the instance would look like this:

data ITree a = Leaf (Int -> a) | Node [ITree a]

instance Functor ITree where
  fmap f (Leaf x) = Leaf $ f . x
  fmap f (Node xs) = Node $ map (fmap f) xs

However, in real code, I wouldn’t actually do that at all. With the DeriveFunctor language extension, you could just ask GHC to write the Functor instance for you. Therefore, in real Haskell code, I would probably just write this:

{-# LANGUAGE DeriveFunctor #-}

data ITree a = Leaf (Int -> a) | Node [ITree a]
  deriving (Functor)

But that’s probably against the spirit of the exercise. :)


JavaScript function which checks the count of words in a string

This seems a bit like reinventing the wheel. I'm not sure on what you're trying to achieve here, but it doesn't look like you're accounting for hyphen separated words, so data-type counts as one word.

It looks like to me that this is just splitting on the space, and it could be replaced by String.split(' ').length

I'm sorry if I missed the point here. But I'm gonna need you to explain it better why you need such a function in the first place.

var sentence = document.querySelector('#sentence');
var exec = document.querySelector('#exec');
var result = document.querySelector('#result');

function execHandler() {
  result.value = sentence.value.split(' ').length;
}

exec.addEventListener('click', execHandler);
.wrap {
  margin: 20px auto;
  width: 900px;
}

.wrap label {
  display: inline-block;
  width: 150px;
}

.wrap div {
  margin: 20px 0;
}

      Sentence to check:

    <input type="text" id="sentence"
           value="one Two2 Three 4four five123"
           size="80" />

    <button id="exec">Exec</button>

      Count of words:

    <input type="text" id="result" />


Instead of throwing an Error, an AssertionError would be better.
An Error is too broad.
An AssertionError conveys better that instantiating is an error by the programmer, violating a precondition.
(The only way this error will be triggered is if you try to create an instance within this class.)

private GCD() {
    throw new AssertionError("Instantiation not allowed.");
}

As this class has only private constructors,
it cannot be extended:
derived classes would need to call a constructor in the super-class,
but none are available.
To make the intention perfectly clear that this class is not designed to be extended, it's good to make it final.


Unless I'm mistaken, the MouseMove event fires everytime the mouse coordinates change - and when you're moving the mouse across the chart, that's a couple dozens (if not hundreds) of times in a very limited amount of time (<1 second!).

There are a couple things that stand out in your code:

Your indentation is off. You need to give the Tab button the lovin' it deserves!
An empty Catch block is bad. You're swallowing exceptions without ever knowing if anything has gone wrong. Don't do that!
GetAxisValuesFromMouse should be returning a Point, not an array of doubles. Returning a simple struct instead of an array can help you gain a couple cycles - my background is c# so the syntax might be a little off here:

Public Structure PointD ' named after System.Drawing.PointF which is using Float/Single.
    Public X As Double
    Public Y As Double
    Public Sub New(ByVal XValue As Double, ByVal YValue As Double)
        X = XValue
        Y = YValue
    End Sub
End Structure

Private Function GetAxisValuesFromMouse(x As Integer, y As Integer) As Double()

    return New PointD(chartArea.AxisX.PixelPositionToValue(x), _
                      chartArea.AxisY.PixelPositionToValue(y))

End Function

The chart object is abstracting a lot of plumbing, and I suspect this plumbing is where your bottleneck is. Your code removes a series, creates a new data point, adds a new series and adds the data point to the new series; the chart probably gets redrawn when you remove the series, and again when you add it, and once more when you add the point. It would be much more efficient to move the datapoint instead of recreating the series everytime the mouse moves by a pixel.

I suggest you only create the data point when you don't already have it (i.e. only once!); keep a reference to your data point, and simply change its coordinates per the mouse. If that alone doesn't do it, you'll need code that finds the data point and moves it. Since you're drawing the point on its own series, that shouldn't be too hard to achieve. The chart will only redraw itself when the coordinates of the point have changed, and when the mouse moves you'll only be fetching the mouse coordinates and assigning new values to the point's XY values. I'm sure this would be much faster.

And yeah, exceptions incur some performance hit, so if your code is swallowing exceptions that is another possible bottleneck, but if you're only moving a data point around, you shouldn't have to worry about that.


This program is organized in a bizarre way.

t1, t2, t1c, and t2c are static variables, which essentially make them "global" state.  This makes your code difficult to follow.
t2c is a write-only variable — assigned but never used.
t1c is only barely used — you're only ever interested in the first character.
It's not obvious what the purpose of ChangeString() is.  What are you changing?  At first glance, it appears to transform the input (which consists of a single letter and a startIndex) into a "yes"/"no" string.

I would expect the program to follow this outline:

using System;

public class TOPSES
{
    public static void Main()
    {
        for (int t = int.Parse(Console.ReadLine()); t >= 0; t--)
        {
            string s1 = Console.ReadLine(),
                   s2 = Console.ReadLine();
            Console.WriteLine(IsRotation(s1, s2) ? "yes" : "no");
        }
    }

    public static bool IsRotation(string s1, string s2)
    {
        …
    }
}

Notes:

Main() should be public.
A for loop gathers all the code related to t together, to make it easy to see what it's for.
Avoid unnecessarily separating declarations and assignments.

The algorithm you use is also too complicated: you're looking for places in t2 that start with the initial character of t1, then checking if t2, if sliced and reassembled there, matches t1.  But why use string.IndexOf(Char, Int) when you could just do string.IndexOf(string)?

public static bool IsRotation(string s1, string s2)
{
    return s1.Length == s2.Length &&
           (s2 + s2).IndexOf(s1) >= 0;
}

This involves just one string concatenation, and no slicing and dicing.


Replace characters using multiple dependent regular expression substitutions

I can't say it would be more Pythonic, but we can reduce your number of re.sub() calls from 3 down to 2.

First, we just eliminate all of the invalid letters:

valid_chars = re.sub('[^-/_ 0-9a-zA-Z]', '', field_value)

Then, replace occurrences of one or more '-', '/', '_' and ' ' characters with a single underscore, convert to title case, and return:

return re.sub('[-/_ ]+', '_', valid_chars).title()

Since the try ... except block is unconditionally re-raising the raised exception, it is not really adding much, and could probably be eliminated.

When using a regex over and over, it is usually more efficient to compile the regular expression once, and then reuse the compiled regular expression object.

INVALID_CHARS = re.compile('[^-/_ 0-9a-zA-Z]')
UNDERSCORE_CHARS = re.compile('[-/_ ]+')

def correct_invalid_char(field_value):
    """
    Correct field values by replacing characters, removing non-alphanumeric,
    non-numeric characters, duplicate underscores, and changing to title case.
    """

    valid_chars = INVALID_CHARS.sub('', field_value)
    return UNDERSCORE_CHARS.sub('_', valid_chars).title()

A quick "Hello world"-ish test:

>>> correct_invalid_char('Hello EMPEROR / ***WoRlD_-=-_lEaDeR***')
'Hello_Emperor_World_Leader'


ASP.net proper login - logout classes - control login status

In addition to losing the hungarian notation there are a few things worth mentioning:

Don't use try-catch construction with empty 'catch' clause. It is almost always a bad idea to hide an exception if it was thrown.
It would be better to check explicitly if the key is in the collection using appropriate methods. BTW exception handling is quite expensive speedwise and explicit checking will work faster.
Try to refactor your controlOfLoginStatus() method into several distinct functions with more meaningful purpose.
Refactor your database code into separate class.
Use parameterized queries while working with database. It will save you from sql injections and it will make your queries run faster.


I see two things right off the bat that may help:

Calculate $maxvalue inside makehill() so you don't have to calculate it after
Do the normalization and flattening in 1 pass. Also, you can do the flattening in a single function call. You're basically raising each value to the 8th power, so use the power function. I don't know perl real well, but it's usually called pow() and takes a value and an exponent.

The other thing that looks problematic is setting each individual pixel through a function call. Is there any way to pass a buffer of memory to ImageMagick? If so, it would probably faster to do that.


What if the script renames file "a.zip" to "b.zip", and both files "a.zip" and "b.zip" exist in the same directory?


Firstly, make it correct.

N is integral, you could make it E so you don't accidentally do integer arithmetic.

N-1 is wrong.

Rename average to mean.

Don't hardcode E.

You get:

template <typename It, typename E = typename std::iterator_traits<It>::value_type>
E std_dev(It begin, It end){
    E N = std::distance(begin, end);
    E const mean = std::accumulate(begin, end, E()) / N;
    auto sum_term = [mean](E init, E value)-> E { return init + (value - mean)*(value - mean); };
    E variance = std::accumulate(begin, end, E(), sum_term);
    return std::sqrt(variance / N);
}

Slightly stylized, with comparison to Boost Accumulator:

Live On Coliru

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>

template <typename It, typename E = typename std::iterator_traits<It>::value_type, typename R = typename std::common_type<double, E>::type>
R std_dev_boost(It begin, It end){
    namespace ba = boost::accumulators;

    ba::accumulator_set<R, ba::stats<ba::tag::variance> > accu;
    std::for_each(begin, end, std::ref(accu));
    return std::sqrt(ba::variance(accu));
}

template <typename It,
    typename E = typename std::iterator_traits<It>::value_type,
    typename R = typename std::common_type<double, E>::type>
R std_dev(It b, It e)
{
    R N          = std::distance(b, e);
    R const mean = std::accumulate(b, e, R{}) / N;
    R variance   = std::accumulate(b, e, R{}, [mean](R a, E v)-> R { return a + (v-mean)*(v-mean); });
    return std::sqrt(variance / N);
}

int main(){
    std::vector<int> stuff {35, 34, 36, 39, 35, 35, 35, 35, 35};
    std::cout << std_dev_boost(stuff.begin(), stuff.end()) << "\n";
    std::cout << std_dev      (stuff.begin(), stuff.end()) << "\n";
}

Prints

1.34256
1.34256


Geeks for Geeks: Trapping Rain Water Problem - time limit exceeded

Your current solution is \$ O(n^2) \$ because of the nested loops.
There are a couple ways to solve this in \$ O(n) \$ time without having to use any extra arrays. One way is to go from left-to-right while keeping track of the highest wall you’ve seen so far, then do the same thing from right-to-left until you reach the last highest wall you saw when going left-to-right. It’s \$ O(n) \$, but you‘ll need to look at almost every array index twice if the wall at index 0 is the highest.
The other way is to alternate between going from left-to-right or right-to-left depending on which side had the last highest wall seen. If you do it like this then you’ll always only need to look at each index one time. You can write the function like this:
int trappingWater(int arr[], int arr_size)
{
    if (arr_size <= 0)
    {
        return 0;
    }

    int water = 0;

    int max_left = arr[0];
    int max_right = arr[arr_size - 1];

    int left_ind = 0;
    int right_ind = arr_size - 1;

    while (left_ind < right_ind - 1)
    {
        if (max_left <= max_right)
        {
            left_ind += 1;
            if (arr[left_ind] > max_left)
            {
                max_left = arr[left_ind];
            }
            else
            {
                water += max_left - arr[left_ind];
            }
        }
        else
        {
            right_ind -= 1;
            if (arr[right_ind] > max_right)
            {
                max_right = arr[right_ind];
            }
            else
            {
                water += max_right - arr[right_ind];
            }
        }
    }
    return water;
}

For your current code, it would be better if you avoided using namespace std; to avoid possible name conflicts: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. You could also use better variable names in some places. There are some spots where you explain what the variable is in a comment right after making the variable. Instead of doing that, you could just give the variable a more complete name. Then you don’t have to check the comment if you forget what it is. Here’s what your current code would look like with those two things in mind:
int maxValueInArray(int arr[], int start, int end){
    if(start == end) return arr[start];
    int maxHeight = 0;
    for(int i = start; i<=end; i++){
        maxHeight = std::max(arr[i], maxHeight);
    }
    return maxHeight;

}

int trappingWater(int arr[], int arrSize){

    // Your code here
    int ans = 0;
    for(int i = 1; i<arrSize-1; i++){
        int currentWall = arr[i];
        int maxLeft = maxValueInArray(arr,0, i-1);
        int maxRight = maxValueInArray(arr, i+1, arrSize-1);
        if(maxLeft == currentWall || maxRight == currentWall) ans += 0; // 8, 8, 3
        else if(maxLeft >= currentWall && currentWall >= maxRight) ans += 0; //8, 5, 3
        else if(maxLeft <= currentWall && currentWall <= maxRight) ans+= 0; //2, 4, 7
        else if(maxLeft < currentWall && currentWall > maxRight) ans+= 0; //5, 7, 6
        else ans += std::min(maxLeft, maxRight) - arr[i];
    }
    return ans;
}

// { Driver Code Starts.

int main(){

    int testCases;
    std::cin >> testCases;

    while(testCases--){
        int arrSize;

        std::cin >> arrSize;

        int arr[arrSize];

        //adding elements to the array
        for(int i =0; i<arrSize; i++){
            std::cin >> arr[i];
        }

        //calling trappingWater() function
        std::cout << trappingWater(arr, arrSize) << std::endl;

    }

    return 0;
}  // } Driver Code Ends


Query optimization PHP for string concatination

For now, one solution is to concatenate the options into a string while the answer is persisted. This is part of my FormToArrayTransformer:

switch ($_question->getFormField()->getType()) {
    case FormField::CHOICE:
        $content = '';

        foreach($answer as $_key=>$option) {
            $surveyAnswer->addFormOption($option);
            if ($_key == 0) {
                $content .= $option->getName();
            } else {
                $content .= ', ' . $option->getName();
            }
        }

        $surveyAnswer->setContent($content);
        break;

Note that now both the FormOption entities and their string representation is stored. When viewing you don't have to iterate over the options anymore but simply calling answer.getContent() will do. This saved me 2300 queries in a table for 200 forms.

I am still unsure why this is so.