First of all, stop using system("pause"); and system("cls");.  Both of those are not portable, and are silly ways of achieving what you want.  Take a look here for an actual solution.

Secondly, you are seeding the random number generator every iteration.  This is not only unnecessary, it is harmful: if you do this in a program that calls rand more than once a second, you will get the same result each call.  Even if you are only accessing it once a second (as you may be here), it is bad practice in any case, and can lead to a decrease in randomness.

Thirdly, I think you're getting a little far with splitting things into functions.  It might make sense to split the move-reading part into a separate function if you're going to perform input validation, but I think it currently just complicates matters.

Your CalculateResults function is overcomplicated.  If 0 is rock, 1 is paper, and 2 is scissors, and x and y are the choices of the players, you can tell who won with (3+x-y)%3.  If the result is 1 then x has won; if it is 2, then y has won; otherwise (if it is 0) there has been a tie.

Further stylistic issues: you should fix your indentation, turn the do ... while loop into a while(true) or for(;;) loop, stop using using namespace std;, and disable precompiled headers (they offer no benefit for a single-file solution).  You should also output '\n' instead of std::endl unless you explicitly want to flush the stream; an expression like std::cout << std::endl << std::endl simply doesn't make sense.

By the way, if you're using Google to solve your C++ problems, you're likely picking up a lot of information that's very wrong.  Make sure you have a good book to learn from, such as Accelerated C++.

Your code could be simplified to this, although the behaviour isn't quite the same:

#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
#include <cstdlib>

std::string numberToWeapon(int n) {
    switch (n) {
       case 0: return "rock";
       case 1: return "paper";
       case 2: return "scissors";
    }
    assert(!"Invalid parameter");
}

int main() {
    std::cout << "Rock-Paper-Scissors v1.0\n";

    int playerScore = 0;
    int ourScore = 0;
    std::srand(static_cast<unsigned int>(time(0)));

    while (true) {
         int playerMove;
         std::cout << "Please enter 1 for rock, 2 for paper, or 3 for scissors.\n";
         if (!(std::cin >> playerMove))
             return 0;
         --playerMove;
         if (playerMove < 0 || playerMove > 2) {
             std::cout << "Invalid input.\n";
             continue;
         }

         int ourMove = rand()%3;

         std::cout << "You played: " << numberToWeapon(playerMove) << ". ";
         std::cout << "We played: " << numberToWeapon(ourMove) << ".\n";
         switch ((3 + playerMove - ourMove) % 3) {
             case 0:
                 std::cout << "The game is a tie.\n";
                 break;
             case 1:
                 std::cout << "You won!\n";
                 ++playerScore;
                 break;
             case 2:
                 std::cout << "We won!\n";
                 ++ourScore;
                 break;
         }

         std::cout << "The score is currently:\n";
         std::cout << "You - " << playerScore << ".\n";
         std::cout << "We - " << ourScore << ".\n";
    }
}

This results in a larger main function, but no global variables.  You can argue on whether that's any better or not: personally, I think it's clear as it is, and I don't see any duplication, but you may want to experiment.

If you are using C++11, you can get even more awesome syntax than the numberToWeapon function, namely:

std::array<4, std::string> weapons = {"rock", "paper", "scissors"};

And then use weapons.at(num) (or weapons[num] if you're sure you're in-bounds).


Python normally promotes duck typing, yours is more statically typed.
You may want to use yield, as your current code possibly uses more memory than needed.
You can check if an item is iterable, and iterate it. Otherwise return the item.

You can do this in two ways either via LBYL or EAFP.

Just using yield can get:

def flatten_list(array):
    for element in array:
        if isinstance(element, int):
            yield element
        elif isinstance(element, list):
            yield from flatten_list(element)
        else:
            raise TypeError("Unsupported type ({})".format(
                type(element).__name__))

Using LBYL and duck typing can then get:

import collections

def flatten_list(array):
    for element in array:
        if isinstance(element, collections.abc.Iterable):
            yield from flatten_list(element)
        else:
            yield element

Using EAFP and duck typing can instead get:

def flatten_list(array):
    for element in array:
        try:
            element = iter(element)
        except TypeError:
            yield element
        else:
            yield from flatten_list(element)

Finally as a side note, if you expect the initial array to have a depth exceeding one thousand, then you may want to instead perform the stack manipulation yourself. So you don't get a stack overflow error.
This can be done with something like:

def flatten(it):
    to_yield = [iter(it)]
    sentinel = object()
    while to_yield:
        item = next(to_yield[-1], sentinel)
        if item is sentinel:
            del to_yield[-1]
            continue
        try:
            item = iter(item)
        except TypeError:
            yield item
        else:
            to_yield.append(item)


What's wrong with static utility classes, versus beans?

Static helper classes makes testing harder. Nick Malik has a good article on this topic: Killing the Helper class, part two.

Mocking non-static methods is closer to OOP and easier than static ones. Another gain is that you'll have simple tests: simple tests for the utility/helper class and simple tests for the clients of the utility class; the tests of the client classes don't have to know the internals of the utility class, and you don't need a DatabaseUtilsTestHelper class to keep in one place the mocking logic for the helper class. The linked article is worth the reading.

Some other notes:

Try not using short variable names like ng. They are hard to read.
persistArticle does not close the transaction in every path. You should rollback it in the finally block if it's still active:

final EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
    ...
    transaction.commit();
} finally {
    if (transaction.isActive()) {
        transaction.rollback();
    }
}

persistArticle does not use the value of max, therefore the getMax call seems unnecessary.


Please spinning it to a separate function. Here is what I think is a little more simpler implementation.

public boolean checkInclusion(String site_i, String site_e, Regex re) {
    if (site_i != null)
        return site_e.matches(re);
    else if(site_e != null)
        return !site_e.matches(re)))
    else
        return true;
}

In your implementation, what happens when the site inclusion has values but does not match, and site_exclusion is null? It seems to not match any of the conditions, which is not in sync with the requirements from my reading.

Also what happens when the site inclusion has values but does not match, and site_exclusion has values that does not match? In your implementation, it seems like site exclusion takes precedence. But that does not seem to be the requirement.

Perhaps I am reading either requirement wrongly or your implementation conditions wrongly?

A rather terse implementation that is same as above is,

public boolean checkInclusion(String site_i, String site_e, Regex re) {
    if (site_i != null) return site_i.matches(re);
    return site_e == null || !site_e.matches(re)
}


First prime number larger than given integer

Things you could improve

Efficiency

As @rolfl stated, you want to use a Sieve of Eratosthenes (+1 to that answer).

I can't see if you are doing this already, but you should be compiling with your compiler's highest optimization level.  With GCC for example, this would be -O3.

Portability

Keep in mind to adhere to the standards as closely as possible, because a system that supports C must adhere to the standards as well.
If you want your program to be as portable as possible, take a look into the AutoTools suite for packaging your program.  This is a bit extreme in your case, since you aren't using external libraries, and your program doesn't have a lot of system dependencies.

Standards

You don't have to return 0 at the end of main(), just like you wouldn't bother putting return; at the end of a void-returning function. The C standard  knows how frequently this is used, and lets you not bother.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.

Use the standard library <stdbool.h> instead of defining your own boolean values.

#define PRIME_FALSE   0     /* Constant to help readability. */
#define PRIME_TRUE    1     /* Constant to help readability. */

It still helps with readability.  And since it is part of the standard in C, systems are guaranteed to have it if they support C.

Syntax/Styling

Don't use goto.

Yes, there are some rare situations where you may find it necessary to use it.  This is not one of them.  A simple break; will suffice in it's place, since you are only breaking out of the inner loop.
Right now you are using a somewhat odd way to test if you have an integer input into the command line arguments.

if (sscanf(argv[1], "%i", &intvar) != 1)

Use argc to test the number of arguments input into the program instead, and isdigit to test if the input contains numbers.

if (argc != 2 || !isdigit(**(argv+1))) printf("Please use an integer parameter to compute the next prime.\n");

Then convert that input into an integer.

int intvar = atoi(*(argv+1));

Note that the order I put it in is important.  We want to test argc first, so we put it first in the test conditional.  If that fails, the second part on the other side of the || isn't even evaluated, and the statements following the conditional are executed.  If we switched those tests around, undefined behavior could occur if we didn't enter in a command line argument.
Use puts() instead of printf() when you aren't formatting your strings.  This allows you to not worry about the newline (\n) character at the end of your printed out strings.

puts("Please use an integer parameter to compute the next prime.");

You don't modify the value of intval within your nextprime() function, therefore the parameter should be declared constant.

int nextprime(const int inval)

You can reduce down one of your test conditionals.

if (inval == 1)
    return (2); /* Easy special case. */
if (inval == 2)
    return (3); /* Easy special case. */

if (inval == 1 || inval == 2) return (inval + 1); /* Easy special case. */


Switch statements in Rock-Paper-Scissors game

Instead of creating a new Item each time you can just use a enum:

public enum Move{
    Paper{
        public boolean canBeat(Move other){
            return other==Rock;
        }
    },
    Scissor{
        public boolean canBeat(Move other){
            return other==Paper;
        }
    },
    Rock{
        public boolean canBeat(Move other){
            return other==Scissor;
        }
    };

    public abstract boolean canBeat(Move other);

    public boolean losesTo(Move other){
        return other.canBeat(this);
    }
}

Then You can keep them in an array (like what is returned by Move.values()) and index into that.

public Item getItem() throws WrongMove {
    int choice = choiceValue(this.move);
    if(choice<0||choice >= Move.values().length)
        throw new WrongMove("Wrong move. Game end");
    else return  Move.values()[choice];
}


I'm not a member of the “goto is evil and must not be used under any circumstances” camp.  Especially in performance-critical low-level routines, it can be useful from time to time.  However, most of the time, the temptation to use goto actually stems from missing a better opportunity to structure the code.  In your example, I'd simply re-structure it like this, which I find is not only more readable but also much shorter.

public static IQueryable<T>
Sort<T>(this IQueryable<T> query,
        String field,
        String direction,
        Expression<Func<T, Int32?>> defaultSort = null)
{
    if (!String.IsNullOrWhiteSpace(field)) {
        try {
            return query.OrderBy(String.Format("{0} {1}", field, direction));
        } catch (NullReferenceException) {
            // NOT FOUND: Field wasn't found just return the original query.
        } catch (ParseException) {
            // NOT FOUND: Field wasn't found just return the original query.
        }
    }
    if (defaultSort != null) {
        query = query.OrderBy(defaultSort);
    }
    return query;
}


I'll answer your primary question first -

Why is it producing 1 char and then immediately consuming that char?

Look at the producing code carefully:

BufferLock.WaitOne();
_Buffer[i % _BuffSize] = (char)(32 + i % 95);
Available++;
Console.WriteLine("Produced: {0}", _Buffer[i % _BuffSize]);
BufferLock.ReleaseMutex();
IsEmpty.ReleaseMutex(); // Try catch removed, but throws quite often

What you're saying is:

Get exclusive access to the buffer (slow)
Add a character to the buffer
Increment a shared field (in a potentially dangerous way)
Release the buffer (slow)
Potentially throw and catch an exception

At the same time your consumer is doing the analogous:

Get exclusive access to the buffer (slow)
Get a character from the buffer
Decrement a shared field (in a potentially dangerous way)
Release the buffer (slow)
Potentially throw and catch an exception

If you start that work at the same time, you're going to end up in a situation where the consumer is first waiting for the producer to release the buffer, then the producer will be waiting for the consumer to release it on every iteration. The threads are basically playing tennis with the Mutex - back and forth, back and forth. Don't forget that acquiring and releasing a Mutex takes a pretty long time - a couple of microseconds - which might be contributing to the 1 produced, 1 consumed pattern as I think the code will be spending most of its time waiting for the mutex operations.

Notes on the implementation

Most importantly (and I think you know this) a Mutex is utterly overkill for inter thread synchronisation.

A Mutex can only be released by the thread that acquired it. So, the consuming thread will never be able to release the IsFull mutex because it will only ever be acquired by the producing thread. The same is true for the IsEmpty mutex - the producing thread will never be able to release it. I'm sure that you noticed the exception but rather than trying to figure out why it was happening, you've caught and ignored the exception. Having a reason to ignore all exceptions from an operation is quite rare - seeing an empty catch with no comment is usually a sign that something's not right.

Locks/mutexes etc. are expensive - minimize where possible and always hold the lock for the least amount of time possible.

Mutex implements IDisposable, as your MutexProducerProducerConsumer class holds references to them at the class level it should also implement IDisposable.

Your waits are just spin blocking. IsEmpty.WaitOne(1000) will wait up to one second to acquire the mutex.

while (Available < 1)
{
    Console.WriteLine("Wait Consumer:");
    IsEmpty.WaitOne(1000);
}

Your consumer will acquire the mutex and never release it. So your code is basically:

while (Available < 1)
{
    Console.WriteLine("Wait Consumer:");
}

Producer/consumer is more easily implemented with a queue of work. It's weird that your consumer has to know how many things the producer will create.

Some general style points:

This was mentioned in your previous question. I don't think you can actually fall foul of this here, but it's worth remembering that ++ and -- aren't atomic operations.

If the type of the RHS of an assignment is obvious, use var.

You don't need to create an explicit delegate here either:

Thread p = new Thread(new ThreadStart(producerConsumer.Produce));

can be more concisely written as:

var p = new Thread(producerConsumer.Produce);


Generic Repository, UnitOfWork and IOC container

First, I would caution against using the generic repository + unit of work pattern that was super trendy a few years ago because it has problems not unlike the problems you're facing (along with problems stemming from the fact that EF crosses traditional DAL/Domain/BL boundaries). Simply put, I would not use repositories with EF unless absolutely necessary, and if I had to, I would not use the generic repository pattern.

If you're hell-bent on using this pattern, then you will need to understand the origins of the problem you're facing. Because you have a generic type being returned by your UnitOfWork "factory," you aren't able to instantiate it during your bootstrapping, you are being forced to to instantiate it on-demand at runtime, resolving using the type you're using in your UnitOfWork method call.

If you are okay with using the same repository instance for all of your resolutions, then just make your objects require Repository<SomeType> in your object constructors or properties with public setters, then use RegisterGeneric(). You can see how that is used here. This bypasses the entire "at runtime" requirement.

If you want to maintain the pattern of fetching a repository using a method, then you need to treat your UnitOfWork class as a factory and use dynamic instantation.


how to make pagination more efficient with large arrays and db support

1) Simply don't pass large arrays, use some abstraction.

2) Once you add the abstraction, you can provide db support.

The following abstraction might show how to do it:

EDIT: ok so i have added some more to point at the core of your problems:

The paginator doesnt really need the setters to be part of its interface.

Also see I use Iterator to represent the page items, instead of array. The array will only be used in specific implementation. You should avoid the array type in the abstraction.

interface PaginatorInterface
{
    public function getItems();

    public function getCurrentPageNumber(): int;

    public function getNumberOfPages(): int;

    public function getTotal(): int;

    public function getTotalOnCurrentPage(): int;

    public function getTotalPerPage(): int;
}

In fact, the class implementing that interface doesnt really need those setters too. It's actualy not even desired.

Also the paginator can do simple computations. You dont have to precompute and assign static values which actualy opens space for corrupted state.

class Paginator implements PaginatorInterface
{
    private $pageNumber;
    private $itemsPerPage;
    private $items;
    private $total;

    public function __construct(int $pageNumber, int $itemsPerPage, \Iterator $pageItems, int $total)
    {

        if ($pageNumber < 1) {
            throw new \InvalidArgumentException();
        }
        if ($itemsPerPage < 1) {
            throw new \InvalidArgumentException();
        }
        $this->pageNumber = $pageNumber;
        $this->itemsPerPage = $itemsPerPage;
        $this->items = $pageItems;
        $this->total = $total;
    }

    public function getItems(): \Iterator
    {
        return $this->items;
    }

    public function getCurrentPageNumber(): int
    {
        return $this->pageNumber;
    }

    public function getNumberOfPages(): int
    {
        return \ceil($this->getTotal() / $this->itemsPerPage);
    }

    public function getTotal(): int
    {
        return $this->total;
    }

    public function getTotalOnCurrentPage(): int
    {
        if ($this->items instanceof \Countable) {
            return \count($this->items);
        }
        return \iterator_count($this->items);
    }

    public function getTotalPerPage(): int
    {
        return $this->itemsPerPage;
    }
}

Here I define the page provider (extended by getTotalCount method since my edit):

interface PageProviderInterface
{
    public function getTotalCount(): int;
    public function getPage(int $offset, int $limit): \Iterator;
}

You then use the page provider within a paginator factory (that is your pagination interface but it actualy is paginator factory so i named it that way).

interface PaginatorFactoryInterface
{
    public function createPaginator(int $page, int $pageSize): PaginatorInterface;
}

class PaginatorFactory implements PaginatorFactoryInterface
{
    /** @var PageProviderInterface */
    private $pageProvider;

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

    public function createPaginator(int $page, int $pageSize): PaginatorInterface
    {
        $total = $this->pageProvider->getTotalCount();
        $offset = ($page - 1) * $pageSize;
        if ($offset >= $total) {
            $items = new \EmptyIterator();
        } else {
            $items = $this->pageProvider->getPage($offset, $pageSize);
        }
        return new Paginator($page, $pageSize, $items, $total);
    }
}

And lastly some implementation of the page provider.

The array one which provider slices of an array that resides in memory:

class ArrayPageProvider implements PageProviderInterface
{
    private $items;

    public function __construct(array $items) {

        $this->items = $items;
    }

    public function getTotalCount(): int
    {
        return \count($this->items);
    }

    public function getPage(int $offset, int $limit): \Iterator
    {
        return new \ArrayIterator(\array_slice($this->items, $offset, $limit));
    }
}

And the silly PDO implementation, which would need some improvement to be actualy usable, but you should get the point:

class DbPageProvider implements PageProviderInterface
{
    private $pdo;
    private $table;

    public function __construct(\PDO $pdo, string $table) {
        $this->pdo = $pdo;
        $this->table = $table;
    }

    public function getTotalCount(): int
    {
        $statement = $this->pdo->prepare('select count(*) from ' . $this->table);
        return $statement->fetchColumn();
    }

    public function getPage(int $offset, int $limit): \Iterator
    {
        $statement = $this->pdo->prepare('select * from ' . $this->table . ' limit ' . $offset . ',' . $limit);
        $result = $statement->execute();
        $i = 0;
        while ($row = $result->fetch()) {
            yield $i++ => $row;
        }
    }

}

And that should actualy be all you need. No need for some crazy collection outsourcing or too much of new new new in one method. Keep it simple and remember the naming is really important for whoever wants to understand the code.

Oh and one more, you hade a getViewData() method there, but that should be done by someone else:

function getPaginatorViewData(PaginatorInterface $paginator) {
  return [
    'elements' => $paginator->getItems(),
    // ...

  ];
}

This could be a global function, or it could be static method of its own class, or could even be elevated to an interface level. But actualy i dont think it belong to the lib, it may be part of some framework bundle, or something like that, but not the lib itself. The moment it becomes shapeless array, it becomes hard to work with...

And here is a simple example of usage:

// in DI container
$pageProvider = new DbPageProvider($pdo, 'users');
$usersPaginatorFactory = new PaginatorFactory($pageProvider);

// in lets say /users/list constroller we have the paginator factory injected
// $pageNumber is coming from request
$paginator = $this->usersPaginatorFactory->createPaginator($pageNumber, 20);

// maybe you wanna pass this to laravel view?
return view('users.list', ['paginator' => $paginator]);
// or maybe if you defined the getPaginatorViewData() function
return view('users.list', getPaginatorViewData($paginator));

PS: try to avoid constructor with $options array. It really is better to name all the parameters separately, even omit default value, let the user or a factory (if there is one) decide. Default values usualy just complicate things even if it seems the opposite at first glance...

oh and PS2: although this should have been a big warning on the beginning.
Dont use eval(), avoid references, definitely dont return references, avoid instantiation of classes by string containing class name. The Pagination::factory is completly wrong. Immediately get rid of that file and never write anything like it again!!!


Misc.:

Modern compilers all support #pragma once. It's much cleaner than old-school include guards.
You need a #include <cassert>

Code Improvements - Class:

Use typedefs to reduce code duplication (and if you ever need to change the clock type, it's much simpler). These should be public.

using clock_t = std::chrono::high_resolution_clock;
using duration_t = clock_t::duration;

Store the duration type at the resolution of the clock, rather than using duration<double>.

clock_t::time_point last_time_point;
duration_t time_duration;

The hours function should be const, but I'd actually recommend replacing it with a function that returns the time in the most accurate units. The stopwatch class shouldn't worry about time conversions - only the user code knows the desired accuracy, and can duration_cast if necessary:

duration_t get_elapsed_time() const
{
    return time_duration;
}

Since the code asserts on the running state in start() and stop(), we probably need a function to check if the stopwatch is running:

bool get_is_running() const
{
    return is_running();
}

Code Improvements - Output:

Now that we have get_elapsed_time(), the ostream operator doesn't need to be a friend.
Use auto here too.
Doing the printing separately from extracting each unit of time makes things clearer.
The ostream operator should take the stopwatch by const&, not by value. (I doubt it makes much difference performance-wise, but it makes the intent and semantics clearer -
surely we shouldn't need to copy the stopwatch object to print the time?). Outsourcing the printing to a separate function also makes things a bit neater (more lines of code, but less duplication). It could be a lambda function if you wanted.

namespace detail
{

    template<class duration_t>
    void print_duration_if_non_zero(std::ostream& out, duration_t const& duration, std::string const& unitPostfix)
    {
        if (duration == duration_t::zero())
            return;

        out << duration.count() << unitPostfix;
    }

} // detail

std::ostream& operator<<(std::ostream& out, stop_watch const& sw) {

    auto t = sw.get_elapsed_time();

    auto h = std::chrono::duration_cast<std::chrono::hours>(t); t -= h;
    auto m = std::chrono::duration_cast<std::chrono::minutes>(t); t -= m;
    auto s = std::chrono::duration_cast<std::chrono::seconds>(t); t -= s;
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(t); t -= ms;
    auto us = std::chrono::duration_cast<std::chrono::microseconds>(t); t -= us;
    auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(t);

    detail::print_duration_if_non_zero(out, h, "h ");
    detail::print_duration_if_non_zero(out, m, "min ");
    detail::print_duration_if_non_zero(out, s, "s ");
    detail::print_duration_if_non_zero(out, ms, "ms ");
    detail::print_duration_if_non_zero(out, us, "us ");
    detail::print_duration_if_non_zero(out, ns, "ns ");

    return out;
}

It would be cleaner not to give stop_watch an ostream operator at all. If you create a print_time_to_stream(stream, time) that takes time as  std::chrono::nanoseconds (or whatever's the highest resolution you need in your app), then your print function can be used for any time, and not just for the stop_watch class!

Your Questions

get_elapsed_time() makes this unnecessary! User code should convert the duration when it needs to.
Since std::chrono::hours etc. are types, they can't just be added to a vector. I suppose you could do something like:

    auto times = std::vector<stop_watch::duration_t::rep>();
    times.push_back(std::chrono::duration_cast<stop_watch::duration_t>(std::chrono::hours(1)).count());
    // same for other desired types...

    auto units = std::vector<std::string>();
    units.push_back("h ");
    // ...

    print_times(std::cout, sw.get_elapsed_time(), times, units);

So the times vector contains the time to use in the units of stop_watch::duration_t. And then you can use integer division to get the necessary values instead of duration_casting.

Other Things

If you're just measuring function times, you might not need the start / stop logic. You could perhaps simplify the class to something like the following:

class timer
{
public:

    using clock_t = std::chrono::high_resolution_clock;
    using duration_t = clock_t::duration;

private:

    clock_t::time_point start_time;

public:

    timer():
        start_time(clock_t::now()) { }

    duration_t get_elapsed_time() const { return (clock_t::now() - start_time); }

    void reset() { start_time = clock_t::now(); }
};

There's no need to worry about leaving the timer "running", since there's no actual work unless you query the time...

timer sw;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "It took: " << sw.get_elapsed_time().count() << "units" << std::endl;


Merge sort algorithm implementation using C++

Looks good.

Couple of things I would do differently (not that your way is wrong).

Rather than pass references to the containers around I would pass iterators into the containers. This allows your sort algorithm to be container agnostic:

void merge_sort(std::vector<int>& numbers)
{}

// My version looks like this

template<typename I>                 // Notice the template
void merge_sort(I begin, I end)      // Just means I don't care what type
{}                                   // of iterator is used.

Same applies to merge().

Rather than creating sub arrays in merge_sort() I would do it inside merge(). With your current implementation you have a space complexity of \$O(N^2)\$. If you do it inside the merge you just need to allocate enough space to merge the current two ranges which is at most \$O(2N)\$ => \$O(N)\$.

Where you have:

std::vector<int>::size_type middle = numbers.size() / 2;
std::vector<int> left(numbers.begin(), numbers.begin() + middle);
std::vector<int> right(numbers.begin() + middle, numbers.end());

merge_sort(left);
merge_sort(right);

// My version looks like this:

std::size_t mid      = length/2;
I           midPoint = std::next(begin, mid);

// Merge in place.
mergeSort(begin, midPoint);
mergeSort(midPoint, end);

I could not work out how to merge without using a temporary (and I don;t have my copy of Knuth here). So my version of merge() merges the two sorted sub vectors into a temporary then copies back over the original.

Looking at your merge code it's slightly hard to follow (but I groked it). I personally prefer a simpler version.

// In this loop:
//    l:     current position in left  sub-array
//    r:     current position in right sub-array
//    i:     current position into merged array.
//    Note because we are merging in-place.
//    begin/midPoint/end are iterators to the input arrays that
//    split it into two parts.
while(l < midPoint && r < end)
{
    if (*l < *r)
    {    *i = *l;
         ++i;
         ++l;
    }
    else
    {    *i = *r;
         ++i;
         ++r;
    }
}
// One of the ranges is empty at this point.
// So only one of the loops will execute.
while(l < midPoint)
{   *i  = *l;
    ++i;
    ++l;
}
while(r < end)
{   *i  = *r;
    ++i;
    ++r;
}

A slight variation on this that I use; Where you use if () {} else {} I prefer to use the Condition Operator => Test ? <TrueWork> : <FalseWork>. I also have done this a few times and can safely compress ++ operations onto the same lines (Note I don't compress all of them; this is just personal preferences as I think it makes it easier to read this way). Which leaves me with:

while(l < midPoint && r < end)
{
    *i = std::move((*l < *r) ? *l++ : *r++);
    ++i;
}
while(l < midPoint)
{   *i  = std::move(*l++);
    ++i;
}
while(r < end)
{   *i  = std::move(*r++);
    ++i;
}

Notice: I use std::move() here. This is because my sort works on generic containers (not just integer containers). So I may be sorting an array of strings.

Final result is:

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

template<typename I>
void doMerge(I begin, I midPoint, I end)
{
    typename std::vector<typename std::iterator_traits<I>::value_type> TmpVec;

    TmpVec  tmp(std::make_move_iterator(begin), std::make_move_iterator(end));

    TmpVec::iterator   beginAlt   = std::begin(tmp);
    TmpVec::iterator   endAlt     = std::end(tmp);
    TmpVec::iterator   midAlt     = std::next(beginAlt, std::distance(begin, midPoint));

    TmpVec::iterator   l   = beginAlt
    TmpVec::iterator   r   = midAlt;
    I                  i   = begin;

    while(l < midAlt && r < endAlt)
    {
        *i = std::move((*l < *r) ? *l++ : *r++);
        ++i;
    }
    while(l < midAlt)
    {   *i  = std::move(*l++);
        ++i;
    }
    while(r < endAlt)
    {   *i  = std::move(*r++);
        ++i;
    }
}
template<typename I>
void mergeSort(I begin, I end)
{
    std::size_t length  = std::distance(begin, end);
    if (length <= 1)
    {   return;
    }

    std::size_t mid      = length/2;
    I           midPoint = std::next(begin, mid);

    mergeSort(begin, midPoint);
    mergeSort(midPoint, end);

    doMerge(begin, midPoint, end);
}

int main()
{
    std::vector<int>    data  {{ 5,12,45,2,67,8}};
    mergeSort(std::begin(data), std::end(data));

    std::copy(std::begin(data), std::end(data), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << "\n";
}


Using static final Strings for SQL Query in Spring Boot

Sorry to present the antithesis to an existing answer once more: if the string is neither reusable nor public, a constant makes no sense in my book. (And yes, this question is opinion-based ;-))

I see why you use a string-variable inside the medthod (to keep it readable for longer strings) which I find totally OK.

In general: aim to write the code for the audience of developers who come after you. In my experience, this future developer will dig through your code with a debugger because something goes wrong. Thus, he will not read the class in its entirity because he's curious, he will jump into that specific method from a stacktrace. All information that is locally there will be beneficial, as there is less jumping around in the code.


Do all URLs on your site use SSL? If not you'll need to setup your site to at least support the authenticate URL over HTTPS.
Currently your passing a plain text Username and Password - anyone can grab them.

On requests after the login, how are you determining whether or not the user is authenticated?
It does not look like you are persisting the login in any way, unless Auth class is doing it behind the scenes.  Typically this is done with a session variable or cookie.


Converting from `std::array>` to `void*`

It's hard to provide overall feedback, since you don't want to provide any details. There's probably a much simpler way to structure all of this.
But some things about the specific code:

don't do manual memory management:
char* bytes = new char[size];

I hope this gets delete[]d somewhere. We should use a std::vector instead, and get a pointer from vector.data() when we actually need to.

use std::byte in C++17:
char* bytes = new char[size];

If we have it, we should use std::byte instead of char (since we're dealing with object representations in memory).

use memcpy, not reinterpret_cast; simplify:
    if(float* flt = std::get_if<float>(&array[i])) {
        *reinterpret_cast<float*>(bytes+byteCounter) = *flt;
        byteCounter += sizeof(float);
    }
    else if(uint32_t* uin = std::get_if<uint32_t>(&array[i])) {
        *reinterpret_cast<uint32_t*>(bytes+byteCounter) = *uin;
        byteCounter += sizeof(uint32_t);
    }

Due to "strict aliasing rules" I don't think this is technically correct (even if it apparently works). Our char array doesn't have floats in it, so we shouldn't pretend that it does and copy in a float. We should instead use std::memcpy to copy the underlying representation of the float into the array.
Note also that we're doing the exact same thing for both types, so we could probably do something like:
std::apply([&] (auto const& var) {
    using T = std::decay_t<decltype(var)>;
    std::memcpy(bytes + byteCounter, static_cast<void const*>(&var), sizeof(T));
    byteCounter += sizeof(T);
}, array[i]);

same again (again):
The same thing is true of the second code snippet:
std::optional<uint32_t> pushConstantSize = std::nullopt; // later used for `size`
auto size_fn = [](auto variant) -> uint32_t {
    using T = std::decay_t<decltype(variant)>;
    if constexpr (std::is_same_v<uint32_t, T>) { return sizeof(uint32_t); }
    if constexpr (std::is_same_v<float, T>) { return sizeof(float);}
};
pushConstantSize = std::accumulate(pushConstants.begin(),pushConstants.end(),0,
    [size_fn](uint32_t acc, auto variant) { return std::move(acc) + std::visit(size_fn,variant); }
);

We don't need the if statements:
auto size_fn = [] (auto const& var) {
    using T = std::decay_t<decltype(var)>;
    return sizeof(T);
};
std::size_t size = std::accumulate(pushConstants.begin(), pushConstants.end(), std::size_t{ 0 },
    [=](std::size_t acc, auto var) { return acc + std::visit(size_fn, var); }
);

std::move won't help with a trivially copyable type, and we should be using std::size_t for the size.
The optional also seems redundant; we always have a size, even if the array is empty.
This snippet should be made a whole complete function by itself.


Implementation:

As of now, the code is not practical, because the limit is 500 chars including zero termination. It does unnecessary copying. You need to determine the actual length of the string by relying on the fact that C strings are null terminated.

size_t length = 0;
while (*(str + length) != 0)
{
    ++length;
}

Notice that I'm using size_t, because it is meant to be used to describe size of the objects in memory. Despite it is easy to do it manually, you should always use strlen when possible:

size_t length = strlen(str);

It should be noted that the function returns the length without null terminator. Then we allocate memory for result, since we are creating new string, rather than making changes in place:

char* result = malloc(length + 1);
if (result == NULL)
{
    return NULL;
}

We check for succession of allocation, as was suggested in the comments. If allocation failed, further operations will definitely invoke undefined behavior, so we return NULL. length + 1 is for null terminator. Then, we immediately null terminate it:

result[length] = 0;

Now we need to capture the position of the last character in the original string, to start copying from there. It is right before null terminator, which is on index length, so needed position is length - 1. There is an edge case of length 0, so we should check for that first

if (length == 0)
{
    return result;
}
size_t last = length - 1;

Then we write algorithm that writes contents of the first string into the second in reverse order:

size_t it = 0;
while (it <= last)
{
    result[it] = str[last - it];
    ++it;
}

then simply return the result:

return result;

Although the implementation has good performance, there are some opportunities to make micro optimizations. The function input type should be const char*, since we don't modify original string. Additionally, it should be noted that the caller is responsible for freeing up malloc'd memory.

Cosmetics:

Name of the function is a little hard to read, so I'd suggest str_reverse. Also, c is not good name at all, so it would be better if it's name str

Put together:

#include <stdio.h>
#include <string.h>

char* str_reverse(const char* str)
{
    size_t length = strlen(str);

    char* result = malloc(length + 1);
    if (result == NULL)
    {
        return NULL;
    }

    result[length] = 0;

    if (length == 0)
    {
        return result;
    }

    size_t last = length - 1;
    size_t it = 0;
    while (it <= last)
    {
        result[it] = str[last - it];
        ++it;
    }

    return result;
}

int main(void) {
    const char* str = "ABCD";
    char* reversed = str_reverse(str);

    printf("%s\n", reversed);
    if (str[4] != 0)
    {
        printf("problems\n");
    }

    free(reversed);
    return 0;
}


Accessing a subset of keys from a nested dictionary in Python

I previously have written a helper for this, as I've come across it too. If you pass the object and the keys to the object then you can do the same.

def get_nested(obj, keys)
    try:
        for key in keys:
            obj = obj[key]
    except KeyError:
        return None
    return obj

This makes usage:

subset['price'] = get_nested(row, 'quotes USD price'.split())

This allows you to extend the keys argument to a minilanguage for other common methods you'd want to apply to returned objects. One case I had was since JavaScript doesn't like maps much (not objects) some APIs tend to  convert dictionaries to arrays, and so I had to search a list of objects for which object I wanted, as I couldn't index the list as I'd get incorrect data at times.


No, don't do that. You seem to be filtering and escaping values out of paranoia rather than understanding what exactly would lead to a vulnerability. As a result, you are corrupting your data.

A well designed application should use the database to store the value that the user typed into the textarea, not some mangled representation of it. If you mangle the data like that before storing it, then:

Certain characters that the user typed get dropped. (What if the user input is x + 3 < 5? The data would no longer make sense after you drop the < character.)
Your database is not reliably searchable. (What if the user input is She said "yes!"? Then you would store a value in the database with &quot; in it.)
If you arbitrarily apply escaping to string just in case, then you'll have a hard time keeping track of how to unescape it correctly when regurgitating the data. (This often leads to bugs where the user sees garbage like his &amp; hers, or even worse, his &amp;amp; hers.)

What's the right way? Don't mangle the data; just store it faithfully:

// store the content
$addPostStmt = $conn -> prepare("
  INSERT INTO posts(description) VALUES (?)
");

$addPostStmt -> bind_param("s", $_POST['userinput']);
$addPostStmtExecute = $addPostStmt -> execute();

When outputting the data as HTML, apply HTML escaping:

Description:	<?php echo htmlspecialchars($description); ?>


Is there a better way to make a function silent on need?

It depends on what you are looking to do.  For localized 'quiet' code, I use this:

class NoStdStreams(object):
    def __init__(self,stdout = None, stderr = None):
        self.devnull = open(os.devnull,'w')
        self._stdout = stdout or self.devnull or sys.stdout
        self._stderr = stderr or self.devnull or sys.stderr

    def __enter__(self):
        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        self.old_stdout.flush(); self.old_stderr.flush()
        sys.stdout, sys.stderr = self._stdout, self._stderr

    def __exit__(self, exc_type, exc_value, traceback):
        self._stdout.flush(); self._stderr.flush()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr
        self.devnull.close()

then it is as easy as:

with NoStdStreams():
   print('you will never see this')

You could easily adapt it to:

with NoStdStreams(verbose):
    print('you may see this')


Transforming a list of maps representing bands

You might consider using map on Option to more cleanly access the values.

  def set_canada_as_country(band: Map[String, Any]): Map[String, Any] = {
    band.get("name").map( name => band.get("active").map(active =>
      Map("name" -> name, "country" -> "Canada", "active" -> active))
  }

At this point, you could reasonable change the resulting type to Map[String, String].

Rather than using a list of functions, you might want to compose a new function using andThen:

Exercise.pipeline_each(Exercise.bands, Exercise.set_canada_as_country andThen
  Exercise.strip_punctuation_from_name andThen
  Exercise.capitalize_names)

That way you are only applying a single filtering function.


Incrementing and decrementing 3 seperate input values by 1 using Javascript

Some things could be said about the HTML (no need for hr, border will do; those imgs should be background images on buttons; this is obviously a list; those smalls should be labels; way to many divs; ...) but let me focus on te JS as you are asking.

First thing that jumps out is the repetition. Each function basically does the same thing, but for a different room and with a different amount. Not very DRY at all.

The easy solution would be to pass the room name and the change amount in the function as parameters, and now you only need one function. Something like this:

function changeValue(roomName, amount) { ...

You can them call your function from the onclick attribute like so:

You can now add more rooms without having to change the javascript, and if you decide to change something in your logic you only have to change it once.

Second thing that was already noticed in the comments, you are changing the innerHtml of your inputs, but there is no such thing on inputs (there is no opening and closing tag with 'innerhtml' between them). Changing the value will suffice.

Also, you mention and tag jQuery, but this is vanilla JS, not a line off jQuery in there (which is fine btw!)

Let me close by showing you how my code would look if I had to write it:

HTML:

    bathrooms
    <button data-amount="-1">-</button>
    <input type="number" id="bathroom_count" value="0" autocomplete="off"/>
    <button data-amount="1">+</button>

    bedrooms
    <button data-amount="-1">-</button>
    <input type="number" id="bedroom_count" value="0" autocomplete="off"/>
    <button data-amount="1">+</button>

    kitchens
    <button data-amount="-1">-</button>
    <input type="number" id="kitchen_count" value="0" autocomplete="off"/>
    <button data-amount="1">+</button>

jQuery:

  $('#rooms li').on('click', 'button', function(e) {
    e.preventDefault();
    var $button = $(e.currentTarget);
    var $input = $button.siblings('input');

    $input.val(parseInt($input.val(), 10) + parseInt($button.data('amount'), 10));
  });

I think the code should speak for itself, but feel free to ask if you want me to elaborate.

I hope you learned something from it and happy coding!


Reduce number of parameters of the same type

That is a real code smell and should be refactored.
How should any mortal soul unterstand, what this code does?

Why not using a simple object?

public class{

    public bool Whateveryouwant { get; set; }
    public bool Whateveryouwantelse { get; set; }
}

The advantage:

1) your parameter shrunk to just one

2) if you name the properties (better than above) anybody else knows, what options were chosen.


Theory-based quiz grader using similarity

There is no need to include stop words in the dictionary if they are filtered out of the vectors anyway. Thus, tokenization and stop words removal can be considered as a single step. Secondly, the vectors can be initialized with the correct values immediately by taking advantage of collections.Counter
from collections import Counter
from typing import List
from nltk.corpus import stopwords
from nltk.cluster.util import cosine_distance
from nltk.tokenize import word_tokenize

def tokenize_without_stop_words(sentence:str) -> List[str]:
    return [
        word
        for word in word_tokenize(sentence)
        if word not in stopwords.words('english')
    ]

def cosine_similarity(first_sentence: str, second_sentence: str) -> float:
    first_words = tokenize_without_stop_words(first_sentence)
    second_words = tokenize_without_stop_words(second_sentence)

    dictionary = list(set(first_words+second_words))

    def encode(words: List[str]) -> List[int]:
        word_counts = Counter(words)
        return [
            word_counts[word]
            for word in dictionary
        ]

    first_vector = encode(first_words)
    second_vector = encode(second_words)

    return 1 - cosine_distance(first_vector, second_vector)


I don't think trying to cut down boilerplate like that is too much of an issue.
Normally I would have no problem with using something->somethingelse for the name of a function that converts from something to something else.  I'm not sure in this case though.  For one thing, I'd assume k means key.  k1->k2 kind of suggests it's acting on the key, but it's not.  In this case I'd probably just follow the example of the stdlib and call it f.  Makes it obvious it is the function that does the updating.  (Semi-related: you might want to check out the sample chapter of elements of clojure - it goes into naming things in clojure in some depth)
If you're running clojure 1.7+, you've got the update function that does this.


Inserting customer care database analysis detail records

With ToArray() you create an in-memory copy of all queried data. If you have 10m records this is incredibly expensive (both for CPU and memory). Avoid that and fetch data from DB each time you use it without needless copies. See also this question post for further details.

First change it to:

var query = from p in behzad.Customer_Care_Database_Analysis_TEMPs select p;

Your query does nothing then you may simply drop it if you don't need to perform any filtering.
Instead of for use foreach and do not (re)count collection each time. Even if LINQ should be smart enough (it was an array and it may cast and directly access .Length property) it's useless (see also Eric Lippert's answer about purpose) and with a pure enumeration it'll hit database with SELECT COUNT(*) ... multiple times.

foreach (var temp in behzad.Customer_Care_Database_Analysis_TEMPs)
{
    var detail = new Customer_Care_Database_Analysis_DETAIL();
    detail.code_faaliyat = temp.code_faaliyat.Trim();
    detail.code_markaz = temp.code_markaz.Trim();

    // And so on...

    behzad.Customer_Care_Database_Analysis_DETAILs.InsertOnSubmit(detail);
    behzad.SubmitChanges();
}

Now you should move SubmitChanges() outside your loop, this is 2nd big step to improve performance. Start searching from this question but there are many (better) posts out there about this topic. See also this question.

foreach (var temp in behzad.Customer_Care_Database_Analysis_TEMPs)
{
    var detail = new Customer_Care_Database_Analysis_DETAIL();
    detail.code_faaliyat = temp.code_faaliyat.Trim();
    detail.code_markaz = temp.code_markaz.Trim();

    // And so on...

    behzad.Customer_Care_Database_Analysis_DETAILs.InsertOnSubmit(detail);
}

behzad.SubmitChanges();

Performance impact of removing multiple array item deferencing and of introducing enumeration is absolutely negligible in this case.
Note that you may also partition your inputs. This is something you should profile for your specific case but you may get better performance working on batches of input data.

You may find many good implementations of Partition() function (also on Stack Overflow, for example or one of linked duplicates) then here I just provide pseudo-code for that:

const int batchSize = 100;
var batches = Partition(behzad.Customer_Care_Database_Analysis_TEMPs, batchSize);

foreach (var batch in batches)
{
    foreach (var temp in partition)
    {
        var detail = new Customer_Care_Database_Analysis_DETAIL();
        detail.code_faaliyat = temp.code_faaliyat.Trim();
        detail.code_markaz = temp.code_markaz.Trim();

        // And so on...

        behzad.Customer_Care_Database_Analysis_DETAILs.InsertOnSubmit(detail);
    }

    behzad.SubmitChanges();
}


Encapsulating snprintf to avoid repetition of sizeof

Pedantically, if (snprintf(buff, sizeof(buff), format, ...) >= SSIZEOF(buff)) goto err; is an insufficient test.  Test for < 0 is also needed.

  The snprintf function returns the number of characters that would have been written
  had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred....
  C111 §7.21.6.5 3

Note that ssize_t itself is not in standard C.

To cope with both issues, perform 2 sided test and drop using ssize_t.

int i = snprintf(buff, sizeof(buff), format, ...);
if (i < 0 || (unsigned) i >= sizeof(buff)) goto err;

... or if INT_MAX <= UINT_MAX/2 (a very common implementation), code can cheat with a one sided test as i<0 coverts to a large unsigned.  Again no need for ssize_t.

int i = snprintf(buff, sizeof(buff), format, ...);
if ((unsigned) i >= sizeof(buff)) goto err;


You're using functions, that's good. But, your program would be easier to understand, and better, if it didn't.

As a rule of thumb; don't put things in global scope.
Whether it be via global or by not putting your code in a function.
This is the global scope becomes un-reliable and you proceed to not know what your code is doing.

I would say that you should move check_answer into your while loop.
This is as rather than using generate_question you should use break.
This at the moment would end the program, but if you add another while True loop you can get the same functionality.
This is better as then you are starting to separate generating a question and checking if it's correct.
As we now only rely on the outer while to correctly setup the inner while, rather than changing globals to get things to work.

And so I'd use:

from random import randrange

def generate_number():
    return randrange(1, 13)

def main():
    while True:
        num1, num2 = generate_number(), generate_number()
        answer = num1 * num2
        print "What is %d times %d?" % (num1, num2)
        while True:
            user_input = int(raw_input("Answer: "))
            if user_input == answer:
                print "Very good!"
                break
            else:
                print "Try again!"

You should notice that this is your code. With a second while loop and a break.
But you should notice it's easier to understand what it's doing, when coming as a third party.

As at first, I didn't notice your code asks more than one question.

Just so you know you're already using a tuple! In print "What is %d times %d?" % (num1, num2).
The (num1, num2) is creating a tuple.
If you decided to use this rather than num1 and num2 then you would change num1 to num[0] and num2 to num[1].
This is as in most programming languages they start lists with zero rather than one.
Lists actually work the same way as tuples, but are created using [] rather than ().
The only difference is you can change num[0] when using a list, but you can't with a tuple.

You should also learn what try-except are. If I enter abc rather than 123 into your program it would exit abruptly.
What these do is try to run the code, if an error occurs run the except code.
But I'll warn you now, never use a 'bare except'. Which is an except that doesn't say what it's protecting against.
This is as if the code raises a different error than you'll run code as if it were another, which can hide bugs.
And makes finding those bugs really hard to find.

And so I'd further change the code to use:

from random import randrange

def generate_number():
    return randrange(1, 13)

def main():
    while True:
        num1, num2 = generate_number(), generate_number()
        answer = num1 * num2
        print "What is %d times %d?" % (num1, num2)
        while True:
            try:
                user_input = int(raw_input("Answer: "))
            except ValueError:
                print('That is not a valid number.')
                continue
            if user_input == answer:
                print "Very good!"
                break
            else:
                print "Try again!"


Get average of each nested array in dynamic object

First off, you should ensure that each key is a properly defined member of movieObj, not part of the prototype:

for (var key in movieObj) {
    if (movieObj.hasOwnProperty(key)) {
        // ...
    }
}

Instead of declaring getSum on Array, you can use the builtin reduce function:

var sum = function(previous, current) {
    return previous + current;
};

var ratings = movieObj[key].rating;

if (ratings.reduce(sum) / ratings.length < 5) {
    // ...
}

Finally, your console.log statement can use direct property access, instead of square bracket notation.  I believe moveName is a typo, and should in fact be movieName, but correct me if I'm wrong there:

console.log(movieObj[key].movieName);

Putting it all together gives:

var sum = function(previous, current) {
    return previous + current;
};

for (var key in movieObj) {
    if (movieObj.hasOwnProperty(key)) {
        var ratings = movieObj[key].rating;

        if (ratings.reduce(sum) / ratings.length < 5) {
            console.log(movieObj[key].movieName);
        }
    }
}


Populating Day/Month Selections in UserForm Controls

Why not doing it more directly like this:

Private Sub UserForm_Initialize()

  Dim i As Byte
  For i = 1 To 12
    UF_BankRec_cbx_Month.AddItem MonthName(i)
  Next

End Sub

Private Sub UF_BankRec_cbx_Month_Change()

  Dim i As Byte, startDate As Long
  UF_BankRec_cbx_EndDay.Clear

  startDate = DateValue("01/" & UF_BankRec_cbx_Month.Text & "/" & Year(Now()))

  While Month(startDate) = Month(startDate + i)
    i = i + 1
    UF_BankRec_cbx_EndDay.AddItem i
  Wend

End Sub

I'd say it is a bit better to read while i normally just speed codes up (so they end up in a way you can't read them anymore)... I tried my best to make it readable even without comments.
However, there may be a reason for you to run extra macros and using objects which i skipped out here... (to insert arrays to CBoxes is also possible solution to avoid objects)

If there any questions or something like that, feel free to ask Or better, tell me what you don't like looking at my code (this way i get the best idea what you desire) :)

At least your lastDayThisMonth = DateAdd("d", -1, firstDayNextMonth) is the same like lastDayThisMonth = firstDayNextMonth - 1 (but i am sure there is also a reason for that)


It really depends on what you're using the map for.
As already raised, you are overwriting the map for each line you read.

If you want to do something with the data later then I'd recommend creating a custom object with the fields for each column. Then you could store it in a list or a map with one of the values as a key (the value should be unique to prevent clashes) for future use.

If you're operating on it within the line read loop then you don't even need a data structure, just operate on the data right there and then.

Really until we know what you want to do with the data it is hard to say if you're using the correct data structure.

As a final note you state it is space delimited, I'd probably use String.split(" ") to create an array of your column data instead of using absolute references in your substring call, this would allow for cases where the data is larger than your substring range but still delimited by a space, unless you're absolutely sure the data is in a fixed format and is clean.


Compute leaderboard of competitive riders throughout a season

You should strive to reduce the number of queries to your DB. Instead of updating the whole table, row by row, each time you compute a new value, you could:

load the data (using pd.read_sql_table);
perform the computation of the positions (this may require you to use None or pd.np.NaN instead of 'NULL');
write the whole new table at once at the end (using df.to_sql).

The rewrite could look like:

def set_positions():
    """Add positions to the DB for each column in our overall table"""
    engine = sql.create_engine(MYSQL_CON_STRING)
    connection = engine.connect()
    trans = connection.begin()

    # Men, Women, Junior
    for category in CATEGORIES:
        table = category + '_overall'
        df = pd.read_sql_table(table, engine)
        compute_positions_for_table(df)
        df.to_sql(table, engine, if_exists='replace')
        trans.commit()
    connection.close()

def compute_positions_for_table(df):
    points_columns_list = [col for col in df.columns
                           if 'total' in col and 'position' not in col]

    # Calculate the rank based on current total points column and
    # insert into current column index + 1
    for points_column in points_columns_list:
        position_index = df.columns.get_loc(points_column) + 1
        position_column = df.columns[position_index]
        current_points = df.groupby('year')
        position = current_points[points_column].rank(ascending=0, method='min').astype(int)
        df.loc[:, position_column] = position.values

        # No points awarded in this and/or previous rounds. Everyone is
        # at 0 so everyone is rank 1
        df.loc[(df[points_column] == 0)
               & (df[position_column] == 1), position_column] = None

And even if you can't "replace" the table, you should still update the table only once at the end of the computation rather than at each new column computation.


Yes, that function terminate (unless the semantics of blobstore are stranger than expected and blobs is an infinite generator). One thing to be concerned about might be that, should your query take a very long time, you would not delete a single blob before a DeadlineExceededError is thrown, and so schedule another task without doing any work. This is a bad thing, as you may end up with many jobs that simply get half way through a query, give up and then schedule themselves to run again. The worst part is that your only indication would be that your log would be full of info level messages (i.e. messages that will be ignored), giving you no idea that this travesty was unfolding in your task queue.

I would recommend you add some kind of limit to make sure you are decreasing the number of blobs towards zero each time. You could think of it as an inductive proof almost; see Burstall's 69 paper on structural induction if you feel like formulating a mathematical proof. However, that is probably not necessary in this case. My suggested rewrite would be something like:

# The number of times one call to do_blobs_delete may `recurse`, should probably be
# made a function of the count of all blobs
MAX_ATTEMPTS = 10

def do_blobs_delete(msg=None, b=None, c=None, attempt=0):
    logging.info(msg)
    edge = datetime.now() - timedelta(days=750)
    statmnt = "WHERE size < 1" # size in bytes
    logging.debug(statmnt)
    try:
        gqlQuery = blobstore.BlobInfo.gql(statmnt)
        blobs = gqlQuery.fetch(999999)
        for blob in blobs:
            if blob.size < 1 or blob.creation < edge:
                blob.delete()
    except DeadlineExceededError:
        if MAX_ATTEMPTS <= attempt:
            logging.warning("Maximum blob delete attempt reached")
            return
        # Queue a new task to pick up where we left off.
        attempt++
        deferred.defer(do_blobs_delete, "Deleting empty blobs",
                       42, c=True,
                       attempts=attempt)
        return
    except Exception, e:
        logging.error('There was an exception:%s' % str(e))

Note that this does not explicitly address the lack of an inductive variable, though it does limit any damage done.

Another thing to note is that you have a race condition on the .delete. Should the method be called concurrently, say by process A and B, then the call to .fetch could return the same set of bobs to each. They would then attempt to delete the elements twice, which would raise an error on the .delete call, leading to fewer blob deletions than expected. This problem gets a lot worse when we consider more processes and things like unspecified ordering. The correct way to handle this is to treat any exceptions thrown by the .delete in a more nuanced way than you are currently, and accommodate multiple attempted deletes without prejudice.

Your current code will work fine at the moment, the problems will manifest themselves when things get more complicated. While I am sure Google's infrastructure can handle these upsets, your bottom line may be less flexible.


Divide two numbers, then apply a custom rounding rule

DivisionMethod is a pretty vague/poor name for your method; any method with the word "method" in it should raise a "bad name" flag!

Also, hard-coding the threshold into the function takes away flexibility. Perhaps I'd consider an optional parameter, like this:

public static double RoundedDivision(double a, double b, double threshold = 0.6)

Okay, not sure RoundedDivision is a much better name... naming is hard!. This is where XML comments can help:

/// <summary>
/// Divides <c>a</c> by <c>b</c> and round up if quotient is
/// greater than <c>threshold</c>, round down if it's less.
/// </summary>
public static double RoundedDivision(double a, double b, double threshold = 0.6)

It's probably best to call a cat, a cat: a is the dividend and b is the divisor, so the method would be clearer with a signature like this:

/// <summary>
/// Divides <c>dividend</c> by <c>divisor</c> and round up if quotient is
/// greater than <c>threshold</c>, round down if it's less.
/// </summary>
public static double RoundedDivision(double dividend, double divisor, double threshold = 0.6)

As was mentioned in the comments, there's an ambiguity issue with the threshold: what happens if the quotient is exactly equal to the threshold?


Recursively replace string placeholders with parameterized phrases

What if you would use re.sub() with a replacement function until there are no unfulfilled placeholders left. Something along these lines:

PHRASE_PATTERN = re.compile(r"(bb:\w+)(?:\[(.*)\])?")

def expand_message(message):
    """Recursively replaces any occurrences of building blocks with its text."""
    while "bb:" in message:
        message = PHRASE_PATTERN.sub(lambda group: phrases[group[1]].format(*group[2].split(","))
                                                   if group[2] else phrases[group[1]],
                                     message)
    return message

This way you don't need to iterate over all the available phrases and only handling the phrases used in a message. Should scale much better.


Get the width and height of a shape as user input

I think you have chosen really bad way to model the inheritance relation between a rectangle and a shape.

I believe that every shape has an area. Unlike your Shape class, which does not allow this, only the Rectangle class does.

On other hand, I believe that not all shapes have width and height. If anything, they have a smallest outer rectangle which has a width and height. Unlike, your Shape class which always has width and height and allows to set it to any arbitrary value.

You should turn it inside out.

You can still have the shape be able to give you the smallest outer rectangle (with its width and height), but implementing that method for anything except the Rectangle (where it would just return copy of itself) would be a bit more complex and providing such code for you would go far beyond a code review :) But that way you can provide the width/height pair in a read only manner, making sure that it cannot be modified for shapes where it would lead to corruption (like setting width!=height for a circle).

I would also rather use double for the numeric values as you would soon find out that areas of shapes are not always integers even for shapes which themselves are defined with integers (although this is not the case for rectangles).

class Rectangle;

class Shape
{
public:
  virtual ~Shape() {}
  virtual double getArea() const = 0;
  virtual Rectangle getSmallestOuterRectangle() const = 0;
};

class Rectangle : public Shape
{
public:
  double width, height;

  Rectangle(double width, double height) : width(width), height(height) {}
  virtual ~Rectangle() {}
  virtual double getArea() const {return width * height;}
  virtual Rectangle getSmallestOuterRectangle() const {return *this;}
};

Further obviously, you cannot create all shapes from just height and width.
If I wanted to create a circle, two variables are too much.
If I wanted to create an arbitrary triangle, two variables are not enough.

In any way, having the Shape/Rectangle/Circle/Triangle classes know anything about streams is a mistake. You can always read the values into variables and pass them through constructor or update the respective property (if you made them public, which is ok here I believe, no setters/getters are needed).


C# Code to Find all Divisors of an Integer

Style

As far as style goes, your code looks clean and readable, and follows the conventions, so good job for that.

You may want to include documentation comments with \\\ four your class and methods. Although the method names are descriptive enough in this rather simple case, it is a good habit to take on.

Tests

It's nice you use a test framework to test your class. However, the methods name don't match (Divisors vs GetDivisors) and comparing arrays doesn't work that way.

You could also benefit from including more tests for edge cases . What if the given argument is prime (since you make it a special case)? What if it is int.MaxValue? What if it is 0? What if it is negative?

Make your class static

Your Divisors class only has static methods. As such, it should be a static class. I might help the compiler with optimizations and can improve performance a little.

Unexpected behavior

As far as I know, 1 and n are always divisors of n, yet they are omitted from the returned array. You should probably include them, or at least document that they are omitted.

If the number is negative, you return null. While in theory negative numbers have divisors (and positive numbers have negative divisors), I understand why this you chose this approach, as well as why you only return positive divisors. I would suggest you either document this behavior, or enforce it by using the uint datatype. I would chose the former approach, as intis much more prevalent, and using uint would most likely imply a lot of casting down the line.

Optimizing the algorithm

You check if the number is prime before looking for divisors. First of all, your algorithm for primality checking is rather naive and can be optimized in various ways. More importantly, this is an optimization only if the argument is prime, but is counterproductive in the vast majority of cases when it isn't prime. I suggest to simply get rid of that check.

Furthermore, you check if every number between 2 and n is a divisor of n; however, you know that if i is a divisor, so is n / i. Therefore, you can loop only on values between 1 and sqrt(n) and add two divisors for every match.

My attempt

    public static class Divisors
    {
        /// <summary>
        /// Finds all the divisors of any positive integer passed as argument.
        /// Returns an array of int with all the divisors of the argument.
        /// Returns null if the argument is zero or negative.
        /// </summary>
        public static int[] GetDivisorsMe(int n)
        {
            if (n <= 0)
            {
                return null;
            }
            List<int> divisors = new List<int>();
            for (int i = 1; i <= Math.Sqrt(n); i++)
            {
                if (n % i == 0)
                {
                    divisors.Add(i);
                    if (i != n / i)
                    {
                        divisors.Add(n / i);
                    }
                }
            }
            divisors.Sort();
            return divisors.ToArray();
        }
    }

As for performance, finding all divisors for every integer between 0 and 10,000 takes around 130ms with your solution on my machine vs 12ms with mine, so a performance gain of around 10x.
Finding divisors for int.MaxValue takes around 9s your solution vs 5ms with mine, a performance gain greater than 1000x!
Finally, finding divisors for 2095133040 – the largest highly composite number that fits in the int datatype, with a total of 1600 divisors – takes around 5s with your solution, vs 13ms with my solution, again a performance gain of around 400x.

Performance can probably be improved further by estimating how many divisors has a given input and passing that estimate to the List<int> constructor, and thus limiting how much memory reallocating is done as the list grows. In fact, the upper bound of the number divisors is known: 1600. You could simply allocate the list as:

List<int> divisors = new List<int>(1600);

This brings the execution time down to 5ms for the highest composite number, but feels like a waste of memory in most cases.


Problems with backtracking algorithm in C++

Observation 1

If you find a 5000-length NOP-sequence, an L-length prefix of it would be a valid nop-sequence. Hence computing a full-length nop-sequence once in the beginning and just outputting prefixes (or suffixes) of it will make things quicker.

Observation 2

Generating substrings and checking them will make code slow. Writing your own substring equality check will speed this up. In addition, pass the string by const reference because it is not going to be modified.

bool checkequal(const string &str, int l1, int r1, int l2) {
  for (int i = l1, j = l2; i < r1; ++i, ++j) {
    if (str[i] != str[j])
      return false;
  }
  return true;
}

bool reject(const string &str) {
  int i = 1, len = str.size();
  while (i <= len / 2) {
    if (checkequal(str, len - i, len, len - 2 * i))
      return true;
    i++;
  }
  return false;
}

These two improvements should make your code fast enough to be accepted in contest.


I'd suggest that the position, and maybe orientation also, ought to be its own object ... "Location"?

I'd also prefer to use symbols rather than strings where possible, and rely on data rather than logic (see use of hashes below).

You might be interested in implementing a builder method, in which the methods called simply return the original object, which allows commands to be daisy-chained ...

class Location
  LEFT = {
    n: :w,
    e: :n,
    s: :e,
    w: :s
  }

  RIGHT = {
    n: :e,
    e: :s,
    s: :w,
    w: :n
  }

  def initialize(x:, y:, direction:)
    @x         = x
    @y         = y
    @direction = direction
  end

  def left
    @direction = LEFT.fetch(@direction)
    self
  end

  def right
    @direction = RIGHT.fetch(@direction)
    self
  end

  def move
    case direction
    when :n
      self.y += 1
    when :e
      self.x += 1
    when :s
      self.y -= 1
    when :w
      self.x -= 1
    end
    self
  end

  attr_reader :x, :y, :direction

  private

  attr_writer :x, :y, :direction
end

Hence:

2.4.5 :125 >   l = Location.new(x: 0, y: 0, direction: :n)
 => #<Location:0x00007f9f5329e858 @x=0, @y=0, @direction=:n>
2.4.5 :126 > l.left.move.right.move.left.move.right.right.move
 => #<Location:0x00007f9f5329e858 @x=-1, @y=1, @direction=:e>


In JS, when you have a switch, it's usually better to go with a dispatch table.

var mapping = {
    82: newDoc,
    79: openDoc,
    83: saveDoc,
    66: function() {
        showHideStatusBar(statusBarOn ? false : true);
    },
    191: function() {
        alert("Welcome to " + appname + "!");
    }
};
mapping[e.keyCode]();

Or if you don't want to give a name:

({
    82: newDoc,
    79: openDoc,
    83: saveDoc,
    66: function() {
        showHideStatusBar(statusBarOn ? false : true);
    },
    191: function() {
        alert("Welcome to " + appname + "!");
    }
})[e.keyCode]();

Also, use === instead of == for multiple reasons. Google "triple equal javascript" if you want more information.


Query with multiple foreign keys to the same table

I've updated the Fiddle with your initial query and 2 alternatives.

This is the initial query plan:

Using OUTER APPLY instead of the nested SELECT statements.

select created_at, prior_dd_rcvd_status_id,
    new_dd_rcvd_status_id, prior_dd_status, new_dd_status, filing_id
from ES_LOG
outer apply (
    select dd_doc_status_name as prior_dd_status
    from ES_DOCUMENT_STATUSES where dd_doc_status_id = prior_dd_rcvd_status_id
) a
outer apply (
    select dd_doc_status_name as new_dd_status
    from ES_DOCUMENT_STATUSES where dd_doc_status_id = new_dd_rcvd_status_id
) b
where filing_id = 988;

The query plan gets simplified:

And using LEFT OUTER JOIN instead of the OUTER APPLY.

select created_at, prior_dd_rcvd_status_id,
    new_dd_rcvd_status_id,
    a.dd_doc_status_name as prior_dd_status,
    b.dd_doc_status_name as new_dd_status,
    filing_id
from ES_LOG
left outer join ES_DOCUMENT_STATUSES a
    on a.dd_doc_status_id = prior_dd_rcvd_status_id
left outer join ES_DOCUMENT_STATUSES b
    on b.dd_doc_status_id = new_dd_rcvd_status_id
where filing_id = 988;

With an even more simplified query plan:

However, as you can see, the table scans take most of the time. So I'm not sure how much performance you could gain by picking either of the alternatives.

Further improvements require the use of indexes (Table Scan vs Index Scan). Deciding which index to provide depends not only on this query, but also the general design of how these tables will be used for other queries and CRUD operations. I would advise you learn about them.


Formatting/Indentation

Your code as posted here has a horrible formatting which makes it hard to read and understand. You add a level of indentation for each nesting level (each {} block).

Extracting functions

All your code is in the main function which increases dependencies and reduces readability. Consider extracting independent tasks into own functions like.

a function to get the next number in the collatz sequence from the current one
a function to measure the length from a number to 1 in the collatz sequence
a function to build the maximum of this length for a range of integers

Then your main function would only consist of the code for reading the input and printing the output (which might also be moved into own functions as well)

C vs C++

As you are using C++ you should take advantage of its features. For example in C++ you don't need to declare all variables up front. This allows you to declare them as late as possible (when they are needed).

C++ also does not require return 0; at the end of main. If execution reaches the end the return 0; will be automatically done by the compiler.

Use std algorithms

I don't think it is really necessary but your code stores the minimum and maximum of i and j in a and b (not necessary because the task seems to guarantee that i <= j). You are doing this calculation on your own which adds burden on the reader to understand what you are doing. There are std algorithms for this:

a = std::min(i, j);

Naming

All your variables have far too short and undescriptive naming. Ideally, a reader should know from the name of a variable what it is for. In your case this is not possible. I would suggest:

i -> first_input (or start_number if it is guaranteed to be less or equal the j)
j -> second_input (or stop_number)
a, b according to the suggestions above if you still use them
l -> current_sequence_start
tot -> current_sequence_length
gtot -> maximal_sequence_length
k -> current_sequence_number

Don't using namespace std;

This can become a problem later on so don't get used to it. Typing std:: is not that bad and if it becomes too bad you still can do using std::cout; to avoid the "lengthy" names.

Putting all this together I get the following code

#include <iostream>
#include <algorithm>
#include <cassert>

/**
 * @brief Get the next number in the collatz sequence from the current one
 */
int next_collatz(int current_collatz) {
  return current_collatz % 2 == 0 ? current_collatz / 2
                                  : 3 * current_collatz + 1;
}

/**
 * @brief Count the number of steps in the collatz sequence from current_number
 *        to 1
 */
int count_collatz_steps_until_1(int current_number) {
  int counter = 1;
  while (current_number != 1) {
    ++counter;
    current_number = next_collatz(current_number);
  }
  return counter;
}

/**
 * @brief Find the maximum of the lengths of the collatz sequence for each
 *        number bewteen start_number and end_number (inclusive)
 */
int maximal_collatz_sequence_length(int start_number, int end_number) {
  assert(start_number <= end_number);
  int maximum_sequence_length = 0;
  for (int current_number = start_number; current_number <= end_number;
       current_number++) {
    int current_sequence_length = count_collatz_steps_until_1(current_number);
    maximum_sequence_length =
        std::max(maximum_sequence_length, current_sequence_length);
  }
  return maximum_sequence_length;
}

int main() {
  int first_input, second_input;
  while (std::cin >> first_input >> second_input) {

    int start_number = std::min(first_input, second_input);
    int end_number = std::max(first_input, second_input);

    std::cout << first_input << " " << second_input << " "
              << maximal_collatz_sequence_length(start_number, end_number)
              << std::endl;
  }
}

This should be an improvement in clarity but not in speed as it is the same algorithm.


Concatenating prefix of one array with the reversed suffix of another array

The only note I can make is that in func1 and func2 you have an "API bug": the indices are "included" in the array. Consider this example:

[1, 2, 3, 4].slice(1, 3)

will produce [2, 3], so the point is that 3 in slice(1, 3) is not included. This does not happen only in Javascript, but also in other languages as well (I know Java does it that way). So the only advice would be to write your functions as

function func1(arr1,arr2,ind1,ind2)
{
    let arr = [];
    for (let n = 0; n < ind1; n++)
        arr.push(arr1[n]);
    for (let n = ind2 - 1; n >= 0; n--)
        arr.push(arr2[n]);
    return arr;
}

function func2(arr1,arr2,ind1,ind2)
{
    return arr1.slice(0, ind1).concat(arr2.slice(0, ind2).reverse());
}

Also, it is good to have a single space after each comma , in the function parameter list.


Abstract factory pattern for implementing AdNetworks on multiple platforms

It looks a lot like some service with platform dependent implementation. You might use a dependency injection pattern or service locator pattern.

I think factory is not quite great as a solution cause you will not create different implementations in a single application run. Also that is not great if you need this Controller to be created only once.

While it depends directly on your implementations and functionality of this service I will go with some interface. Further if implementations share same code then you might use an abstract base class to put that part of logic in it.


Counting numbers that are divisible by 3 and can be produced from the digits of a given number

The algorithm can be improved, so that we do less work:

Use the fact that multiples of 3 have a sum of digits that's also a multiple of 3.  That means we can select all the distinct combinations of digits, and discard any that don't sum to a multiple of 3.  Only for those sets not discarded, we can compute the number of permutation of the selected digits.  (Note that we don't have to actually produce all the numbers, merely count them - so if we have n different digits, we count n! permutations; if p of them are identical, then n!/p!, and so on).

For example, with input 5532:

5+5+3+2 is 15, this gives us 4!/2! permutations that are multiples of 3 (and remember 5532 as the largest such multiple).
5+5+3 is 13, so ignore it.
5+5+2 is 12, giving us 3!/2! more permutations to add to our count.
5+3+2 is 10; ignore it.
5+5 is 10; ignore it.
5+3 is 8; ignore it.
5+2 is 7; ignore it.
2+3 is 5; ignore it.
5 alone - ignore
3 alone - add one to the count.
2 alone - ignore.

And we're done; the total count is 4!/2! + 3!/2! + 1 = 16.


File selection button for Jupyter notebook

It is a nice piece of code. I have tried it in both jupyter notebook and jupyter lab. It works quite well in the notebook, but it does not work that well in lab.

In jupyter lab, it shows the button, but does not execute anything when you push it. I have adapted your code to be able to run it in lab.

Code:

import traitlets
from ipywidgets import widgets
from IPython.display import display
from tkinter import Tk, filedialog

class SelectFilesButton(widgets.Button):
    """A file widget that leverages tkinter.filedialog."""

    def __init__(self):
        super(SelectFilesButton, self).__init__()
        # Add the selected_files trait
        self.add_traits(files=traitlets.traitlets.List())
        # Create the button.
        self.description = "Select Files"
        self.icon = "square-o"
        self.style.button_color = "orange"
        # Set on click behavior.
        self.on_click(self.select_files)

    @staticmethod
    def select_files(b):
        """Generate instance of tkinter.filedialog.

        Parameters
        ----------
        b : obj:
            An instance of ipywidgets.widgets.Button
        """
        with out:
            try:
                # Create Tk root
                root = Tk()
                # Hide the main window
                root.withdraw()
                # Raise the root to the top of all windows.
                root.call('wm', 'attributes', '.', '-topmost', True)
                # List of selected fileswill be set to b.value
                b.files = filedialog.askopenfilename(multiple=True)

                b.description = "Files Selected"
                b.icon = "check-square-o"
                b.style.button_color = "lightgreen"
            except:
                pass
out = widgets.Output()
raw = SelectFilesButton()
widgets.VBox([raw, out])


Assembly 8086 program to input a 16-bit signed number (in string form) and output its binary equivalent

One of the most problematic things to deal with in assembly and even other higher languages but to a lesser degree, is spaghetti code. The logic of the program becomes lost in scrolling back and forth through hundreds of lines, SO concise documentation of what is going in is essential.

Working from the inside out is a method that has worked very effectively for me.

; Read ASCII NULL terminated string and convert input to packed BCD.

      GetNext:    lodsb                  ; Read next character into AL
                  or      al, al         ; Teminator ?
                  jz      Done

                 .......

                 jmp     GetNext

       Done:

Sometimes you may even want to think of efficiency in terms of time. The most probable scenario is that you'd be encountering digits 0 to 9.

      GetNext:    lodsb                  ; Read next character into AL
                  cmp     al, '0'
                  jae     @F
                  cmp     al, '9'
                  jbe     @F
                  cmp     al, 0
                  jz      Done

    ; At this point we know our entry is invalid or alternately we might
    ; want to check for things like '+', '-' or in this case just ignore
    ; extraneous input.

                 jmp     GetNext

            @@:  ; This is peculiar to MASM and is a local label.
                 ; NASM it could be preceded with a period like .L0:

                 .......

                 jmp     GetNext

       Done:


There is a better way, use a single sort function where you check on both values. If network status is different, sort on that, otherwise sort on battery power:

var devices = JSON.parse(document.getElementById('devices').innerHTML);

function sortDevicesByStatusAndPower(a, b) {
    var aStatus = a.network_status,
        bStatus = b.network_status;
    if( aStatus != b.network_status )
      return aStatus < bStatus ? -1 : 1;
    else
     return a.battery_level - b.battery_level;
}

console.clear();

console.log(devices.sort( sortDevicesByStatusAndPower ));

I built a jsbin for this: http://jsbin.com/gesoq/1/edit

Finally, storing the JSON iside a script tag is .. novel, not sure it is the best approach.


if type(lst)==tuple:
        t=lst
        lst=[]
        for elem in t:
            lst+=[elem]
    if type(lst)==str:
        lst=list(lst)

It's worth knowing that list works on tuples too. (Online demo).

    for elem in lst:
        if elem:

What purpose does this if serve? It seems to me to introduce a bug, because the spec does not ask for falsy elements of lst to be ignored.

            l_temp=[lst[0]]
            lst=lst[1:]

[lst[0]] would be more Pythonic as lst[:1]. Spot the symmetry with the second line.

The reuse of names is not particularly helpful, especially given that lst is a bad name. How about this?

            first, rest = lst[:1], lst[1:]

            lst.extend(l_temp)

Wait, that was just to rotate the list? Why? At this point I'm seriously in need of some comments to explain what you're trying to do.

            temp=list(lst[1:])
            r_list=[]
            lst_of_lst=[]
            r_list+=[lst[0]]

lst_of_lst? That sounds like a bad name for a 2D array, but the spec doesn't ask for a 2D array and I can't see why you'd need one.

r_list is again just lst[:1].

                holder=temp[1:]
                t_holder=[temp[0]]
                temp=[]
                temp.extend(holder)
                temp.extend(t_holder)

Or in other words temp = temp[1:] + temp[:1]. You're rotating lists often enough that maybe it's worth factoring out a function to make the flow of logic clearer.

                if len(r_list)==1:
                    r_list.extend([e for e in temp])
                    lst_of_lst+=[r_list,]
                    r_list=[]
                    r_list+=[lst[0]]
            yield lst_of_lst

There is no way this algorithm can be correct. Have you tested your code?

print len(list(permutations([1, 2, 3])))
print len(list(permutations([0, 1, 2, 3])))

should output

6
24

Once your code works, given that it's Python you should run it through an automated PEP8 checker. It should be easy to find one online.


Analyzing the U.S. Births dataset in Python

If you want to do data-analysis in Python, you should learn about numpy and pandas. The former implements efficient numeric calculations (on whole arrays). The latter uses numpy and introduces a DataFrame, which is a bit like a table that can be manipulated in many ways. You can sort it by some column(s), you can transform them and you can even group them by some column(s) and perform operations on the groups (which is what you want to do here).

Your current code boils down to very few lines with pandas:

import pandas as pd

df = pd.read_csv("us_birth_statistics.csv", skipinitialspace=True)
birth_per_month = df.groupby("month").births.sum()
birth_per_weekday = df.groupby("day_of_week").births.sum()

print(birth_per_month)
print()
print(birth_per_weekday)

#month
#1    48311
#Name: births, dtype: int64

#day_of_week
#1    10142
#2    11248
#3    11053
#6     8096
#7     7772
#Name: births, dtype: int64


Function to ensure that at least one choice is selected

if (key === 'insight' || key === 'spike' || key === 'momentum') {

Instead of looping through and checking these specific keys using an if, why not just create an array with the keys you're interested in and loop through that?

var filterKeys = ['insight', 'spike', 'momentum'];

Running on this, you can easily use map to gather the values, filter to reduce to only those that are true. Then checking if it's the last true filter will just be a matter of checking if what remains from a filter is an array with 1 as length.

Additionally, this function can be made so that it doesn't introduce side-effects or reduces the surface area of a side-effect. You can simply split off the logic to another function and return a boolean, while leaving the logic with side-effects (one that alters settings) in the caller.

function isLastFilter(settings) {
  var filters = ['insight', 'spike', 'momentum'];

  return filters.map(filter => settings[filter])
                .filter(value => value === true)
                .length === 1;
}

function updateFilters(type) {
  var shouldUpdate  = !isLastFilter(settings);
  settings[type]    = shouldUpdate ? settings[type] : !settings[type];
  settings.errorMsg = !shouldUpdate;
}

On other things, settings.errorMsg shouldn't be part of the data. It's a computation of other settings. In this case, it's derived from a state where there's only one filter present. The problem here is that updateFilters is essentially a "sync" function, syncing settings.errorMsg to the state of the other settings. Lose this, and you'll get an invalid state.

Drop settings.errorMsg. If you're using an ng-if or something to toggle the error in the UI, it should be something like ng-if="isLastFilter(settings)".


Creating default parameters for a TestResultDefinition

if (this.Parameters == null || this.Parameters.Count == 0)

Is a check this complex actually necessary? It's hard to say for sure without seeing the rest of the class, but it seems like "Parameters is never null" is an invariant that the class could guarantee. For example by initializing to an empty collection in the constructor, making sure nothing else in the class sets it to null, and not exposing a public (or protected) setter so that nothing else can set it to null.

Doing this isn't always possible, but when it is, it does a good deal for reducing the potential of bugs and decreasing cognitive load by reducing the number of possible states you have to worry about the system being in.

As for your potential alternative- yes, it probably is better! In fact if you had ReSharper, it would recommend you did exactly that. It calls it "inverting if statement to reduce nesting".

This probably isn't a completely uncontroversial opinion though, so I'll try to sum up the pros and cons of each:

Pro inversion

Deeper nesting is generally harder to read
When reading into a nested if statement, you have to keep a "mental stack" of the conditions that each set of curly braces corresponds to. It has to be a stack so that you can readily "pop" off the last conditional once a set of curly braces ends. By contrast, when an if statement returns, you simply know that that condition is never true for the rest of the method, rather than having to be ready to jump between the true and false case. Cognitively this is much easier.

Anti-inversion

There's a style point that has lost popularity recently but some people still adhere to that a method should only have one exit point. I guess the reasoning is that having a single exit point corresponds to a single "path" through the code- even if conditionals mean that path can fork. There's some more analysis of this here.
Your conditional is probably slightly more likely to be a negative one if you do this. So instead of saying "if X then do Y", you're saying "if not X then don't do Y", which is mentally a bit harder to understand. The "don't do Y" part is unavoidable, but the "if not X" bit can be avoided by extraction of your conditional into a well-named method. For example:

private bool HasParameters()
{
    return this.Parameters != null && this.Parameters.Count > 0;
}

Some misc points:

You may have noticed HasParameters has slightly different logic than the line in your second snippet. That's because your one has a bug! In your case, a non-null but empty value for Parameters would have a value of true for this conditional, but it should have false.
Assuming you're using standard naming conventions, you shouldn't have anything method-scoped whose name starts with a capital letter. So no need to keep writing this.Parameters. Just Parameters would be equally unambiguous.


Printing a number based on a user-provided number

The best way to shorten the code would be to write a formula for it.  That formula should be packaged into a function:

public static String outputForDay(int day) {
    if (!(1 <= day && day <= 31)) {
        throw new IllegalArgumentException("Invalid entry for the day.");
    }
    int onesDigit = day % 10,
        tensDigit = day / 10;
    return Integer.toString(10 * (tensDigit + 1) + (onesDigit % 4) + 1);
}

Then, you would call the function like this:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        System.out.print("Enter the day of the month: ");
        System.out.println(outputForDay(scanner.nextInt()));
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
    }
}


If you are using .NET 4 or above drop your code, and use MemoryCache.


Cleaning parameters before passing them to a model

Honsetly, I don't see any sense in your extension.
Can you tell me what is the difference between

@idea = Idea.create(Idea.filter_parameters(params))

and

@idea = Idea.create(params)

mass assignment sanitizing make this code safety.


General select statement to stored procedures

This is first refactored version of your code. I have changed following thing

If any object provide dispose method , prefer using statement.
Use dictionary rather than list of parameter as you have a possibility of specifying param names also
Current implementation sticks only to datatable , you might need to think about the datareader.
naming of variable should be explicit.

Few more things needs to be thought like out param if you need.

public static DataTable ExecuteDataTable(string queryName, CommandType commandType, Dictionary<string,object> parameters=null)
{
    using (OleDbConnection connection =  WorkerDB.GetConnection())
    {
        using (var command=new OleDbCommand())
        {
            connection.Open();
            command.CommandText = queryName;
            command.CommandType = commandType;
            command.Connection = connection;

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                }
            }

            var dataAdapter = new OleDbDataAdapter(command);
            var dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            dataAdapter.Dispose();

            return dataTable;
        }
    }
}