I know that you're supposed to create the slowest-growing function possible, but that doesn't mean you necessarily need to make your function the slowest possible (LoL!).

As far as I can determine, your code for the Ackermann is mathematically correct - according to both Wikipedia and my (admittedly poor) sense of mathematical intuition.

<BoringMaths>

However, the inverse Ackermann as defined by Wikipedia is supposed to be a two-parameter function, and as such you cannot imitate it using a one-parameter function.

Also, you want a do-while loop here, so that the loop runs at least once even if the constraining condition is false at the start, as well be for my suggestion below. I don't think the return should be i - 1 instead of i either, as you can potentially return 0 if it remains as-is, which is not a legal value.

What you could try, as the ending paragraph of the relevant section of the Wikipedia article mentions, is setting the parameter m to a constant - not n, and especially not making \$n=m\$ - although that works too.

Here, I'd suggest choosing \$m=0\$. Such a choice helps with golf-ability - you can get rid of the division and the Math.floor in one fell swoop - \$\lfloor\frac{m}{n}\rfloor\$ is always \$0\$, regardless of \$n\$ (assuming that NaN, when converted to integral type, is 0, as it is in Java). So the loop condition basically becomes \$Ack(i, 0) < log_2(n)\$. Note the less-than (\$\lt\$), not less-than-or-equal-to (\$\le\$): this is the proper negation of the condition greater-than-or-equal-to (\$\ge\$).

Mathematically, how about a constant function, which is in fact the slowest growing function as it doesn't grow at all? Why not just return a constant and be done with it?

I think the PPCG question's rules forbid submitting a constant function, so let's not dwell on that any more (but it does make for a cheap trick, doesn't it?)

</BoringMaths>

<NonCritical>

A few small improvements for your implementation in the readable version

Extract out Math.log2(n) into a variable.
I think ES6+ gets you let and const - use them instead of var. As far as I remember, the former gets you proper scoping and the latter allows you to declare a named constant. I think my point (1) should have a const declaration.

Type Coercion is not readable!

Don't use implicit Boolean coercion of numbers in code which you claim to be "readable" - it isn't. Use proper comparisons in readable code, and leave the cool weak-typing hackery for the golfed version. How much does writing out the actual condition improve the readability of the code?

Everything else seems to be fine - naming, indentation, and all.

</NonCritical>

Suggested Code:

function Ackermann(m, n) {
  if (m < 0 || n < 0) {
     throw new TypeError("Arguments to Ackermann must be non-negative");
  }
  if (m == 0) {
     return n + 1;
  }
  else if (n == 0) {
     return Ackermann(m - 1, 1);
  } else {
     return Ackermann(m - 1, Ackermann(m, n - 1));
  }
}

function inverseAckermann(n) {
  const log2_n = Math.log2(n);
  let i = 0;
  // Taking `m` to be the constant 0 in the definition of the inverse Ackermann function
  do {
      ++i; // Pre-increment implies less side-effects
  } while (Ackermann(i, 0) < log2_n);

  return i;
}


Dragable infinite loop carousel, performance issues on dragging large number (25+) of slides

From a once over, some performance tips:

At least on some versions of Chrome, parseInt(string,10); is slower than a number of alternatives, my preference is +string
It is faster to call Math.abs(string) than Math.abs(parseInt(string,10))
Each object property lookup has a cost, so consider var base = this.protected; since all your object accesses are on `base.protected'
Be wary of ternary operators, a regular if tends to be faster
Your code has actually a number of little inefficiencies

You will capture var MousePosition = GetEventCoordinates(ev); but then later you still call locals.NewSliderLeft = GetEventCoordinates(ev).x - locals.DragStartTouchOffsetX-locals.PopAdjustment;
You store locals.NewSliderLeft but you use it only once in the assignment here: base.protected.$Slider.css('left',locals.NewSliderLeft);, I would skip storing this value in locals altogether.

From a style perspective, I would suggest that you use more spaces and fewer parentheses so var MouseMoveDistance = (MousePosition.x-locals.StartingMousePosition.x); becomes
var MouseMoveDistance = MousePosition.x - locals.StartingMousePosition.x;
Also prefixing in general is discouraged (oEdgeCounts)
From a DRY perspective, the block of if(oEdgeCounts.left<1 && MoveDirection==='>'){ and if(oEdgeCounts.right<1 && MoveDirection==='<'){ is pretty much copy pasted, you should refactor that

All in all, your code is quite readable and maintainable and I dont see immediately where the culprit is. I fully endorse the opion of Doug Gale to use the Chrome developer tools to find the culprit.


Monte-Carlo method to estimate Pi runs slower in multiple threads, than in single thread

The cause of the long execution times in the multithreaded case were the use of static methods, fields, objects.
In the scala code code above, if I change the Circle class to object:

class Circle {
  class Point(val x: Double, val y: Double) {
    def isInside: Boolean = Math.sqrt(x * x + y * y) < 1.0
  }
  val random = new Random()
  private def randomPoint(): Point = {
    def generate() = random.nextDouble() * 2 - 1
    new Point(generate(), generate())
  }
  def tryToHit(): Boolean = randomPoint().isInside
}

And then create a Circle instance inside of the PiCalculator class:

class SimplePiCalculator(n: Int) extends PiCalculator with Callable[Int] {
  override def call(): Int = calculateHits()
  val circle = new Circle
  def calculateHits(): Int = {
    var hits = 0
    for (i <- 1 to n) {
      if (circle.tryToHit()) hits += 1
    }
    hits
  }
  def calculate(): Double = 4.0 * calculateHits / n
}

Then execution times are as follows:

Calculating PI using the Monte-Carlo method
Elapsed time: 481745137ns 481ms
3.142086
4.933464102068186E-4
Elapsed time: 219407150ns 219ms
3.1410116
5.810535897929903E-4

Also in the Java solution, I've found, that the Circle class was using a public static final Random RANDOM static variable to generate random points, and this was the cause of the slowdown.

So it looks like, when writing multithreaded code, one must avoid using common objects, and static methods/variables.


Every instance in an enum already has an ordinal (the 0-based position of the value in the declaration order of the enum). For example, your instance C.ordinal() will return 2. See: Enum.ordinal(). These are the same values as the ones you are assigning to test. Is that a coincidence?

Additionally, you're using a small range of 0-based values for the test field, and as a consequence, an array will be a better storage option than a Map. Even if the array is as much as 80% empty it would still be more efficient (space and performance) than the Map.

About the exception - yes, I would throw a NoSuchElementException if the user tries to get a value that does not exist. Enums are compile-time constants and any use of the enum that's not legal should be reported, and found as soon as possible. In a sense, it's for this reason that Enums exist - to give compile-time certainty that your code references meaningful constants. The very fact that you are mapping the enum values back to an int is itself a bit concerning.

There is no need to make the Map a read-only map. The map is completely contained/encapsulated in the enum and no other write accesses exist, and no user can write to it, so it's redundant to make it read-only.

If your values can span a (very) wide range I would keep your Map-based lookup, but change the code to be:

private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM = new HashMap<>();
static {
    for (TestEnum testEnum : TestEnum.values()) {
        tmpMap.put(testEnum.test, testEnum);
    }
}

public static TestEnum fromValue(final int value) {
    // Add validation?
    TestEnum v = VALUE_TO_TEST_ENUM.get(value);
    if (v == null) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }
    return v;
}

If your values are in a small range, at, or close to 0, I would do:

private static final TestEnum[] VALUE_TO_TEST_ENUM;
static {
    int max = 0;
    for (TestEnum testEnum : TestEnum.values()) {
        max = Math.max(max, testEnum.test);
    }
    VALUE_TO_TEST_ENUM = new int[max + 1];
    for (TestEnum testEnum : TestEnum.values()) {
        VALUE_TO_TEST_ENUM[testEnum.test] = testEnum;
    }
}

public static TestEnum fromValue(final int value) {
    // Add validation?
    if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }

    TestEnum v = VALUE_TO_TEST_ENUM[value];
    if (v == null) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }
    return v;
}

If your test values are from 0 to n-1 and are the same as the ordinals of the enums, then I would completely get rid of the test value, and have the code:

private static final TestEnum[] VALUE_TO_TEST_ENUM;
static {
    VALUE_TO_TEST_ENUM = TestEnum.values();
}

public static TestEnum fromValue(final int value) {
    // Add validation?
    if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }

    return VALUE_TO_TEST_ENUM[value];
}


It's generally best to divide your code into separate sections (possibly separate functions) for argument handling and actual computation.

Errors should be printed to standard error rather than standard output.  Also, prefer small integer values for exit status (and since we're in main(), we can use simple return rather than exit() - note the useful EXIT_FAILURE macro for the return value).

It's worth documenting case fallthroughs.  This one is especially suspect:

               case 1: sa.sin_family = AF_INET6;
             }
    case 1: sa.sin_family = AF_INET;
  }

After we store AF_INET6, it's immediately overwritten with AF_INET - is that really intended?

This fallthrough would be clearer as two independent cases:

    case 0:
        printf("\nInput address is not a valid IPv6 address.\n");
        /* fallthrough */
    case -1:
        if (n_res == -1)
            printf("\nError(%s)\n",strerror(errno));
        exit(-1);

Compare:

    case 0:
        fprintf(stderr, "\nInput address is not a valid IPv6 address.\n");
        return 1;
    case -1:
        fprintf(stderr, "\nError(%s)\n", strerror(errno));
        return 1;

This line seems to be no use to a user:

printf("\nsa.sin_addr.s_addr[%d]\n",sa.sin_addr.s_addr);

We check for argv less than 2, but we neither complain about nor use any excess arguments.

There's no need to null out the node storage, as getnameinfo() will either fail (in which case we'll never access it) or write a valid string.

Minor (grammar): don't use "for" with "e.g." - that reads like, "for for example".

When I tried running the program, I found it wouldn't work at all with IPv6 addresses, because sockaddr_in is too small for IPv6 addresses.  I had to totally rewrite with a union of address types:

#include <arpa/inet.h> //for inet_pton()
#include <netdb.h> // for NI_MAXHOST, getnameinfo() and gai_strerror()

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

static int convert4(struct sockaddr_in *sa, const char *name)
{
    return inet_pton(sa->sin_family = AF_INET, name, &sa->sin_addr);
}

static int convert6(struct sockaddr_in6 *sa, const char *name)
{
    return inet_pton(sa->sin6_family = AF_INET6, name, &sa->sin6_addr);
}

int main(int argc, char** argv)
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s [IP]\nE.g. %s 10.32.129.77\n", argv[0], argv[0]);
        return EXIT_FAILURE;
    }

    union {
        struct sockaddr         sa;
        struct sockaddr_in      s4;
        struct sockaddr_in6     s6;
        struct sockaddr_storage ss;
    } addr;

    if (convert4(&addr.s4, argv[1]) != 1 && convert6(&addr.s6, argv[1]) != 1) {
        fprintf(stderr, "%s: not a valid IP address.\n", argv[1]);
        return EXIT_FAILURE;
    }

    char node[NI_MAXHOST];
    int res = getnameinfo(&addr.sa, sizeof addr, node, sizeof node, NULL, 0, NI_NAMEREQD);
    if (res) {
        fprintf(stderr, "%s: %s\n", argv[1], gai_strerror(res));
        return EXIT_FAILURE;
    }

    puts(node);
}


Light Python pubsub lib, but is it too light?

1. Code review

It's hard to evaluate this kind of thing in the abstract without knowing what the requirements are. However, here are a few thoughts.

There's no top-level documentation. How am I supposed to use this code? You could provide a module-level docstring.
The Python style guide (PEP8) recommends that global variables should be "lowercase, with words separated by underscores". So topics would be preferred to Topics (which looks like the name of a class). You're not obliged to follow PEP8, but it makes it easier for you to collaborate with other Python programmers.
The use of a global variable to store persistent data makes code hard to debug and test. When you have persistent data (like your Topics dictionary) together with a group of functions that operate on the data, it's usually best to organize this into a class.
You have a global variable Topics but the things it contains are called "messages". It would be clearer if you stuck to one word to describe these things.
Your implementation has the constraint that the only thing that can subscribe to a topic is an object with a method that has the same name as the topic. This is likely to be an annoying constraint. For suppose that I have a function f and I want to subscribe it to the topic named "t". Here's one way to do it:

obj = type('_dummy', (object,), {})()
obj.t = f
subscribe(obj, 't')

but this seems like the kind of boilerplate that a well-designed publish/subscribe library would not need.
The implementation of publish_with_results seems dodgy to me. A topic is a set of subscribers (that is, the subscribers have no particular order), but publish_with_results returns a list of results (that is, in a particular order). So there is no way to match up the results with the subscribers.

It's hard to say whether this is really a problem without knowing more about what you would use this for.
Your implementation requires all topics to share the same namespace: they are all string keys in the Topics dictionary. But this means that if different modules want to use your publish/subscribe library, they need to coordinate their choices of names, to avoid clashes.

It would be better to use Python's own namespace mechanism to handle name clashes, by making each topic into its own object, perhaps like this:

class Topic(set):
    """A publish/subscribe topic, implemented as a set of functions.

    Subscribe by adding a function to the topic using the set
    methods. Send a message to the subscribers by calling the publish
    method.

    >>> t = Topic()
    >>> t.add(print)
    >>> t.publish('hello, world!')
    hello, world!

    """

    def publish(self, *args, **kwargs):
        """Publish message by calling all subscribers."""
        for s in self:
            s(*args, **kwargs)

The example code in the docstring can be run using the doctest module.

2. Response to comments

"You say it's harder to debug or test without a class - why?"

When you're testing code you want to start each test case from a known state (not from whatever happens to be left over from the previous test cases). If you're testing code that's encapsulated in a class, then that's easy: you can just create a new instance of the class for each test case and throw it away when you're done. But if you're testing code that uses global variables, you have to explicitly reset all the global variables before starting the next test case.
"Wouldn't each message ideally be unique anyway?"

What I have in mind here is that a program may be made up of several modules or libraries that use the publish/subscribe library. For example, there may be a user interface toolkit that publishes a message when a user presses a button, and there may be a networking module that publishes a message when a networking event takes place.

This would go wrong if these two modules happen to choose the same name for two different events. For example, the user interface toolkit publishes the "login" message when the user presses the "Login" button, and the networking module publishes the "login" message when the user successfully signs in to a remote service. These message names clash and so their subscribers incorrectly see the messages for the other event.

So in this situation there needs to be some coordination in the choice of message names. But these two modules might be written by different programmers who have no idea that they would be combined in the same program.

It would be better not to put all the messages in the same namespace.


Find the contiguous subarray within an array (containing at least one number) which has the largest sum

1

The usual C coding conventions dictate that a space is added before and after a binary operator. For example, you should write

a += b;
if (foo < bar) ...
int currIndex = 0;

instead of

a+=b;
if(foo<bar) ...
int currIndex=0;

Also, you should add a single space before the opening parenthesis associated with keywords for, while, and if. For example, you should write

for (i = 0; i < x; ++i) ...

instead of

for(i = 0; i < x; ++i) ...

2

You add a space (sometimes) before the closing semicolon (;). Don't do it.

3

Your code would be more nifty if you added an empty line after each closing brace (}). For example,

if (sum > maxSumTillNow)
{
    ...
}

if (firstNeg == -1 && A[currIndex + currLength] < 0)
{
    ...
}

4

Your algorithm seems to run in quadratic time. The Kadane's algorithm does this in linear time.

Summa summarum

All in all, I had this in mind:

#include <stdio.h>
#define MAX(a, b) (a) > (b) ? (a) : (b)

int maxSubArray(const int* A, int n1)
{
    int currIndex     = 0;
    int maxSumTillNow = A[0];
    int maxSumStart   = 0;
    int maxSumLength  = 1;
    int currLength;
    int sum;
    int firstNeg;

    while (currIndex <= n1 - 1)
    {
        if(A[currIndex] < 0)
        {
            if(A[currIndex] > maxSumTillNow)
            {
                maxSumTillNow = A[currIndex];
            }

            currIndex++;
            continue;
        }

        sum = 0;
        firstNeg = -1;

        for (currLength = 0; currLength + currIndex <= n1 - 1; currLength++)
        {
            sum += A[currIndex+currLength];

            if (sum > maxSumTillNow)
            {
                maxSumTillNow = sum;
                maxSumStart   = currIndex;
                maxSumLength  = currLength + 1;
            }

            if (firstNeg == -1 && A[currIndex + currLength] < 0)
            {
                firstNeg = currIndex+currLength;
            }
        }

        if(firstNeg == -1)
        {
            break ;
        }

        currIndex = firstNeg + 1;
    }

    return maxSumTillNow;
}

int kadanesAlgorithm(const int* array, const size_t length)
{
    int maximum_so_far = array[0];
    int maximum_end    = array[0];

    for (size_t index = 1; index < length; ++index)
    {
        const int x    = array[index];
        maximum_end    = MAX(maximum_end + x, x);
        maximum_so_far = MAX(maximum_end, maximum_so_far);
    }

    return maximum_so_far;
}

int main(int argc, const char * argv[]) {
    int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
    printf("Original result: %d\n", maxSubArray(arr, 9));
    printf("Kadane's result: %d\n", kadanesAlgorithm(arr, 9));
}

Hope that helps.


Generate N pairs of checkboxes and N textboxes

I would use the razor boolean attributes:

  <input type="checkbox" id="canRead_@item.SecureFolderID" class="CHKreader" onchange="changePermissions(@item.SecureFolderID)" checked="@(singleItem != null && singleItem.FolderRead)" />

    <input type="checkbox" id="canWrite_@item.SecureFolderID" class="CHKwriter" onchange="changePermissions(@item.SecureFolderID)" checked="@(singleItem != null && singleItem.FolderWrite)" />

    <input class="datepick" id="expDate_@item.SecureFolderID" onchange="changePermissions(@item.SecureFolderID)" value="@((singleItem != null && singleItem.ExpireDate != null)?singleItem.ExpireDate.Value.ToString("yyyy-MM-dd"):null)" />

Going further, if item/singleitem are coming from an Enumerable, there is probably a better way to generate the Ids as well.  Especially if you want them to post back into a nice object.  Remove the classes, remove the onchange handler.

@for(var i=0;i<Model.Count;i++)
{

      @Html.CheckBoxFor(m=>m[i].FolderRead)

      @Html.CheckBoxFor(m=>m[i].FolderWrite)

      @Html.TextBoxFor(m=>m[i].ExpireDate,new{type="date"}) // HTML5 date w/datepicker for browsers that support it

}

You could also use an EditorFor on the date and create your own template if you prefer that route.


Fast distance calculation for Starcraft2 bot

You should probably have another look at the scipy.spatial module. It provides (hopefully) faster methods for most of these checks using a k-d-tree.

from scipy.spatial import cKDTree

class Points(np.ndarray):
    def __new__(cls, units_or_points):
        obj = np.asarray(units_or_points).view(cls)
        obj.kd_tree = cKDTree(obj)
        return obj

    def closest_to(self, point: Point2) -> Point2:
        """Returns the point of self that is closest to another point."""
        _, i = self.kd_tree.query([[point.x, point.y]])
        return Point2(self[i][0])

    def closer_than(self, point: Point2, distance: Union[int, float]) -> "Points":
        """Returns a new Points object with all points of self that
        are closer than distance to point."""
        selection = self.kd_tree.query_ball_point([point.x, point.y], distance)
        return self[selection]

    def in_distance_between(
        self, point: Point2, distance1: Union[int, float], distance2: Union[int, float]
    ) -> "Points":
        """Returns a new Points object with all points of self
        that are between distance1 and distance2 away from point."""
        selection_close = self.kd_tree.query_ball_point([point.x, point.y], distance1)
        selection_far = self.kd_tree.query_ball_point([point.x, point.y], distance2)
        selection = list(set(selection_far) - set(selection_close))
        return self[selection]

    def closest_n_points(self, point: Point2, n: int) -> "Points":
        """Returns a new Points object with the n points of self that are closest to point."""
        _, indices = self.kd_tree.query([[point.x, point.y]], k=n)
        return self[indices]

    def in_distance_of_points(self, points: "Points", distance: Union[int, float]) -> "Points":
        """Returns a new Points object with every point of self that
        is in distance of any point in points."""
        pairs = self.kd_tree.query_ball_tree(points.kd_tree, distance)
        return points[[i for closest in pairs for i in closest]]

These are all the ones I could quickly find a way for using the tree. Not included are sort_by_distance_to, n_closest_to_distance and n_closest_to_distance.

In order to test if this is really faster, here are some tests, with the following setup:

np.random.seed(42)
points = np.random.rand(300, 2)
points_graipher = Points(points)
points_op = PointsOP(points)
point = Point2(np.random.rand(2))
points2 = np.random.rand(10, 2)
points2_graipher = Points(points2)

Here PointsOP is you class and Points is the class defined in this answer.

%timeit points_op.closest_to(point)
# 38.3 µs ± 1.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit points_graipher.closest_to(point)
# 43.7 µs ± 249 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit points_op.closer_than(point, 0.1)
# 39.5 µs ± 238 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit points_graipher.closer_than(point, 0.1)
# 11 µs ± 26 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit points_op.in_distance_between(point, 0.1, 0.2)
# 52.9 µs ± 275 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit points_graipher.in_distance_between(point, 0.1, 0.2)
# 21.9 µs ± 180 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit points_op.closest_n_points(point, 10)
# 29.5 µs ± 359 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit points_graipher.closest_n_points(point, 10)
# 41.7 µs ± 287 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit points_op.in_distance_of_points(points2, 0.1)
# 116 µs ± 727 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit points_graipher.in_distance_of_points(points2_graipher, 0.1)
# 89.2 µs ± 500 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

As you can see for \$N = 300\$ points there are some methods which are faster with the KDTree (up to four times), some that are basically the same and some that are slower (by up to two times).

To get a feeling how the different approaches, scale, here are some plots. The only thing changing is the number of points. The steps are 30, 300, 3000, 30000.

To summarize, you should check this for some actual cases you have. Depending on the size of points your implementation or this implementation is faster.


The logic is mostly clear, but it's not obvious exactly how to change to one of the other scales.  There's also a case where calling the function wrongly (with vmin==vmax), you'll divide by zero.  Although that's a bug in the calling code, it may be preferable to take a defensive line on this, and just return the middle value.

I'd be inclined to split this into two three parts:

scale the input value to the range [0,1]
split into one of the sub-ranges [0,0.5) or [0.5,1]
interpolate linearly between the two colours

I'll start with the last of those.  Assuming that the input is between 0 and 1, we can interpolate quite easily:

cv::Scalar get_colour(double alpha, const cv::Scalar& c0, const cv::Scalar& c1)
{
    return (1-alpha) * c0  +  alpha * c1;
}

How do we get that value between 0 and 1?  Steps 1 and 2 look like

cv::Scalar get_colour(double v, double vmin, double vmax)
{
    // clamp value within range
    v = v <= vmin ? vmin
        : v >= vmax ? vmax
        : v;

    const double alpha = (vmax <= vmin)
        ? 0.5                   // avoid divide by zero
        : (v - vmin) / (vmax - vmin);

    static const cv::Scalar blue{ 255, 0, 0 };
    static const cv::Scalar white{ 255, 255, 255 };
    static const cv::Scalar red{ 0, 0, 255 };

    if (alpha < 0.5) {
        return get_colour(alpha * 2, blue, white);
    } else {
        return get_colour(alpha * 2 - 1, white, red);
    }
}

Here, we have used constants for the colours in both parts of the gradient, meaning that if we want to change to different colours, there's only one place that needs changing.

I hope it's apparent with this change that we could make the interpolation into an object, with the range and colours being member data.  Depending on your application, that may be easier to work with than free functions with lots of parameters.


Is it good OOP style?

No. The class contains a IAsyncCursor<TResult> field and a IList<TResult> field,
but depending on how it's constructed,
only one of these will be actually used.
This is a pretty clear indication that we have two classes masquerading as one.

  Maybe I need to split this class into two classes?

You hit the nail on the head!

  How to do this? What methods should I need to take out to the interfaces?

The interface should contain GetEnumerator and that's it.
That's the common functionality.
Let's call the interface DeferredResultCollection<TResult>.

Next, add two classes that implement this interface,
one using a IAsyncCursor<TResult> and the other a IList<TResult>,
let's call these CursorBasedDeferredResultCollection<TResult> and ListBasedDeferredResultCollection<TResult>.

Optionally, you could add a factory,
let's call it DeferredResultCollections,
with two methods, such that both return objects of the interface type DeferredResultCollection<TResult>,
but one of them takes a IAsyncCursor<TResult> and the other a IList<TResult> as parameter,
and create and return objects with the appropriate implementations.
This has the benefit that users don't need to learn the names of the implementation classes.
In fact they don't even need to know them at all (they can be private).


Shorter:

There are possibilities to make the code shorted without making it less correct/clear.

for(auto it = input.begin(); it!= input.end(); ++it)

Range loop could be used for this purpose.

        if(freq.find(*it) != freq.end())
        {
            freq[*it] += 1;
        }
        else
        {
            freq[*it] = 1;
        }

map zero initializes built in types when it creates the key-value pair. Source. So the check can be removed, and ++ used instead of +1. The change may also improve performance, but I don't think it will be much of a deal.

    std::vector<std::pair<char, int >> v;
    std::transform(freq.begin(), freq.end(), std::back_inserter(v), [](std::pair<char , int > kv) {return kv;});

std::vector has a constructor which takes iterator pair and constructs the container from that.

    std::make_heap(v.begin(), v.end(), CompareHeap());
    while(v.size() > 0)
    {
        std::pop_heap(v.begin(), v.end(), CompareHeap());
        answer += std::string(v.back().second,v.back().first);
        v.pop_back();
    }

In my opinion sort would be a better fit (making a heap is sorting too, but I think std::sort have potential to perform better), then do range for loop with the last 2 lines of the code inside of it. Currently intentions are less clear, though still good.

Style:

I think that having operator() in the outside class is confusing. If the clarity is really wanted, named lambda could be made, then passed to std::sort() or make_heap().

Theoretically input.length() can be bigger than maximum value of int, so std::size_t should be used, just to be nerd that cares about standard compliance.

Usage of map:

I think that map is the most clear solution for this problem. It lifts a lot of burden from the programmer. There are also possibilities that compiler vendor did some small map optimization (so everything will be in the automatic storage).

Copying the map into vector will probably cost nothing, since everything is POD, so it will decay into std::memset() or something similar (in case the map is small map, it will be even faster).

Sorting a vector should be fast as well, since char on the platform has theoretical maximum of 256 values.

The only thing that could be slightly sped up is putting the data into the result. reserve(input.length()) can be called on the result string so that it won't perform any additional memory allocations.

Performance:

The algorithm should be fast enough for most of the systems, unless insane blazing performance is needed (e.g. Facebook or similar).


So, this isn't a full answer to your question, but maybe still relevant.

Included with the Linux sources is scripts/checkpatch.pl - which checks for things like coding style compliance, but also warns on use of outdated interfaces.

If you have a checked out (clean) git repository of the kernel, you can simply copy your source file into there and run

linux$ git diff HEAD | scripts/checkpatch.pl -

Doing that on the above code does point out a few things not just coding-style related.


Why is my Sieve of Eratosthenes using generators so slow

That's not the sieve of Eratosthenes
It's rather prime trial division.
Your filter for 2 lets 1/2 of all numbers through, your filter for 3 lets 2/3 of all remaining numbers through, etc. So 1/2 * 2/3 * 4/5 * 6/7 = 22% of all numbers make it through your filters for 2, 3, 5 and 7, so your filter for 11 will have to check 22% of all numbers. The real sieve of Eratosthenes treats 11 by marking off every 11th number, i.e., only 9% of all numbers. Less than half of your percentage. And yours gets worse for the larger primes. For example your filters for the primes from 2 to 89 let ~12% of all numbers through, so your filter for 97 checks ~12% of all numbers. While the real sieve of Eratosthenes treats 97 by marking off only about 1% of all numbers.
So that's why it's slow. It's doing way too much work.
An improvement
You can make it a bit faster by not stacking filters but simply doing the trial divisions at the current number, using the primes you're collecting anyway:
from itertools import count

def primes(n):
    primes = []
    sieve = (x for x in count(2) if all(x % p for p in primes))
    for _ in range(n):
        primes.append(next(sieve))
    return primes

Or using islice:
from itertools import count, islice

def primes(n):
    primes = []
    sieve = (x for x in count(2) if all(x % p for p in primes))
    primes += islice(sieve, n)
    return primes

Demo:
>>> primes(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

The real thing
But here's a genuine lazy one based on the paper mentioned by trentcl. I add each prime to the list of its next multiple. When the list of the next x is empty, it's thus a prime. Otherwise, I move the primes from the list to their next multiples.
from itertools import count
from collections import defaultdict

def primes(n):
    marked = defaultdict(list)
    primes = []
    for x in count(2):
        if x in marked:
            for p in marked.pop(x):
                marked[x + p].append(p)
        else:
            primes.append(x)
            if len(primes) == n:
                return primes
            marked[x * x].append(x)

Benchmark 1
Times for n = 10000 (benchmark code at the end of the answer):
9.330 s  original
3.502 s  improved1
3.499 s  improved2
0.065 s  genuine

That said, your original and my improved version can be made much faster by using fewer filters (only up to the square root of the current number), as I've done in my later answer.
To infinity and beyond
As Eric Duminil showed, it's trivial to make the latter an infinite generator, which also makes it shorter. No need to build a result list and check whether you're done, just yield the primes:
infinite:
def primes():
    marked = defaultdict(list)
    for x in count(2):
        if x in marked:
            for p in marked.pop(x):
                marked[x + p].append(p)
        else:
            yield x
            marked[x * x].append(x)

The other solutions can similarly be turned into infinite generators, but meh, they're no good anyway. Plus in my improved1 and improved2, the primes list is not just the result but is also used for filtering, so I need to build it anyway.
As infinite generator, it's more versatile. You can still get a list of the first n if you want to:
>>> list(islice(primes(), 20))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]

You can also get all primes up to a desired limit:
>>> *itertools.takewhile(72 .__gt__, primes()),
(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71)

Or if you neither know how many you need nor how big you need but you need "enough" somehow, for example enough so that their product exceeds a million:
>>> result, product = [], 1
>>> it = primes()
>>> while product < 10**6:
        p = next(it)
        result.append(p)
        product *= p

>>> result
[2, 3, 5, 7, 11, 13, 17, 19]

Or if you just want the millionth prime:
>>> next(islice(primes(), 999999, None))
15485863

Or if you have a prime and want to know the "how manyth" prime it is:
>>> from operator import indexOf
>>> indexOf(primes(), 15485863) + 1
1000000

Or if you have a prime and want to know the next larger one (granted, there are more efficient ways to do that):
>>> it = primes()
>>> 89 in it and next(it)
97

Note that in the last few cases, you don't want a list of primes at all, so building one is wasted memory.
Speaking of memory, though... the generator (and also my version) do take a lot of memory. Here are memory measurements and benchmarks for up to n=1,000,000 for the above "infinite" solution and the solutions I'll show below:
            |     time for the first...    | tracemalloc for 1,000,000
            |  10,000   100,000  1,000,000 |     size         peak
------------+------------------------------+--------------------------
   infinite | 0.068 s   0.971 s   12.450 s |  231,866,275  312,793,599
   no_lists | 0.035 s   0.574 s    8.065 s |  143,870,959  226,554,527
     lazier | 0.033 s   0.456 s    6.016 s |   36,500,174   36,535,742
  recursive | 0.032 s   0.473 s    6.116 s |       72,169      109,109
    twostep | 0.015 s   0.217 s    2.897 s |       71,986      108,926

The memory usage was measured like this:
import tracemalloc
tracemalloc.start()
it = primes()
prime = next(islice(it, 9999999, None))
size, peak = tracemalloc.get_traced_memory()

So the above "infinite" solution takes hundreds of megabytes to generate the first million primes, i.e., hundreds of bytes per prime. Quite a lot. Let's see why, by doing global marked first thing in the primes() function so we can inspect it afterwards. We'll see that almost a million composites are marked and the dictionary takes 84 MB:
>>> it = primes()
>>> next(islice(it, 999999, None))
15485863
>>> from sys import getsizeof
>>> len(marked), getsizeof(marked)
(999919, 83886176)

The lists of primes total 88 MB, and almost all of them contain only a single prime marking the composite:
>>> sum(map(getsizeof, marked.values()))
87992872
>>> from collections import Counter
>>> Counter(map(len, marked.values()))
Counter({1: 999845, 2: 69, 3: 4, 4: 1})

The marked composites take 32 MB and the marking primes take 28 MB:
>>> sum(map(getsizeof, marked))
31983680
>>> from itertools import chain
>>> sum(map(getsizeof, chain.from_iterable(marked.values())))
27999972

Together that's indeed 232 MB as reported by tracemalloc in the table above:
>>> 84 + 88 + 32 + 28
232

Since most lists of marking primes just contain a single prime anyway, let's store only the first prime at the composite. If more primes want to mark that composite, then instead move them ahead to their next multiple:
no_lists:
def primes():
    marked = {}
    for x in count(2):
        if x in marked:
            p = marked.pop(x)
            while (x := x + p) in marked:
                pass
            marked[x] = p
        else:
            yield x
            marked[x * x] = x

As the above table showed, this made it faster and saved a lot of memory.
In my other answer, I showed that prematurely setting marked[x * x] as soon as you discover a new prime x is wasteful. Let's rewrite the better version from there as an infinite generator as well. Here m is the next marking prime, and it will start marking as soon as we reach m2=m2.
lazier:
def primes():
    yield 2
    primes = [2]
    markers = iter(primes)
    marked = {}
    m = next(markers)
    m2 = m * m
    for x in count(3):
        if x == m2:
            while (x := x + m) in marked:
                pass
            marked[x] = m
            m = next(markers)
            m2 = m * m
        elif x in marked:
            p = marked.pop(x)
            while (x := x + p) in marked:
                pass
            marked[x] = p
        else:
            yield x
            primes.append(x)

This brought it down to under 37 MB, as marked got much smaller. However, it creates a primes list again, in order to update m to the next next marking prime.
Can we get the best of both worlds? Not prematurely enter marked[x * x] and not build a primes list? Yes we can!
What do we use the primes list for? Just as a more slowly used stream of primes. But that's what we're writing! A generator of primes. So we can use it recursively. Our main generator iterator of primes will use a slower generator iterator of primes. But where does that slower one get its marker primes from? From yet another even more slowly progressing one, if needed. And so on. A potentially infinite stack of infinite iterators.
recursive:
(also see the addendum at the end of the answer for better versions of this)
def primes():
    yield 2
    marked = {}
    markers = primes()
    m = next(markers)
    m2 = m * m
    for x in count(3):
        if x == m2:
            while (x := x + m) in marked:
                pass
            marked[x] = m
            m = next(markers)
            m2 = m * m
        elif x in marked:
            p = marked.pop(x)
            while (x := x + p) in marked:
                pass
            marked[x] = p
        else:
            yield x

Let's see the levels by storing each iterator's marked in a global levels list by doing levels.append(marked) right after marked = {}. Then:
>>> levels = []
>>> millionth = next(islice(primes(), 999999, None))
>>> for marked in levels:
        print(len(marked), max(marked.values()))

546 3931
18 61
4 7
2 3
1 2

We see that there are five levels of iterators. The top-level iterator, the one we're using directly, has 546 marking primes, the largest being 3931. That makes sense, as the next larger prime is 3943, which starts marking at 39432, which is larger than the millionth prime:
>>> it = primes()
>>> 3931 in it and next(it)
3943
>>> 3943**2
15547249
>>> millionth
15485863

The next-lower level so far only needed to yield the 18 primes up to 61. Which is correct, as the next-larger prime 67 will only start marking at 672=4489, well above the prime 3943 needed next by the top-level iterator. And so on, until the fifth and lowest level only needed its initial yield 2 so far.
With only a few hundred primes in all levels combined, it's no wonder this solution takes faaar less memory than our first "infinite" one, about 3000 times less, only around 100 KB. And its advantage will increase for larger numbers of primes, as the earlier solutions need O(n) memory while the recursive ones take something like O(sqrt(n)) memory (not sure how the density of primes affects it).
Last but not least, here's a little variation where I handle the prime 2 separately and then move everything twice as fast, which makes the overall solution about twice as fast (again see the table above):
twostep:
def primes():
    yield 2
    yield 3
    marked = {}
    markers = primes()
    next(markers)
    m = next(markers)
    m2 = m * m
    for x in count(5, 2):
        if x == m2:
            marked[m2 + 2*m] = 2*m
            m = next(markers)
            m2 = m * m
        elif x in marked:
            step = marked.pop(x)
            while (x := x + step) in marked:
                pass
            marked[x] = step
        else:
            yield x

Code for benchmark 1:
from timeit import repeat
from itertools import count, islice
from collections import defaultdict

def original(n):
    sieve = count(2)
    primes = []
    nprime = 0
    for _ in range(n):
        nprime = next(sieve)
        primes.append(nprime)
        sieve = filter(eval(f"lambda x: x % {nprime} != 0"), sieve)
    return primes

def improved1(n):
    primes = []
    sieve = (x for x in count(2) if all(x % p for p in primes))
    for _ in range(n):
        primes.append(next(sieve))
    return primes

def improved2(n):
    primes = []
    sieve = (x for x in count(2) if all(x % p for p in primes))
    primes += islice(sieve, n)
    return primes

def genuine(n):
    marked = defaultdict(list)
    primes = []
    for x in count(2):
        if x in marked:
            for p in marked.pop(x):
                marked[x + p].append(p)
        else:
            primes.append(x)
            if len(primes) == n:
                return primes
            marked[x * x].append(x)

funcs = original, improved1, improved2, genuine

n = 10000

expect = funcs[0](n)
for func in funcs[1:]:
    print(func(n) == expect, func.__name__)

for _ in range(3):
    for func in funcs:
        t = min(repeat(lambda: func(n), number=1))
        print('%.3f s ' % t, func.__name__)
    print()

Addendum - better recursive generators
I came up with a nicer way later, don't want to rewrite the answer using this now but want to share. This goes through the primes of the underlying generator in an outer loop and from one prime's square to the next prime's square in an inner loop. It's less code and makes the structure of the procedure clearer.
def primes():
    yield 2
    marks = {}
    i = 2
    for p in primes():
        for i in range(i+1, p*p):
            if i not in marks:
                yield i
            else:
                m = marks.pop(i)
                j = i + m
                while j in marks:
                    j += m
                marks[j] = m
        marks[p*p] = p

And a version with the paper's way of potentially storing several primes at the same common multiple:
def primes():
    yield 2
    marks = defaultdict(set)
    i = 2
    for p in primes():
        for i in range(i+1, p*p):
            if i not in marks:
                yield i
            else:
                for m in marks.pop(i):
                    marks[i+m].add(m)
        marks[p*p] = {p}


waitUntilClear is always 0 when clearScreen is false then boolean flag is redundant:

void setDisplay(String lineValue, int lineNumber, unsigned long msToWaitBeforeClear) {
  lcd.setCursor(0, lineNumber),
  lcd.print(lineValue);

  if (msToWaitBeforeClear > 0) {
   delay(msToWaitBeforeClear);
   lcd.clear();
  }
}

Note that delay() accepts unsigned long instead of int then our parameter should match its type (does it make sense to have a negative delay?)

Now is (should be) clearer that we're calling setDisplay() twice but it's easier to simply call it with the index of the current line:

void displayPage(String messages[], size_t startIndex) {
  for (int8_t rowIndex = 0; rowIndex < NUMBER_OF_DISPLAY_LINES; ++rowIndex) {
      lcd.setCursor(0, rowIndex),
      lcd.print(messages[startIndex + rowIndex]);
  }

   delay(DELAY_BETWEEN_PAGES_IN_MS);
   lcd.clear();
}

Used as:

for (size_t i = 0; i < COUNT_ELEMENTS - 1; ++i) {
  displayPage(messages, i);
}

Now it's time to remove those magic numbers in setup() and lcd declaration. I'd also suggest to move all global constants to the very top, outside functions (probably in a separate file). It's what you want to change to configure your display and it's better if you don't have to search them buried inside code.

One small note: if you manually unroll the loop over NUMBER_OF_DISPLAY_ROWS then you can skip the first call to setCursor() because clear() already do it for you:

void displayPage(String messages[], size_t startIndex) {
    lcd.print(messages[startIndex]);
    lcd.setCursor(0, 1),
    lcd.print(messages[startIndex + 1]);

    delay(DELAY_BETWEEN_PAGES_IN_MS);
    lcd.clear();
}


ConcurrentThrottledList - Will this implementation be thread safe?

@ChrisW made valuable comments, I'll add mine:
Well done:

I like that private fields are all1 readonly, this makes intent explicit, which works towards greater maintainability.
I like that the class is highly cohesive and focused, this works towards greater readability, maintainability and extensibility.

Nitpicks:

I don't see why _lock gets an underscore and items and maxItems don't; being consistent with the underscore prefix for private fields would mootinate the this qualifier in the constructor.

Items could be called ToArray, making it more consistent with the framework's lingo, and more representative of its semantics.

TryAdd and TryRemove both look like they were named after the TryParse pattern; a developper looking at the API would then also be expecting an Add and a Remove method:

Add would add the specified item, throw an exception if it can't, and return void.
TryAdd would add the specified item, return true if successful and false otherwise.
Remove would remove the specified item, throw an exception if it can't, and return void.
TryRemove would remove the specified item, return true if successful and false otherwise.

However, List<T>.Remove() is already taking care of returning false if the specified item cannot be removed - throwing an exception in that case would be utter nonsense. Therefore, I'll second @ChrisW in saying that TryRemove should be simply called Remove.
I agree with TryAdd being called as such, because I would seriously expect an Add method to return void, so I'd consider also having an Add method that throws some CapacityExceededException (or whatever is more appropriate) when it can't add the specified item.

1 I would be led to believe _lock could also be made readonly, but I don't work with enough multithreaded code to know whether that would/could impact anything.


Codeigniter 3 - Set Flashdata Array issue

This seems more like a code review question (like Alive to Die comments), so I'm not entirely sure what you are needing.  For the most part, your code looks fine.  I have a few things to consider, but they are mainly preferential.

You could adjust the View output within the form.

<?php
    for($i=0; $i<$max; $i++) {
        echo '<label>Username ' . $i . ' </label><input type="text" placeholder="username" name="username[' . $i . ']>';
    }
?>

In your Controller, you could also initiate $a and $b differently, as mentioned in this Stack Overflow article: Assign same value to multiple variables.

$a = $b = 1;


Classifying integers as "weird" or "not weird"

In addition to the things dfhwze already mentioned:

You should separate calculation and output. Even the shorter solution mentioned by dfhwze contains a repetition of the output code (System.out.println) and the output message ("Not weird"). Furthermore, thinking on to real world problems, code that only outputs something is really hard to unit-test.

Thus, do something like:

private static boolean isWeird(int n) {
   return (n % 2 != 0) || (n >= 6 && n <= 20); // or however you want to do the calculation
}

... // and in main:
boolean weird = isWeird(n);
if (weird) {
   System.out.println("Weird");
}
else {
   System.out.println("Not Weird");
}

One missing convention: variables should start with a lowecase character: N should be renamed to n


my code is messy and wasteful of lines, how do I make my code simple

Because the <div> associated with each input not its adjacent sibling, but its next sibling, you can dynamically navigate from the element being validated to its associated icon with .nextElementSibling calls. But your checkFileType isn't set up to call the success callback with a calling context of the element it's attached to, so fix that first. Change the success and error calls to:
options.success.call(this);

options.error.call(this);

and then the rest of your code simplifies to the following:
$('input[type="file"]').checkFileType({
    allowedExtensions: ["pdf"],
    success() {
        $(this).next().next().attr('class', 'checkmark');
    },
    error() {
        $(this).val('');
        $(this).next().next().attr('class', 'crossmark');
    },
});

If you're going to use jQuery, go ahead and use it instead of the native DOM methods like getElementById if you want, native DOM methods are a bit more verbose than jQuery's $.
Using the above method, you'll also be able to remove the IDs entirely from your HTML. (Numeric indexed IDs are quite a code smell anyway.)
This is a pretty simple problem though, it seems pretty odd to need to use a big library like jQuery for something this trivial. (If you're just learning JavaScript, consider focusing on learning just built-in JavaScript rather than a particular library like jQuery, which is somewhat obsolete for most things it's used for nowadays - built-in methods work just fine and are usually easier to understand in my experience)
Just as one example, rather than
if ($.inArray(extension, options.allowedExtensions) == -1) {

you can use
if (!options.allowedExtensions.includes(extension)) {


Running a shell command when a file is added to FTP on Linux Ubuntu

[ x == y ] is not strictly-conforming POSIX sh. Use [ x = y ] instead.

Instead of using /home/MyName, you may consider using the environment variable ${HOME}.

I think you made a typo in "$ filename". Use "$filename" instead.

Good job on the commenting and indentation.


Interleaving values from several iterables

First off, I think there is an error in the original code. The code produces afhbgicjdke instead of the expected afhbgic. I think the intention was to return instead of pass in the stop iteration block, the answer below work under this assumption.

Let's look at the for loop in the middle

for i in range(len(itrs)):
    try:
        yield next(itrs[i])
        temp.append(itrs[i])
    except StopIteration:
        return

No where in the body operate on the index, so every itrs[i] can be replaced with just i with a simpler for i in iters. This gives us

for i in itrs:
    try:
        yield next(i)
        temp.append(i)
    except StopIteration:
        return

Now lets look at the while body

while itrs != []:
    temp = []
    # ... the for loop that includes an append to itrs
    itrs = temp

This basically gives the code a way to exit when everything is finished. However, if you think about how the code works, the only time itrs has a lower length than args is when one of the itrs reaches StopIteration. In that case, we would have returned already!

So the while loop can become a while True loop and temp and it's usage can be ommited.

def skip(*args):
    itrs = [iter(arg) for arg in args]
    while True:
        for i in itrs:
            try:
                yield next(i)
            except StopIteration:
                return

Now we need to convince ourselves that the code will actually return at some point. This isn't too hard, as long as one of the iterable passed in is finite i.e. has an end, we will reach StopIteration at some point. And in the case that every iterable is infinite, the original code would run forever too. So we are good there.

But there is another problem. What if skip is called with no argument? This will result in us never returning from the function, since there is no iterable for us to trigger StopIteration! In the original code, this is dealt with implicitly through temp being empty. Since we don't have that anymore, we have to handle it explicitly.
This gives us the final code:

def skip(*args):
    if len(args) == 0:
        return
    itrs = [iter(arg) for arg in args]
    while True:
        for i in itrs:
            try:
                yield next(i)
            except StopIteration:
                return

With this

for i in skip('abcde','fg','hijk'):
    print(i,end='')

outputs afhbgic and

for i in skip():
    print(i,end='')

is a noop

As an aside, the indentation in the original code is inconsistent, which makes it un-runnable. Please be sure to post usable code next time


Why a string array . Just a String would suffice.
Do we really need to store it in arrays. The computed arrays would only be usde to display. So we can work towards a display method instead of storing and displaying them.

int i;
for(i=1;i<26;i++){
    System.out.print(i+", ");
    System.out.print(Character.toString((char)(64+i))+", ");
}
System.out.print(i+", ");
System.out.println(Character.toString((char)(64+i))+".");

StringBuilder next = new StringBuilder();
for(i=1;i<26;i++){
    System.out.print(i+", ");
    next.append(Character.toString((char)(64+i)) + ", ");
    System.out.print(next);
}
System.out.print(i+", ");
next.append(Character.toString((char)(64+i)));
System.out.println(next);
// Time complexity: O(n)
// Space complexity: O(n+m*(m+1)/2))

Assuming we are striving to have a generic implementation wherein we have two input arrays and we wish to provide the output. Even in that case we can carry forward with above implementation with slight changes.
Having the last condition check seems an unneeded overhead. Instead we loop in for last-but-one index and print the last outside.

if ((i + 1) == result.length)


Validator extended to handle domain objects / entities

I disagree with @Madara Uchiha on a several points.

If you couple business rule validations to the domain object, you cannot apply different business rules to the same domain object.

Never assume you will only have one set of business rules. By creating validators outside the domain object, you give yourself the flexibility of creating whole different swaths of business rules without touching the domain layer.

Basically, by the time you go to save a domain object to a database or other repository it should be completely valid from a business rule AND storage perspective. This allows you to communicate problems to the user in a manor that allows them to correct their mistake. If you let a SQL error propagate up the call stack and result in a 500 Internal Server Error, you as a programmer have not done your due diligence when validating data.

Now I could see a case for separating the storage validations from the business rules. Maybe you start out persisting your domain objects in a database, but later you move to a RESTfull web service. The web service may have different basic data validations, which you can then swap out for a different validator while keeping your existing business rule validations.
I disagree that this solution doesn't scale. Quite the opposite actually. It scales very well. Mashing your validations into the domain object is what doesn't scale. Changing the storage mechanism or needing to apply different categories of business rules gets complicated when your domain objects validate themselves. Domain objects should be mere boxes containing data. The decision of whether that data is correct is wholly out of scope for the domain object, in my opinion.
The storage manager should have absolutely no validations. It should accept a domain object, attempt to persist it and throw an exception if anything goes wrong.

Really, all of my objections are related to this tenet of software engineering, and especially object oriented programming: Do one thing, and do it well.

Putting validations into your domain objects means they are serving a dual purpose: Hold data from a storage medium AND ensuring it is valid. Do one thing and do it well. The domain object should hold data. The validation layer should ensure things are valid.

Putting validations into your storage manager means it is serving a dual purpose in the same manor. You should be able to swap out one layer for another with minimal refactoring. If you have to copy and paste of rewrite lots of code, then your application needs additional layers with looser coupling.


Reversing an array in C++ 14, my second array requires an extra element

The first couple of lines show that this is shoddy code:

#include <bits/stdc++.h>

using namespace std;

<bits/stdc++.h> is not a standard header, and dragging all of std into the default namespace is a maintainability disaster (see other Code Review answers, ad nauseum).
None of the code which reads from std::cin ever checks whether the reading was successful, and there's no error handling whatsoever.
arr is a terrible name for a vector.  arr2 is worse.
There's no need for handcrafted loops, when we could use std::copy_n() to read elements, and std::reverse() to reorder them.
Actually, there's no need to reorder the stored data - just write the output using a reverse iterator.

The low quality shows up when we analyse the memory accesses:
valgrind ./255602 <<<$'4\n1 4 3 2 5'
==5474== Memcheck, a memory error detector
==5474== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==5474== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==5474== Command: ./255602-orig
==5474==
==5474== Invalid write of size 4
==5474==    at 0x10B466: main (255602.cpp:30)
==5474==  Address 0x4d49000 is 0 bytes after a block of size 16 alloc'd
==5474==    at 0x480BDEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==5474==    by 0x10E741: __gnu_cxx::new_allocator<int>::allocate(unsigned long, void const*) (new_allocator.h:115)
==5474==    by 0x10E437: allocate (allocator.h:173)
==5474==    by 0x10E437: std::allocator_traits<std::allocator<int> >::allocate(std::allocator<int>&, unsigned long) (alloc_traits.h:460)
==5474==    by 0x10DE3F: std::_Vector_base<int, std::allocator<int> >::_M_allocate(unsigned long) (stl_vector.h:346)
==5474==    by 0x10D60C: std::_Vector_base<int, std::allocator<int> >::_M_create_storage(unsigned long) (stl_vector.h:361)
==5474==    by 0x10CEA0: std::_Vector_base<int, std::allocator<int> >::_Vector_base(unsigned long, std::allocator<int> const&) (stl_vector.h:305)
==5474==    by 0x10C46C: std::vector<int, std::allocator<int> >::vector(unsigned long, std::allocator<int> const&) (stl_vector.h:511)
==5474==    by 0x10B3B6: main (255602.cpp:21)
==5474==
==5474== Invalid read of size 4
==5474==    at 0x10B449: main (255602.cpp:30)
==5474==  Address 0x4d48fb0 is 0 bytes after a block of size 16 alloc'd
==5474==    at 0x480BDEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==5474==    by 0x10E741: __gnu_cxx::new_allocator<int>::allocate(unsigned long, void const*) (new_allocator.h:115)
==5474==    by 0x10E437: allocate (allocator.h:173)
==5474==    by 0x10E437: std::allocator_traits<std::allocator<int> >::allocate(std::allocator<int>&, unsigned long) (alloc_traits.h:460)
==5474==    by 0x10DE3F: std::_Vector_base<int, std::allocator<int> >::_M_allocate(unsigned long) (stl_vector.h:346)
==5474==    by 0x10D60C: std::_Vector_base<int, std::allocator<int> >::_M_create_storage(unsigned long) (stl_vector.h:361)
==5474==    by 0x10CEA0: std::_Vector_base<int, std::allocator<int> >::_Vector_base(unsigned long, std::allocator<int> const&) (stl_vector.h:305)
==5474==    by 0x10C46C: std::vector<int, std::allocator<int> >::vector(unsigned long, std::allocator<int> const&) (stl_vector.h:511)
==5474==    by 0x10B382: main (255602.cpp:20)
==5474==
==5474== Invalid read of size 4
==5474==    at 0x10B495: main (255602.cpp:33)
==5474==  Address 0x4d49000 is 0 bytes after a block of size 16 alloc'd
==5474==    at 0x480BDEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==5474==    by 0x10E741: __gnu_cxx::new_allocator<int>::allocate(unsigned long, void const*) (new_allocator.h:115)
==5474==    by 0x10E437: allocate (allocator.h:173)
==5474==    by 0x10E437: std::allocator_traits<std::allocator<int> >::allocate(std::allocator<int>&, unsigned long) (alloc_traits.h:460)
==5474==    by 0x10DE3F: std::_Vector_base<int, std::allocator<int> >::_M_allocate(unsigned long) (stl_vector.h:346)
==5474==    by 0x10D60C: std::_Vector_base<int, std::allocator<int> >::_M_create_storage(unsigned long) (stl_vector.h:361)
==5474==    by 0x10CEA0: std::_Vector_base<int, std::allocator<int> >::_Vector_base(unsigned long, std::allocator<int> const&) (stl_vector.h:305)
==5474==    by 0x10C46C: std::vector<int, std::allocator<int> >::vector(unsigned long, std::allocator<int> const&) (stl_vector.h:511)
==5474==    by 0x10B3B6: main (255602.cpp:21)
==5474==
2 3 4 1 ==5474==
==5474== HEAP SUMMARY:
==5474==     in use at exit: 0 bytes in 0 blocks
==5474==   total heap usage: 9 allocs, 9 frees, 78,336 bytes allocated
==5474==
==5474== All heap blocks were freed -- no leaks are possible
==5474==
==5474== For counts of detected and suppressed errors, rerun with: -v
==5474== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)

Such failures fall short of working, in my opinion.

This is what a decent C++ program to do this looks like:
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

int main()
{
    // read the inputs
    std::size_t n;
    std::cin >> n;
    if (!std::cin) {
        std::cerr << "Failed to read number of elements\n";
        return EXIT_FAILURE;
    }

    std::vector<std::string> elements;
    elements.reserve(n);
    std::copy_n(std::istream_iterator<std::string>{std::cin},
                n, std::back_inserter(elements));
    if (!std::cin) {
        std::cerr << "Failed to read element content\n";
        return EXIT_FAILURE;
    }

    // write the values, in reverse order
    std::copy(elements.crbegin(), elements.crend(),
              std::ostream_iterator<std::string>{std::cout, " "});
}

See - no loops or arithmetic required.
Or, if you prefer an exception-based error handling strategy:
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

// read size from stream, then read that many elements into a vector
template<typename T>
std::vector<T> read_size_and_vector(std::istream& is)
{
    std::size_t n;
    is >> n;
    std::vector<T> elements;
    elements.reserve(n);
    std::copy_n(std::istream_iterator<T>{is}, n, std::back_inserter(elements));
    return elements;
}

int main()
{
    std::cin.exceptions(std::istream::badbit|std::istream::failbit);
    try {
        auto const elements = read_size_and_vector<std::string>(std::cin);
        std::copy(elements.rbegin(), elements.rend(),
                  std::ostream_iterator<std::string>{std::cout, " "});
        return EXIT_SUCCESS;
    } catch (std::ios_base::failure&) {
        std::cerr << "Failed to read the input\n";
        return EXIT_FAILURE;
    }
}


Revised: Counting subnumbers divisible by a given prime

It is a bit weird to have two special cases and start with the case that it is neither of those. I would re-arrange your cases to
if p == 2:
    ...
elif p == 5:
    ...
else:
    ...

Unless you did this as a performance improvement, because a random prime is much more likely to be neither 2 nor 5, but in that case you should have some measurements to show that this is not a premature optimization and probably add a comment in the code.

If you iterate over something and need both the index and the value, use enumerate:
if p == 2:
    ans = sum(i for i, digit in enumerate(number, 1)
              if digit in {'0', '2', '4', '6', '8'})
elif p == 5:
    ans = sum(i for i, digit in enumerate(number, 1)
              if digit in {'0', '5'})

Note that I used the second (optional) argument of enumerate to start counting at one and I used a set instead of a tuple, because it has faster membership test (not a lot faster for small collections as this, but measurably faster). I also put it all into a generator expression and used sum.

Python has an official style-guide, PEP8, which recommends using lower_case for variables, so your counter should be called c, or better yet, something readable like digit_count. You can also factor out the 0 case to avoid having to check for it up to nine times:
else:
    slices = (int(number[i:]) % p for i in range(len(number)))
    digit_count = Counter(slices)

    # get the count of zeroes, with a default value of zero
    zeroes = digit_count.pop(0, 0)
    ans = (zeroes * (zeroes + 1)) // 2
    ans += sum((count * (count - 1)) // 2
               for count in digit_counts.values())


string str = "";

There's no sense in assigning str to an empty string just to over write it two lines later. This would be much more terse.

ImageManagerV1 imgMgr = new ImageManagerV1();
string str = imgMgr.galleryOrder(LocalConfig.ImageManagerAuthCode, Convert.ToInt32(hdnListingId.Value), "");

str.Replace("seq[]=","-").Split('-');

Why not just split on "seq[]="? The Replace feels unnecessary here. Actually, the more I look at this, why are you splitting? Split returns an array, but you're not making an assignment here. I really think you need to decide what this line is supposed to do.

str = str.Replace("&", "");
if (str == "") {
    for (int i = 0; i < nodelist.Count; i++) {
        str += "seq[]=" + i;
    }
}

Two things. As a maintainer of the code, I've no idea why you're stripping out the ampersands. A comment here is in order. Secondly, this loop needs a StringBuilder. StringBuilder is a mutable string of characters and thus, more efficient in this situation.

string[] strNew = str.Replace("seq[]=", "-").Split('-');

Okay, now you can skip the Replace and split directly on "seq[]=". Speaking of, that string seems to show up an awful lot. You should replace it with a constant.

string[] separators = new string[] {"seq[]="};
strNew = str.Split(separators, SplitStringOptions.None);

    for (int i = 0; i < strNew.Length; i++) {
        if (strNew[i] != "") {
            str += "-" + strNew[i];

At first glance, I want to tell you to use a string builder again, but I honestly don't have the foggiest idea why you just split the string apart, just to put it back together. Forget what I just said about splitting, and just Replace("seq[]=","-"). Don't split. It looks to be unecessary.


Parses XML to return the bus times at specified bus stop

Imports are okay, you'll find different advice about whether to import
individual functions, so I'll say no more.
You have __name__ ..., good, perhaps just move the contained block
into another function main so that you can easily invoke it from the
REPL.
is_empty is obsolete, at some point you'll just remember that empty
lists are False in a boolean context.  Oh and it's unused as well.
You have a lot of quoting options in Python, so if you need a literal
' in a string, consider delimiting it with " instead of using the
backslash syntax.
You're in Python, so perhaps also use the built-in HTTP library
instead of shelling out to curl.
format_set is more easily written with a list comprehension, e.g.:

def format_set(result_set):
    return [str(el.get_text()) for el in result_set]

Technically get_stop_number accepts more than just numbers and
'quit', so just be aware of that.  I'd inline the stop_numb
variable as well (n.b. why care about saving two characters there?)

...
return int(raw_input('> '))

get_stop_info has a camel-case variable s, that's inconsistent with
the rest and in general not advised in Python.  Again, the loop can be
a list comprehension, but maybe that'll be a bit too dense, your
choice.  In general returning an unstructured list like is will also
prevent the reader from getting a clearer understanding of the code,
but if it's just for display purposes that's fine.

...
return [[int(el.find('RouteNo').get_text()),
         str(el.find('RouteHeading').get_text()),
         format_set(el.find_all('TripStartTime'))]
        for el in soup.find_all('Route')]

I'm a fan of aggressively factoring out common code, you can try and
see how you like e.g. creating smaller functions for
int(el.find(name).get_text()) and so on; that can be helpful later
on as your program(s) grow(s).


Seems like a nice implementation! Here are my thoughts,

this is implicit. Consider removing this, i.e. use topPtr instead of this->topPtr. Similarly, void doesn't need to be used as an argument, consider removing void, i.e. top() instead of top(void).
Consider using std::size_t for MAX. Also, consider naming MAX as MAX_SIZE since it is slightly more descriptive. If using std::size_t, make sure not to subtract one from MAX to avoid overflow. Instead, when checking for equality, add one to the other side.
It might be nicer to use a T* instead of an int for topPtr. nullptr could be used instead of -1 initially for topPtr.
For print consider passing a std::ostream object. This allows for decoupling and one could pass in a std::ostringstream instead of std::cout if desired.
For top and pop, consider using assert instead if/else. An exception could also be used, but I think assert is a little nicer. To include a message, use something similar assert(!empty() && "Stack is empty. Can't pop");. See https://en.cppreference.com/w/cpp/error/assert. Maybe add a comment about the requirements of these functions.
Consider adding documentation for any public function. Include information such as what the function returns, requires, and modifies. For example, top requires there are element in the stack.


template<class Function, class Iterator, unsigned... IntegerSequence>
    auto apply(Function f, Iterator first, std::integer_sequence<unsigned, IntegerSequence...>)
    {
        return f(*std::next(first, IntegerSequence)...);
    }

The Iterator has the requirements of a forward iterator (dereferenceable, forward traversal, multipass).  At the very least, document the iterator type. Also, you should check to make sure the iterator meets the requirements.

The sequence type is too narrow and doesn't support a commonly used sequence like std::index_sequence.

The sequence helpers are defined in <utility>. Don't rely on latent dependencies from other includes, if you reference it, you should include it.

#include <cstddef>       // std::ptrdiff_t
#include <iterator>      // std::iterator_traits, std::next, std::distance
#include <type_traits>   // std::is_base_of
#include <optional>
#include <utility>       // std::make_integer_sequence
/* ... */

    template<class Function, class ForwardIterator, class Index, Index... Indices>
    auto apply(Function f, ForwardIterator first, std::integer_sequence<Index, Indices...>)
    {
        static_assert(
            std::is_base_of<std::forward_iterator_tag,
                typename std::iterator_traits<ForwardIterator>::iterator_category
            >::value, "");
        return f(*std::next(first, Indices)...);
    }

    template<typename F>
    constexpr const unsigned arg_count_v = arg_count<F>::value;

Programmers typically refer to the number of arguments or operands a function or operation takes as the Arity.

What is the arity of [](auto...){}? What is the arity of [](){} and how does that interact with any subsequent divisions?

Try to be consistent with your naming.  While F is commonly Function, you kinda bounce between the two.  Pick one and be consistent.

//Returns a pointer to the remainder values or the end or nullptr
template<class Iterator,class Function>
auto for_each_adjacent(Iterator begin,Iterator end,Function func)
-> std::optional<typename std::iterator_traits<Iterator>::pointer>

Adjacents work like a sliding window, where each subsequent window starts at an offset of 1 from the first element in the previous window, e.g.

$$
[1, 2], [2, 3], [3, 4], ...
$$

The behavior you have implemented is a window over chunk sizes, incrementing from the last element in the previous window instead of the first, e.g.

$$
[1, 2], [3, 4], [5, 6], ...
$$

and some remainder less than the the length.  Consider renaming this function to a name that better represents its action, (for_each_chunked?).

Reading your comment, why not just return std::optional<Iterator> or the Iterator itself? After the calls, begin will always point to the first element in the remaining chunk or end.  The user can check if the returned iterator is at end.

    using value_type = typename std::iterator_traits<Iterator>::value_type;
    const value_type length = std::distance(begin,end);

This doesn't make sense. Iterator::value_type is the type of the values that can be obtained by dereferencing the iterator.  std::list<std::string>::iterator::value_type is std::string.  Just use auto and let std::distance provide the correct type (iterator::difference_type, or std::ptrdiff_t).

    const auto length = std::distance(begin, end);

    const std::ptrdiff_t remainder = length % detail::arg_count_v<Function>;
    for (auto d = length; d >= detail::arg_count_v<Function>; d -= detail::arg_count_v<Function>)
        detail::apply(func,(end - d),std::make_integer_sequence<unsigned,detail::arg_count_v<Function>>());

return (remainder) ? std::make_optional(end - remainder) : std::nullopt;

Instead of trying to figure out if their are enough elements remaining to call a function by arity, just calculate the number of chunks you are going to call f with.  Integral division has the nice property of truncating the remainder.

    auto chunks = length / detail::arg_count_v<Function>;

If you really want the remainder

    auto [chunks, remainder] = std::div(length, detail::arg_count_v<Function>);

Then you just loop on that count.

    constexpr auto indices = std::make_index_sequence<detail::arg_count_v<Function>{};

    while (chunks--) {
        detail::apply(func, begin, indices);
        std::advance(begin, detail::arg_count_v<Function>);
    }

    return begin;

An added benefit it that you can keep supporting forward iterators (std::advance) instead of elevating the requirement to random access iterators (end - d, end-remainder).

  I am not sure to pass in a epilogue function for the remaining variables

Does your use-case require you to have the entire range consumed by functions?  Let the caller decide what to do and just return an iterator.


Make yourself a "template" that you immediately convert into html (using innerHtml or whatever your framework has handy), then use the dom to fix up the few variable bits. You may use ids to locate the tags that need substitution, if you can guarantee they are unique. Otherwise use XPath.


How to make this code follow Solid Principle C#

Let me show you how to review your code from SOLID principles point of view.
Here I try to list some general questions and give some guidance to help you determine that your current solution does violate some of the principles or not.
Single - Responsibility principle
Q: What does XYZ method do?
If your answer resembles to any of these:

First it ... then it ...
It does ... and it ...
It calls ... method and ... method
etc.

it is a good sign that your code method does too much things.
Just to make it clear this principle does NOT suggest to wrap each line into a separate function. On the contrary, it suggests to combine those that are closely related to each other to enhance cohesion. We should strive/aim for high cohesion and low coupling.
Open - Closed principle
Q: Is your XYZ method suitable for T or W type of changes?
In this principle you try to guess what will future present you. Let's suppose that XYZ can handle X, Y and Z. If you need to support T and W then do you need to modify the current code or can you for example inherit from that and override only the necessary methods?
Liskov Substitution principle
Not applicable here.
Interface Segregation principle
Q: Do I (as a consumer of your API) have to know what does each method of IXYZ do?
This principle suggests to try to think from the consumer perspective. If I want to call only X then do I need an interface which provides X, Y and Z? You can think of this principle as an extension of SRP to interfaces. If your interface contains members that are not highly coherent then you need to slip it.
Dependency Inversion principle
Q: Does your XYZ class / method depend on other concrete classes?
This principle suggests to depend on abstractions rather than on concrete types. (Remember we are aiming for loose coupling). If you depend on abstraction and not the implementation then you can switch easily without the need to modify this class (this helps OCP as well).

I hope this helped you a bit. I suggest to further read these excellent articles:

What to look for in a Code Review: SOLID Principles
The Zen of Code Reviews: Review As If You Own the Code
What to look for when reviewing code for SOLID principle ‘violations’


Add multiple instances of a property to a list

You can shorten the first part to 3x this:

var teamAverage1 = Players
    .Where(p => p.teamId == id && p.a == 'x')
    .Select(x => x.Average1)
    .ToList();

I don't like the p.a properties. They look like a bad design. But it's hard to say more from the snippet you've showed.


Updating tables with bulk of data through CSV

You can use first_or_initialize and first_or_create! to skip the if...else statementes.

location = Location.where(name: 'New York').first_or_create! do |loc|
  loc.short_name = 'NY'
  loc.status     = 'Active'
end

discipline = Discipline.where(name: 'Name', location_id: location.id).first_or_initialize
discipline.assign_attributes code: 'code', status: 'Active'
discipline.save!

speciality = Speciality.where(name: 'Name', location_id: location.id).first_or_initialize
speciality.assign_attributes code: 'code', discipline_id, discipline.id
speciality.save!


I'll refactor so every line tells the reader something about the program.

{-# LANGUAGE ScopedTypeVariables #-}
import Text.Printf
import Control.Monad
import Data.List.Split (splitPlaces)
import Safe (headNote)

main :: IO ()
main = interact                                                                -- no side effects
  $ (\f -> unlines . zipWith f [1..] . subList [2,4..] . lines)                -- embarassingly parallel
  $ (\solve (i :: Int) -> printf "Case #%d: %d" i . solve . map read . words)  -- mere math
  $ (\cost (s :: [Int]) -> minimum [cost l s | l <- [1 .. maximum s]])         -- brute optimization
  $ \l -> (+l) . sum . map ((`div` l) . subtract 1)

-- This gets a name because we ought to be importing it from a library.
subList :: [Int] -> [a] -> [a]
subList is = map (headNote "subList: index list not strictly ascending")
  . drop 1 . splitPlaces (zipWith (-) is $ 0:is)


FontObject

Since all your data members and methods are public, consider making it a struct instead of a class. Makes no difference to a compiler, but makes your intention clearer.
Consider using a unique_ptr instead of shared_ptr, since only one instance of GameObject owns the object.

FontsLoader

I'm sure they are many people who will explain why you shouldn't use the Singleton pattern. Ultimately, it comes down to whether you (and people you're coding with) are okay with. I've seen various large projects (~100K-1M lines) use the Singleton pattern, so I'm not going to tell you whether you should or shouldn't use it.
Use something like an std::unordered_map<FontsID, FontsObject>. That way, you won't have to cast it into an integer and access a vector.
On a side note, for vector access, use size_t.
Consider passing the sf::Font object as a raw pointer or a const reference. Remember, non-owning raw pointers is FINE, even recommended. Whatever calls the getFont method is not concerned with ownership of the object, just the object itself. Don't pass smart pointers around unless you want the calling code to have ownership of the object.


Volatile

Application.Volatile

I'm walking down the code as I'm writing this, so I haven't really seen the code below that line. The Application.Volatile method call tells Excel to recalculate your function every time any cell anywhere on the worksheet is modified. The default behavior is to recalculate only when the input variables change.
That method call on the Application object tells me that you've perhaps tested it without at first, and concluded that it was required in order for the function to properly recalculate.
A comment explaining why Application.Volatile is needed here, might be judicious.

Naming notes...
I like the consistency you have with your naming style, it's nice to see. The style matches that of native Excel worksheet functions, like SUM:

SUMIF(range, criteria, [sum_range])

I think it's fine to expose that style to outside code (and/or Excel), but I don't see a reason for the internals to use any snake_case, convention is to use camelCase for locals (and usually, parameters too), and PascalCase for member names (procedures, functions, properties, ..).

Dim i(0 To 1) As Long, j As Long, lookup_vector_values As Variant

Hmm. 3 variables declared in the same instruction, of 3 different types and meanings. For readability's and maintainability's sake, a few points:

Declare arrays on their own line. As Long, j As Long is pretty much hiding the identifier.
If you're going to declare more than one variable in one instruction, do so but with variables of the same type.
Use meaningful identifier names: i is usually used in a For..Next loop, to count iterations. An array of Int32's isn't exactly trivially that. We don't know anything about that variable until we stumble on a usage of it, which hopefully isn't too far. The first usage is actually 2 lines below, which isn't too bad, but... let's face it, we all hate it when it's down to i and l and 1.
j is also typically used for iterating Foo..Next loops, usually when i is already taken. I'll have to scroll further down to see where the loop is. An interesting loop, I'll get back to it.
Declare variables as close as possible to their first usage.

I'd get rid of i, and rename lookup_vector to lookup_range or, as VLOOKUP has it, table_array (although, ...)
I said I was going to get back to the loop:

For i(j) = 1 To UBound(lookup_vector_values, j + 1)

Why make that operation a side-effect of iterating the loop? It's non-standard; people usually use a variable in a For loop, not an expression - one must read it carefully. If it can't be refactored, then it should be commented.


Return list of common email ids from a list of lists

Using a HashSet is fine, but you don't need to keep the count of occurrence of each email, you can just keep in the HashSet those that appear in all list, and remove all other emails.

//Need to check if email1 is empty before this step!
HashSet<String> set = new HashSet();
set.addAll(email1.get(0));
for(int i = 1; i < email1.size(); i++){
    HashSet<String> tmp = new HashSet();
    for(String email : email1.get(i)){
        if(set.contains(email)){//If set contains this email, keep it!
           tmp.add(email);
        }
    }
    set = tmp;//Important step
}
//All emails will be in the set
System.out.println(set);


If this unit of code is a router, then it should remain a router. Have the controller handle its dependencies. You could have multiple controllers, each with its own dependencies. You wouldn't want a single router code become a monster just to keep up with the controllers.

class Router{

  private $request;
  private $cleanUri;

  private $controller;
  private $action;
  private $params = [];

  public function __construct(Request $request){
      $this->request  = $request;
      $this->cleanUri = $this->sanitizeUri($request->getUri())
      $this->parseUri();
      $this->load();
  }

  // Extract sanitize. You might want to add more than just this and the constructor
  // is a bad place to put it.
  private function sanitizeUri($uri){
    return preg_replace(['#/+#', '(\.\./)'], '/', trim($uri, '/'));
  }

  private function parseUri(){
      $parts            = explode('/', $this->cleanUri);
      $this->controller = ($this->cleanUri !== '' ? ucfirst(array_shift($parts))  : 'Index') . 'Controller';
      $this->action     = array_shift($parts);
      $this->params     = !empty($parts) ? $parts : null;
  }

  // Extract the 404
  private function send404(){
    if (class_exists('_404Controller')) {
      $controller = new _404Controller();
      $controller->index();
    } else {
      throw new Exception('404 controller not found. Page doesn\'t exist for: ' . $this->request->getUri());
    }
  }

  private function load(){

    // If action is empty, use index
    if (empty($this->action)) $this->action = 'index';

    // If either controller or method doesn't exist, 404
    if(!(class_exists($this->controller)  && method_exists($this->controller, $this->action)))
      $this->send404();

    // else execute
    $controller->$action($this->params);

  }
}

Then the controller could have:

class MyController extends Controller{

  public function __construct(){
    $this->load(array(
      'database',
      'cats',
      'unicorns'
    ));
  }

  public function index(){
    $this->database->getSomething();
  }
}


Symlinking git-managed dotfiles into a home directory

Some guidelines to follow:

If possible, as it is in your case, work with absolute path.
You'll have at the beginning to do more or less something like:

dir = '/home/rik/'
files = [os.path.join(dir,file) for file in os.listdir(dir)]

But everything should be easier and straighforward later on.
You need to move the default behaviour - files = os.listdir('.') - one level up.
I can see one symptom and one reason for that:

You've wrote two times the exact same code.
The two different functions with that code should ignore what's your default directory, since they operate on list of files.

So, if the user does not provide his own custom list, you need to generate the list of files in . and pass it to both your functions. This also means that the functions should not have a default argument value.
If you can, use argparse instead of optparse.
I'm not sure from which version optparse was deprecated, but the main point is that if you have argpare in your standard library use that. You have only a couple of arguments so switching shouldn't take long.
Be consistent with your variable names.

def make_private(files=[]):
    # [...]
    for filename in files:
        # [...]

def linkify(files=[]):
    # [...]
    for source in files:
        # [...]

Why one time files is a list of filenames and another a list of sources?
If you strongly believe that one function works on filenames and the other on sources maybe you need to change the argument name, otherwise being consistent will help the readability of your code.
As Winston Ewert already told you, you should use capital letter for your constants names. Quoting from PEP8:

  Constants are usually defined on a module level and written in all
  capital letters with underscores separating words.  Examples include
  MAX_OVERFLOW and TOTAL.

Additional notes

Don't do this:

def function(lst=[]):
    # ...

Do this instead:

def function(lst=None):
    if lst is None:
        lst = []
    # ...

The reason for that is well explained here (or google it, because it's a very well known problem in which everyone stumbles sooner or later).

I'd say that by doing this you'll also remove the useless else, but as I explained it above you should remove the whole check and move it one level up against the user arguments.


Iterating through a collection of objects

You can do the same with just a foreach loop instead of reading the enumerator.

You can use the String.Compare method to do a case insensetive compare instead of creating a lowercase version of each string that you compare.

Improved improved code:

public List<string> getParentPegs(IGrouping<string, SupplyDemand> data) {

  List<string> result = new List<string>();

  foreach (SupplyDemand obj in data) {
    if (String.Compare(obj.Source, "make", true) == 0) {
      result.Add(obj.Peg);
    }
  }

  return result;
}

Note: In your first code you are getting the property Part, but in the second you are getting the property Peg instead.


Best way to pass parameters to Factory class?

How about some kind of intermediary blackboard that the client code constructs before calling the factory, and each concrete Impl can poll to construct itself?

// client code:

Blackboard blackboard = new Blackboard();
blackboard.pushCollectionB(collectionB);
blackboard.pushCollectionC(collectionC);
blackboard.pushFoo(foo);

IImpl myInstance = Factory.GetInstance(b);

///////////////////////////

// in Factory.GetInstance():

return new Impl3(blackboard);

////////////////////////////

// in Impl3:

Impl3(Blackboard b) { process(b.getCollectionC()); }

I've hidden the switch statement in the client code, but you could move that into the blackboard as well.

What data each concrete Impl needs is now hidden from both the Factory and the client code. However if you need more data in your Blackboard for Impl(x+1) you will need to update every place in your code that creates a Blackboard.

Depending on application, over-constructing the Blackboard like this may be expensive for you. You could construct a cached version at startup, or you could make the Blackboard an interface and have your client code derive from it.


It does indeed make a difference whether you use bool[] or int[] - an int uses four times as much memory and hence the array requires four times as many cache line transfers as bool does, and it will exceed the CPU's level-1 cache capacity - usually around 32 KiByte - for smaller values of n than a boolean array. And, as Dave said, testing the truthiness of a bool cell looks nicer in languages where integers aren't truthy and thus need to be compared to 0, and it reflects the program logic better.

If you invert the logic of your sieve from 'is prime' to 'is composite' then you can skip the initialisation of the array to all true (or 1) because the array will already have been initialised to the bit pattern 0, and semantically it would be more accurate anyway. Besides, I don't think that the old Greek ever said anything about marking all numbers as 'prime' before the start of the sieving - that must have been invented by tutors in the modern age.

Also, the Sieve of Eratosthenes has no need for multiplying indices - it strides additively, by adding the current prime to the current position during each step:

for (int i = 2, sqrt_n = (int)Math.sqrt(n); i <= sqrt_n; ++i)
    if (!is_composite[i])
        for (int j = i * i; j <= n; j += i)
            is_composite[j] = true;

I've also adjusted the starting point for the crossing-off to the square of the current prime, since all smaller multiples will already have been crossed off during the cycles for smaller primes.

The outer loop still contains a small inefficiency: there is only one even prime, yet the loop tests all even numbers up to sqrt(n) for compositeness. Quite a few performance reserves can be unlocked by removing the number 2 from the picture entirely and sieving only the odd numbers. The biggest gain comes from removing half of all 'hops' (crossings-off) in the inner loop and from the halved memory pressure.

Last but not least, the performance will drop significantly when the sieve array gets appreciably bigger than the L1 cache size of the CPU (typically 32 KiByte), and it will drop even further when the L2 cache size is exceeded. If you need decent performance in ranges beyond the L1 cache size then you might want to consider segmented sieving, i.e. working the sieve range in cache-sized blocks.

This is quite simple to implement, and definitely simpler than windowed sieving; you can find an example in my answer to Find prime positioned prime number. There you can also see that odds-only sieving is just as simple as plain sieving; it just requires a bit of care when dealing with indexes (i.e. clarity whether a given value is supposed to be a number or a bit index).

Many coding challenges that deal with primes require the sieving of millions of numbers instead of small handfuls, and so an investment in studying suitable 'prime technology' can pay off handsomely. Moreover, this study can tell you lot about the efficiency of basic mechanisms in your language - be it bool[] vs BitSet (bool[] wins hands-down in Java, C# and C++, if you have an eye on cache sizes), or the performance cost of syntactic sugar.


Finding max amount of integers in list that add up to target

Some suggestions:

foo[:bar] is syntactic sugar for foo[0:bar].

The idiomatic way to ensure that a file is closed when the code is finished with it is to use a context manager:
with open(…) as fName:
    [any code which reads from fName]

data is a literally meaningless name: anything stored in a variable is data. In this case you might want to use a name like user_counts or users.

The return value of open is not a file name, but rather a file descriptor.

Unless this is a one-off piece of code I would wrap the different bits (the input-handling code (reading the file), the central algorithm and the output code) into functions.

By returning the result rather than printing it this code could be reused by other code.

Since the code naturally only takes a single input stream, I would read the values from standard input (per the Unix philosophy). That way the code can be called with any file trivially, as in ./max_sum_inputs.py < ../root_files/26_7791633.txt

A linter like flake8 or pylint will tell you about other non-idiomatic code, such as how variable names should all be snake_case.


The details of TrieNode don't need to be visible outside of Trie, so I recommend making it a private (or protected) member type Trie::Node.

We don't need to write a constructor, if we initialise the root node with the value we want:
std::unique_ptr<TrieNode> root = std::make_unique<TrieNode>();

Some coding styles ask us to indicate when auto resolves to a pointer type:
    auto* node = root.get();

Prefer passing a std::string_view than a const std::string& - it saves having to construct a string object in many circumstances (including the const char* string literals used in this program).  Either way, we're missing the required header file, and only succeed by dumb luck.

We're doing a lookup twice here:

        if (node->children.find(ch) == node->children.end())
        {
            node->children[ch] = std::make_unique<TrieNode>();
        }
        node = node->children[ch].get();

If we keep the result of find(), then we can use that iterator for that last line, instead of finding it all over again with [].  Perhaps a good idea to use insert() for adding the new node; that gives you back an iterator:
    auto* node = root.get();
    for (auto const ch: word) {
        auto& children = node->children;
        auto it = children.find(ch);
        if (it == children.end()) {
            it = children.emplace(ch, std::make_unique<TrieNode>()).first;
        }
        node = it->second.get();
    }

Similarly, in search():
bool search(const std::string_view word) const
{
    auto* node = root.get();
    for (auto const ch: word) {
        auto& children = node->children;
        auto it = children.find(ch);
        if (it == children.end()) {
            return false;
        }
        node = it->second.get();
    }
    return node->isLeaf;
}

This call:

trie.startsWith("app")

This fails to compile, as there's no such member.  It looks like part of the code is missing, which is certainly a sign that testing could be improved.

Don't flush streams unnecessarily using std::endl when a plain newline will do.

Improved program
#include <iostream>
#include <map>
#include <memory>
#include <string_view>

class Trie
{
    struct Node
    {
        bool isLeaf = false;
        std::map<char, std::unique_ptr<Node>> children = {};
    };

    std::unique_ptr<Node> root = std::make_unique<Node>();

public:
    void insert(const std::string_view word)
    {
        auto* node = root.get();
        for (auto const ch: word) {
            auto& children = node->children;
            auto it = children.find(ch);
            if (it == children.end()) {
                it = children.emplace(ch, std::make_unique<Node>()).first;
            }
            node = it->second.get();
        }
        node->isLeaf = true;
    }

    bool search(const std::string_view word) const
    {
        auto* node = root.get();
        for (auto const ch: word) {
            auto& children = node->children;
            auto it = children.find(ch);
            if (it == children.end()) {
                return false;
            }
            node = it->second.get();
        }
        return node->isLeaf;
    }
};

int main()
{
    Trie trie;
    trie.insert("application");

    for (auto const s: {"app", "apple", "application"}) {
        std::cout << s << (trie.search(s) ? " is present\n" : " not found\n");
    }
}