Remapping of arrays on structs (code style)

Whenever I see (e.g.):
int foo0, foo1, foo2, foo3, ..., fooN;

I think that can be replaced more cleanly with an array. So, I'd rather have:
int foo[N];

Thus, I'd change:
int32_t micInside0[SIGNAL_LENGTH];

(et. al.) into:
int32_t micInside[4][SIGNAL_LENGTH];

That sort of thing occurs in several more places for different variables as well.

A good style rule is to use shorter names for argument names and stack/automatic variables [that have shorter scope/duration] and longer names for globals.
For example: FilterSample_t filterSamples[SIGNAL_LENGTH] is a bit redundant and could be shortened to (e.g.) FilterSample_t fslist[SIGNAL_LENGTH]
Likewise, FilterSample_t *filterSample = &filterSamples[i]; is a bit long and could be shortened to: FilterSample_t *fscur = &fslist[i];
To me, the longer names are "too much eye candy".
Also, with the shorter names, the lines will be shorter, so they're less likely to need to be wrapped to multiple lines [with the indenting].

If you add an additional struct, you can reorganize/simplify micInside* and micAux*.

As to the indenting of the second [wrapped] line that you didn't like, personally, I do that 10 times / day. I've found that to be very clean. But, I've been doing that for 20+ years, so I'm used to it.

Note that you did [for all "X", where "X" is one of 0,1,2,3]:
filterSample->micInsideXa = inputSignals->micInside0[i];

But, I think that was a typo and you meant to do:
filterSample->micInsideXa = inputSignals->micInsideX[i];

I realize that school classes teach the use of i, j, etc. But, I've found that more descriptive names can make the code clearer.

Anyway, I've refactored your code incorporating these ideas.
Caveat: I had some difficulty with the remapping to arrays and I had to guess a bit about some of the relationships. (e.g.) CHANMAX for "max # of channels" was a guess, based on my experience with video and audio processing and seeing "mic" (as in "microphone") and "aux" (as in "auxiliary audio").
And I may have messed this up by transposing the array indexes, but it should give you an idea of what I'm driving at:
#include <stdint.h>

#define SIGNAL_LENGTH 1024

#define CHANMAX     4

/**
* Multiple linear input signals as read by a previous input stage
*/
typedef struct {
    // Mics inside
    int32_t micInside[CHANMAX][SIGNAL_LENGTH];

    // Mics aux
    int32_t micAux[CHANMAX][SIGNAL_LENGTH];
} InputSignals_t;

typedef struct {
    int32_t mic_a;
    int32_t mic_b;
    int32_t mic_select;
} micfilter_t;

/**
* Single input struct to be passed to the following filtering stage
*/
typedef struct {
    micfilter_t filt_micinside[CHANMAX];
} FilterSample_t;

/**
* Map the linear input signals to interleved multi-channel filter input signals.
*/
void
mapMicFilters(InputSignals_t *inputSignals, FilterSample_t fslist[SIGNAL_LENGTH])
{
    for (int isamp = 0; isamp < SIGNAL_LENGTH; isamp++) {
        FilterSample_t *fscur = &fslist[isamp];
        InputSignals_t *inpbase = &inputSignals[isamp];

        // I am rather unhappy with the look of the following
        // code section where the mapping is done.

        for (int ichan = 0;  ichan < CHANMAX;  ++ichan) {
            micfilter_t *fchan = &fscur->filt_micinside[ichan];
            int32_t *inpcur = inpbase->micInside[ichan];
            fchan->mic_a = inpcur[isamp];
            fchan->mic_b = 0;
            fchan->mic_select = 0;
        }
    }
}


Extract list of selected contractors by matching serialized array in Rails

If your database supports array types natively I would use that  feature, I know that Postgres does. I would also call the field contractor_ids or even selected_contractor_ids then use a method called contractors or selected_contractors to return the actual objects.

I would change this:

@contractors = Contractor.where({ verified: true, validated: true })
                         .where('membership_type != ?', Contractor.membership_types["no_membership"])

to a scope or scopes on the Contractor class. You can also code the second where clause as where.not(membership_type: Contractor.membership_types["no_membership"])

And I would change this:

@selected_contractors = @company.contractors.map { |c| Contractor.find(c.to_i) }

to be a method on the Company class. I would also write it as:

@selected_contractors = Contractor.find(@company.contractors)

this would issue a single query instead of n queries, additionally the to_i is not usually necessary.


Selecting one MySQL date with month reduced by one

If there is no workaround then, bad practice as it may be, what you have is functional. I found this post on SO that may allow you to convert the column's date data type to the 0-11 format. Hope this helps.

EDIT

Removed bad idea. If you really wish to see it just look at the edit history, but it is not a good idea. I'm going back to my original answer.


How to make string.Format template more readable?

Like @jesse said you can have a custom method, maybe pass a user object to that method.
Something like this:

class User
{
    public int AutoLoginRequestTemplate { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string Val1 { get; set; }
    public string Val2 { get; set; }
    public string requestSub { get; set; }
    public string Language { get; set; }
    public int minValue { get; set; }
    public int maxValue { get; set; }
    public int agentDiffType { get; set; }

    /// <summary>
    /// Formats the user info.
    /// </summary>
    /// <param name="user">The user object.</param>
    /// <returns>A formated string</returns>
    public string FormatUserInfo(User user)
    {

        return String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}",
                                user.AutoLoginRequestTemplate,
                                user.username,
                                user.password,
                                user.Val1,
                                user.Val2,
                                user.requestSub,
                                user.Language,
                                user.minValue,
                                user.maxValue,
                                user.agentDiffType);
    }
}

Your question changed, now I see that you are trying to create an xml string.

For the sake of readabilty, I wouldnt use string.Format(), instead I would just do simple concatenation:

"<Password>"+passowrd+"</Password>"

Now I am not sure about performance, but here we are talking about readability (you probably can spend your time being productive at something else rather than trying to decide which type of concatenation is more efficient/readable)

Now in terms of best practice, I wouldn't create xml manually (just like I wouldnt try to create a JSON or CSV parser) instead I would use .NET framework to do this, which would certainly make it more readble, something like this:

        XElement xml = new XElement("RemoteXMLData",
            new XElement("Username",
                new XAttribute("agent_diff_type", agentDiffType),
                new XAttribute("agentDiffType", agentDiffType),
                new XAttribute("usertype", userType),
                new XAttribute("ticket_language", Language),
                new XAttribute("min_slip_stake", minValue),
                new XAttribute("max_stake", maxValue),
                new XAttribute("location", location),
                username),
            new XElement("Password",
                password),
            new XElement("Reseller",
                reseller),
            new XElement("Function",
                function),
            new XElement("AppKey",
                appKey),
            new XElement("Sub",
                sub)
        );


It's not necessary to special-case the head of the list if you think about it in a different way.  In particular, each entry in your hashtable is a pointer to an Nlist structure, so if you take the address of the hashtable entry, you can treat it just like any other node.  Specifically, you can use this:

void undef(char *name)
{
    struct Nlist **tmp = &hashtab[hash(name)];
    struct Nlist *old;

    /* find our matching node */
    for ( ; *tmp && strcmp(name, (*tmp)->name); tmp=&((*tmp)->next));

    /* if we have found it, delete and adjust pointer */
    if (*tmp != NULL) {
        old = *tmp;
        free(old->name);
        free(old->defn);
        *tmp = old->next;
        free(old);
    }
}

Also note that defn was not being deleted in your original code, resulting in a memory leak.


You make this harder then it needs to be.

Since IDbSet implements the IEnumerable<TEntity> interface

 public interface IDbSet<TEntity>
 : IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable

you can simply use the Contains extension optionally with your own comparer that can implement such things as Trim etc.


Analysis describing the combination of cards

The order is not the problem here but rather the fact that you have multiple virtual calls in your constructor. This is really bad because in your derived class, when they are being instantiated, your constructor will first call the base implementation of the virtual functions your base class constructor, which might result  in unexpected behaviour form t he virtual functions.

Also you shouldn't be using fields, use properties instead.

Here is how you can avoid all of your current issues :

public abstract class TichuTrick
{
    private readonly List<CardData> _cards;
    public List<CardData> OrderedCards => OrderCards(_cards, WildcardsCount);

    public int CardCount { get; }

    public int TrickValue => CalculateTrickValue();
    public int HighestCardValue => CalculateHighestCardValue();
    public int WildcardsCount { get; }

    internal TichuTrick(List<CardData> cards, int cardCount, int wildcardsCount)
    {
        if (wildcardsCount > 1)
        {
            throw new System.ArgumentException("More than one wildcards support, is not yet implemented", nameof(wildcardsCount));
        }
        CardCount = cardCount;
        _cards = cards;
        WildcardsCount = wildcardsCount;
    }

    protected virtual List<CardData> OrderCards(List<CardData> cards, int WildcardCount)
    {
        return cards.OrderBy(x => x.NumericalValue).ToList().CopyList();
    }

    protected virtual int CalculateTrickValue()
    {
        return CalculateHighestCardValue();
    }

    protected virtual int CalculateHighestCardValue()
    {
        return OrderedCards.Last().NumericalValue;
    }
}

I also don't think this parameter should be a parameter at all cardCount you can access the card count from the array, but since I'm not 100% sure that this is correct I left it there.


Lexicographically largest string from allowed swaps

Your code is quite good for a beginning, but there's still much room for improvement. Your code main flaw is that it is difficult to read. There are also some performance issues, but they are a lot easier to correct.
N.B: I'll stay close to your algorithm, although you could probably find a better one in a graph library (see for instance https://en.wikipedia.org/wiki/Connected_component_(graph_theory)#algorithms)
Performance
You must pick your types more carefully. Don't choose a type that allocates memory when you can use one that doesn't. For instance, don't represent a pair of indices by a std::vector: a pair will always have two elements, there is no need to ever grow it. So choose a std::pair<int, int> instead: it is lighter, quicker, and reflects your intent more clearly. In the same way, don't use std::string to represent 1 character: your stringpool can as well be of type std::vector<std::string>.
You must also be more careful while passing objects around. Don't pass large objects by value unless you need both to copy and modify them. For instance, the signature: std::string swapLexOrder(std::string str, std::vector<std::vector<int>> pairs) is only partially correct. You will indeed modify str, and you want the user to keep his original string untouched, so passing by value is a good call. But pairs is read-only in your code, so pass it by const reference.
Expressiveness
Your code is one big function containing a lot of nested loops. As a result,it's very hard to understand, let alone optimize. There is two ways to fix it: the first is to better comment on your algorithm (for instance, a minimum would be: first, we merge all pairs of indices that are connected together; then we extract the corresponding characters from the input string, sort them in decreasing order and put them back); the second, is to make your code express your intent clearly.
The most important rule, which also is one of the hardest to obey, is to choose meaningful names. newset doesn't mean much, neither does p. pairpool should not contain set of more than two elements.
Another way to write more expressive code is to avoid "raw loops". Use named algorithms instead. For instance, I rewrote the first part of your algorithm as a combination of a partition discriminating sets containing one element of the considered pair and an accumulation which merges them:
std::string swapLexOrder(std::string str, const std::vector<std::pair<int, int>>& pairs)
{
    if(pairs.size() == 0) return str;
    std::vector<std::set<int>> index_permutations; //pairpool : contains sets of interchangeable indices

    for(auto pair : pairs)
    {
        // [matches, end) <- sets containing either one of the pair's elements
        auto matches = std::partition(index_permutations.begin(), index_permutations.end(),
                                      [&pair](const auto& permutation_set) {
            return std::none_of(permutation_set.begin(), permutation_set.end(), [&pair](auto index) {
                return index == pair.first || index == pair.second;
            });
        });

        if (matches == index_permutations.end()) index_permutations.push_back({pair.first, pair.second});
        else { // merge matches
            *matches = std::accumulate(matches, index_permutations.end(),
                                       std::set<int>{pair.first, pair.second},
                                       [](auto&& init, auto&& permutation) {
                init.insert(permutation.begin(), permutation.end());
                return init;
            });
            index_permutations.erase(std::next(matches), index_permutations.end());
        }
    }
// ...

Here's a link to the partially rewritten code if you want to experiment with it: https://wandbox.org/permlink/6Wij6Y4NuooMlW6C


Choose random instants in a day with a low memory footprint

1. Review

There's a lot of repetition, especially of the number 86400. This can be avoided by defining a global constant, for example:

_DAY_SECONDS = 24 * 60 * 60  # Seconds in a day.

or alternatively:

import datetime
_DAY_SECONDS = datetime.timedelta(1).total_seconds()

and then in mainloop:

day, partday = divmod(int(time.time()), _DAY_SECONDS)
seconds_left = _DAY_SECONDS - partday
if day != planday:
    planday = day
    events_planned = round(getPref('events_per_day') * seconds_left
                           / _DAY_SECONDS)

(This avoids the need for the function planifie.)
If time.time happens to return a number less than 86,400 (perhaps because the computer's clock has not been set correctly) then events_planned will not get set on the first loop. It's better to ensure that the initial value of planday can never equal day, for example by initializing planday to None.

2. The problem

The chance of emitting an event on each loop is events_planned / seconds_left. This would be correct if there each loop iteration took exactly one second. But that's not the case — each loop iteration takes more than a second. That's because (i) some time is taken by do_event (on the iterations where there is an event); (ii) sleep(1) generally takes a little more than 1 second because of the granularity of operating system scheduler, and (iii) as it says in the specification of the sleep function,

  The suspension time may be longer than requested due to the scheduling of other activity by the system.

So each loop takes more than a second, but emits events based on the probability of an event occurring in a period of exactly one second. So there is a small but systematic deficit in the number of emitted events, leading to a rush to catch up at the end.

To have a fair schedule, you need to measure the time actually taken by each iteration of the loop, and adjust the probability accordingly, something like this:

planday = None
prev = time.time()
while not is_closed:
    now = time.time()
    time_passed = now - prev
    day, partday = divmod(now, _DAY_SECONDS)
    seconds_left = _DAY_SECONDS - partday
    if day != planday:
        planday = day
        events_planned = round(getPref('events_per_day') * seconds_left
                               / _DAY_SECONDS)
    if random.random() < events_planned * time_passed / seconds_left:
        events_planned -= 1
        do_event()
    time.sleep(1)

(Note that this doesn't actually ensure that the exact number of events occur in each day — an unlucky scheduling of the last sleep of the day could cause some events to be dropped. But the code in the post has the same problem, and I'm guessing that you don't mind if the number of events per day is short by one or two.)

3. Worked example

You expressed some skepticism about this in the comments, so let's take a simple worked example. Suppose we start out with \$20\$ seconds remaining and \$10\$ events remaining. Then there should be on average one event every 2 seconds. But let's also suppose that the sleep(1) actually takes 2 seconds.

On the first iteration we emit an event with probability \$1\over 2\$, and so after 2 seconds we have emitted on average \$1\over 2\$ an event, so we are 0.5 events behind schedule.

On the second iteration we emit an event with probability \$1\over2\$ if we emitted an event in the first iteration, or \$5\over9\$ if we didn't. So after two iterations we have emitted on average $$ {1\over2}\left(1 + {1\over2}\right) + {1\over2}{5\over9} = {37 \over 36} $$ events, and so we are on average almost 1 event behind schedule.

You can see that in this example, the deficit goes up to start with because although the probability goes up, it doesn't go up fast enough to compensate. Towards the end, the probability catches up, hence the rush to finish.

4. Alternative approach

If the number of events is substantially less than the number of seconds in a day, then most of the loop iterations will be pointless — no event happens and the program just goes to sleep again.

An alternative approach is to emit exactly one event in each loop, and then choose how long to sleep until the next event. If events are distributed uniformly at random, then the time to the next event is given by the exponential distribution and this can be sampled by calling random.expovariate.

(The same problem with over-sleeping will arise here, so you would have to compensate for it, for example by measuring the actual time taken by the loop iteration, subtracting the intended iteration time, and holding over any surplus and subtracting it from the time for the next iteration.)


Determining if one string occurs at the end of another

Const correct the pointers. The function is not changing anything in memory, no reason they shouldn't be const. Same with variables you declare in the function; Make them const

int strend(const char* s, const char* t)

Check for NULL in the input pointers.

Use library string functions wherever possible.
Instead of doing:

while(*s++) ;
s-=2;

call strlen(s); and then substract 1 as needed in your algo. Since you are iterating over the string anyway replacing this with a function call has the same efficiency and makes it more readable.

Add { around the while loop. It is future-proof.

Unit-test to confirm correctness.


Find greatest number in array that is a product of some two elements in the same array

Sort it
As @Peska suggested, sort the array first. But sort it descendand, or simply iterate in reverse order.
Overflow
The multiplication of integers can overflow. It would be wiser to approach the iterations from product, divide by one element and check if the division equals second element, but only if product modulo first element is zero.
Contains() checks too much
First of all.
a.Contains(temp) && temp > x

should be written as
temp > x && a.Contains(temp)

The Contains call is O(n), we want to avoid this as much as possible, as it is turning the entire algorithm to O(n^3). In sorted input, we can make some restrictions and which elements we search through. We can actually deploy a binary search, introducing another loop instead of call to Contains, but this loop will be O(log(n)). In the code I have a naive variant that is commented out and is still O(n), but still checks much less then full Contains scan.
// we will use this to skip duplicate elements in forward iterations
private static int NextDistinctElementIndex(int[] input, int i)
{
    int value = input[i];
    do
    {
        ++i;
    } while (i < input.Length && input[i] == value);
    return i;
}

public static int SlepicMaxPairProduct(int[] input)
{
    if (input.Length < 2)
    {
        // there's never product of two, if there are no two
        return -1;
    }

    Array.Sort(input);

    if (input[0] < 0)
    {
        throw new ArgumentException("Input cannot contain negative numbers.");
    }

    int result = -1;
    int imin = 0;

    if (input[0] == 0)
    {
        // if first element after sort is zero, the result will be at least zero
        result = 0;
        // and we will never have to search for zeroes
        imin = NextDistinctElementIndex(input, 0);
    }

    if (imin < input.Length - 1 && input[imin] == 1)
    {
        // if there is "1" in the input, the greatest element of input is the result
        // except if there is just one "1" and zero(es)
        return input[input.Length - 1];
    }

    // start examining the sorted input from greatest element
    // and assume the values to potentialy be the product we are looking for
    for (int pi = input.Length - 1; pi > imin; --pi)
    {
        int product = input[pi];

        // exclusive index of the greatest element that is reasonable to search for a "b" value
        int bmax = pi;

        // assume values before bmax are some "a", then look for "b"
        for (int ai = imin; ai < bmax; ++ai)
        {
            int a = input[ai];

            // if product is not divisible by a, we won't find any b
            if (product % a != 0)
            {
                continue;
            }

            int expectedB = product / a;

            /*
            // search for a "b" value in the reasonable range (bmin, ai)
            for (int bi = bmin; bi < ai; ++bi)
            {
                int b = input[bi];

                if (b == expectedB)
                {
                    return product;
                }

                if (b > expectedB)
                {
                    bmin = bi;
                    break;
                }
            }*/

            // let's turn the naive "for bi" loop into log(n)

            // searchfor a "b" value using bisection in the reasonable range (bmin, bmax)
            // and export new values of bmax to the outer loop
            // because if we will search for a greater "a" then the current one
            // we are inevitably only going to find a smaller "b"
            int bmin = ai;
            while (bmax > bmin)
            {
                // int bi = (bmin + bmax) / 2;
                // variant with no overflow of index (for very large arrays):
                int bi = (bmin / 2 + bmax / 2) + ((bmin % 2) & (bmax % 2));

                int b = input[bi];

                if (b == expectedB)
                {
                    return product;
                }

                if (b < expectedB)
                {
                    bmin = bi + 1;
                }
                else
                {
                    bmax = bi;
                }
            }
        }
    }

    return result;
}

In conclusion, we have limited the searched space to a great degree and turned the algorithm from O(n^3) to O((n^2) * log(n)).
|       Method |    N |               Mean |            Error |           StdDev |
|------------- |----- |-------------------:|-----------------:|-----------------:|
|    PeskaTest |   10 |           215.3 ns |          3.61 ns |          3.38 ns |
| MilliornTest |   10 |         4,868.0 ns |         88.16 ns |        134.64 ns |
|   SlepicTest |   10 |           264.6 ns |          3.57 ns |          3.34 ns |
|    PeskaTest |  100 |        56,954.4 ns |      1,131.18 ns |      1,548.37 ns |
| MilliornTest |  100 |     4,352,830.7 ns |     76,663.28 ns |     94,149.39 ns |
|   SlepicTest |  100 |        16,452.8 ns |         86.02 ns |         76.25 ns |
|    PeskaTest | 1000 |    27,821,365.8 ns |    349,019.38 ns |    309,396.59 ns |
| MilliornTest | 1000 | 4,193,838,300.0 ns | 43,784,319.26 ns | 40,955,879.40 ns |
|   SlepicTest | 1000 |        50,757.2 ns |        244.00 ns |        203.76 ns |

PS: Based on return value -1 meaning "not found" I assume the input cannot contain negative numbers, otherwise it cannot work like this (where I assume that if zero is present it is on index 0, ...)
PS2: It is not very nice that the implementation sorts the array for the caller. It may be wise to provide the method expecting the input already sorted and provide a wrapper that creates a sorted copy and passes it to this method that expects sorted input. It will be more expensive because of copying and allocating new array, but for big inputs, this should be neglegable (because it is O(n) which is neglegable compared to O(n^2*log(n)) while making it error safe, immutable for the caller, thus more transparent for him, and offering the method that expects sorted input makes it more flexible/efficient for callers that already sorted their input.
EDIT:
New bench results including @potato's solution (2nd snippet). Mine still seems faster although according to potato's big-O, his should be faster. Not sure what's going on yet...
|       Method |    N |               Mean |            Error |           StdDev |
|------------- |----- |-------------------:|-----------------:|-----------------:|
|    PeskaTest |   10 |           209.6 ns |          1.25 ns |          1.11 ns |
| MilliornTest |   10 |         5,168.6 ns |         58.73 ns |         54.93 ns |
|   SlepicTest |   10 |           256.8 ns |          1.12 ns |          0.99 ns |
|   PotatoTest |   10 |           539.0 ns |          1.25 ns |          1.04 ns |
|    PeskaTest |  100 |         3,567.1 ns |         45.20 ns |         37.75 ns |
| MilliornTest |  100 |     4,806,710.5 ns |     13,092.42 ns |     10,932.77 ns |
|   SlepicTest |  100 |         5,039.0 ns |         58.10 ns |         48.52 ns |
|   PotatoTest |  100 |         6,141.9 ns |        111.06 ns |         86.71 ns |
|    PeskaTest | 1000 |    26,678,273.6 ns |    502,308.33 ns |    419,450.21 ns |
| MilliornTest | 1000 | 4,798,816,196.0 ns | 29,527,973.10 ns | 39,418,995.96 ns |
|   SlepicTest | 1000 |        44,601.9 ns |        407.09 ns |        360.87 ns |
|   PotatoTest | 1000 |        84,168.8 ns |        207.99 ns |        173.69 ns |

|     Method |     N |        Mean |     Error |    StdDev |
|----------- |------ |------------:|----------:|----------:|
| SlepicTest |  1000 |    49.88 us |  0.123 us |  0.103 us |
| PotatoTest |  1000 |    86.66 us |  1.121 us |  0.994 us |
| SlepicTest |  2000 |   119.67 us |  0.628 us |  0.557 us |
| PotatoTest |  2000 |   193.52 us |  0.530 us |  0.470 us |
| SlepicTest |  4000 |   279.29 us |  4.180 us |  3.705 us |
| PotatoTest |  4000 |   409.23 us |  1.443 us |  1.127 us |
| SlepicTest |  8000 |   563.60 us |  1.117 us |  0.990 us |
| PotatoTest |  8000 |   859.76 us |  4.800 us |  4.490 us |
| SlepicTest | 16000 | 1,201.41 us | 12.686 us | 11.867 us |
| PotatoTest | 16000 | 1,659.58 us |  8.473 us |  7.511 us |

|     Method |      N |      Mean |     Error |    StdDev |
|----------- |------- |----------:|----------:|----------:|
| SlepicTest | 100000 |  8.657 ms | 0.0556 ms | 0.0464 ms |
| PotatoTest | 100000 | 10.628 ms | 0.0301 ms | 0.0266 ms |

|     Method |       N |     Mean |   Error |  StdDev |
|----------- |-------- |---------:|--------:|--------:|
| SlepicTest | 1000000 | 101.7 ms | 0.41 ms | 0.36 ms |
| PotatoTest | 1000000 | 119.1 ms | 0.30 ms | 0.25 ms |

|     Method |        N |    Mean |    Error |   StdDev |
|----------- |--------- |--------:|---------:|---------:|
| SlepicTest | 10000000 | 1.266 s | 0.0048 s | 0.0043 s |
| PotatoTest | 10000000 | 1.446 s | 0.0194 s | 0.0172 s |

Those were with random numbers r: 0 <= r < 1000.
Now 0 <= r < N:
|     Method |        N |           Mean |       Error |      StdDev |
|----------- |--------- |---------------:|------------:|------------:|
| SlepicTest |    10000 |       726.4 us |     2.90 us |     2.57 us |
| PotatoTest |    10000 |     1,055.5 us |     4.55 us |     3.80 us |
| SlepicTest |   100000 |     9,056.1 us |    33.79 us |    31.61 us |
| PotatoTest |   100000 |    11,992.9 us |    58.15 us |    48.55 us |
| SlepicTest |  1000000 |   107,084.9 us |   473.48 us |   419.73 us |
| PotatoTest |  1000000 |   139,090.3 us |   376.83 us |   352.48 us |
| SlepicTest | 10000000 | 1,306,931.0 us | 2,585.99 us | 2,018.97 us |
| PotatoTest | 10000000 | 1,648,109.2 us | 7,627.77 us | 7,135.02 us |


Flip

Use better variable names. i and j are harder to read than something like front and back.
It's preferable to define the temp value inside the loop and save a line of code.
The method should be private.
Depending on what the interviewer wants, it's much nicer to make a new array than to destructively modify the existing one. I'll assume you asked and they specified to modify the existing array. That being the case, you don't need to return the modified array.

Pancake Sort

You're not doing a pancake sort. It's nonsensical for you to describe a problem and then ask us to review code that breaks your own stated invariants to solve the problem.
-1000 is arbitrary. Use Integer.MIN_VALUE and your code will work for all negative numbers.
Don't use abbreviations or shorten variable names. The extra letters don't cost anything. max and maxPos are not sufficiently descriptive. Don't use c as an array index. Either use j or a descriptive name.
In the comments, you observe that pancake sort is inefficient. Yes, it is. The point was to pick a sort that most people haven't thought about so everybody starts on an even playing field for the interview question. The inefficiency is tied to the algorithmic limitation of only having flip() available. There are no significant performance gains to be had unless you break that limitation, at which point you're no longer doing a pancake sort.

Using an actual pancake sort and my other suggestions, your code might look something like:

class Solution {

    // return an int for convenient testing
    private static int[] pancakeSort(final int[] array) {
        boolean sorted = false;
        while (!sorted) {
            sorted = true;
            for (int i = 0; i < (array.length - 1); i++) {
                if (array[i] > array[i + 1]) {
                    flip(array, i + 1);
                    flip(array, i + 2);
                    flip(array, i + 1);
                    sorted = false;
                    break;
                }
            }
        }
        return array;
    }

    private static void flip(final int[] array, final int elementsToFlip) {
        for (int front = 0, back = elementsToFlip - 1; front < back; front++, back--) {
            final int temp = array[front];
            array[front] = array[back];
            array[back] = temp;
        }
    }

    public static void main(final String[] args) {
        System.out.println(Arrays.toString(pancakeSort(new int[] { 1 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 1, 2 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 2, 1 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 1, 2, 3 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 2, 1, 3 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 3, 1, 2 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 3, 2, 1 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 3, 2, 1, 8, 4, 6, 5, 10, 7, 9 })));
    }
}


Refactoring a function with different signature

Simply use one method for all type of Exceptions.

Make it public static and move into a utility class.

public static StringBuilder getMessageFromException(Exception e){...}

Why do you need overloaded methods for different type of Exceptions?

User defined Exceptions are also subtype of Exception itself.

--EDIT--

create an interface for all your custom exceptions having  getFaultInfo() method.

interface MyFaultWS {} // marker interface
class FaultWS implements MyFaultWS {} // do it for both the packages

interface FaultInfoException {FaultWS getFaultInfo();}

// do it for both the packages
class FaultWS_Exception extends Exception implements FaultInfoException {

    @Override
    public FaultWS getFaultInfo() {
        return ...; // return your package specific exception
    }
}

Finally use

public static StringBuilder getMessageFromException(FaultInfoException e){...}


Similar manipulations on several numpy arrays

You can get the behavior you want using getattr and setattr, this should do the trick for your first example:

for attr in ('v0', 'v1', 'nl', 'nh', 'ul', 'uh', 'V1'):
    setattr(ResultSimulation, attr,
            getattr(ResultSimulation, attr)[::-1].copy)

It should be obvious how to modify the others to fit the same pattern.


Sort array of hashes with nil values last

You can create temporary sorting columns:

def sort records, *attrs
  records.sort_by do |h|
    h.values_at(*attrs).map do |v|
      v.nil? ? [2] : [1, v]
    end
  end
end

Here I added columns with values 1 or 2 to the left for higher priority -- could add to the right or even in between for more complex sorting.


Number of Chocolates to Gluttonize in Clojure

General Questions

Yes. Your tests are fine.
I found the code hard to follow without the requirements. To some degree, that's to be expected. Even once I read the requirements, there were things that I found hard to follow. More on that later.

How idiomatic is my code?

Never use camel case for your clojure-defined symbols.
You should always use lower-cased, hyphenated names in Clojure.
Your formatting was fine, except the let statement. It should be formatted like so:

(let [my-thing :a
      other-thing :b]
  (code-that-does-stuff ...))

The clojure style guide should tell you everything you need to know about styling your code.

What is a good way to communicate what a function does?

This is a complex question. My first piece of advice is to accurately name the function. number-of-freebies implies a number, but you are returning a vector. So a more appropriate name might be division-tuple or, better, quotient-remainder-tuple.

Regarding return types, the options you have, in order of increasing ceremony, are:

Return a tuple.
Return a map whose keys denote the return values.
Define a type or record.

For this example, I think a tuple is fine. If I thought the return value might need to expand in the future, I'd consider using a map. I generally use records and types when:

I'm designing a large(er) system (i.e. doing design work as opposed to implementing functions)
I want to reify a complex type
I want type dispatch

So, for something like this, I'd consider types to be a little overkill. Your tastes may vary.

How do I refactor total-chocolates-consumed to be less complex?

I implemented a solution in preparing your feedback, and the most straightforward method I could come up with on the fly was indeed recursive. Though, I will say this tends to be the kind of problem that you realize can be solved with map/reduce after a night or two of sleep.

There are two things you can do to make total-chocolates-consumed less complex:

Use destructuring:

(let [[freebies startRemainder] (number-of-freebies purchasedChocolates wrappersPerFreebie)]
  ...)

Use more let statements. Specifically inside the loop-recur.

I have a version of total-chocolates-consumed that does those things if you want to see it. I thought you might like to take a stab at it before you see what I did.

Other Notes

When I moved from Java to Clojure, I tended to like very small functions (e.g. number-to-purchase or int-division).
Over time, I've found it's a) more idiomatic and b) easier to read if you start with a rather large function and break it up as needed to increase understanding.
My reasoning for this preference is that Clojure already gives you really good, simple building blocks.
This allows you to define the simple functions that directly enrich your domain without worrying as much about length.
If I want added documentation, I will let a variable with a good name.

On the topic of int-division, I'm pretty sure you can solve this problem with just quot and rem. Wasn't sure you were aware of those functions.
Feel free to let me know if I'm mistaken there.

Lastly, in my solution, I tried to focus first on calculating the purchased chocolates, then on calculating the freebies,
as opposed to creating a seq of all chocolates, then summing them up at the end.  This separation of concerns allows you to structure the program
intent clearly at the topmost level. It has the added benefit of making the recursive part of the program a bit more straightforward.

Update

Per OP's request, here is my solution:

(defn calculate-freebies [purchased-chocolates wrappers-per-freebie]
  (loop [remaining-wrappers purchased-chocolates
         free-chocolates 0]
    (if (< remaining-wrappers wrappers-per-freebie)
      free-chocolates
      (let [new-chocolates (quot remaining-wrappers
                                 wrappers-per-freebie)]
        (recur
          (+ (rem remaining-wrappers
                  wrappers-per-freebie)
             new-chocolates)
          (+ free-chocolates new-chocolates))))))

(defn calculate-chocos [bobs-money cost-of-chocolate wrappers-per-freebie]
  (let [purchased-chocolates (quot bobs-money
                                   cost-of-chocolate)
        freebies (calculate-freebies purchased-chocolates
                                     wrappers-per-freebie)]
    (+ purchased-chocolates freebies)))

Note that I did go ahead and pull out calculate-freebies into a separate defn. I did that because a) it's a standalone concept and b) it makes calculate-chocos easier to read. If it weren't a standalone concept, I would have likely defined it in the let of calculate-chocos itself.


Shuffle array elements by rearranging the key value associations

Rather than making iterated rand() calls, you should randomize the data once for best efficiency.  To do this, just isolate the keys, shuffle them, then rejoin the values to the appropriate keys in the new order.

Code: (Demo)

function preserve_shuffle(&$arr)    #Shuffles the key-value associations in an array.
{
    $keys = array_keys($arr);   #extract the keys from the array.
    shuffle($keys);
    for ($index = 0, $length = count($keys); $index < $length; ++$index) {
        $result[$keys[$index]] = $arr[$keys[$index]];
    }
    $arr = $result;
}

$arr = ["a" => "apple", "b" => "banana", "c" => "capsicum", "d" => "dill"];
preserve_shuffle($arr);
var_export($arr);

Or, if you prefer greater brevity or a functional syntax, you could use the following inside your custom function:

$keys = array_keys($arr);   #extract the keys from the array.
shuffle($keys);
$arr = array_merge(array_flip($keys), $arr);

Proof that it also works: https://3v4l.org/eLMo6

My earlier snippets only reorder the associative data.  The following will shuffle the associations without shuffling the key orders.  It does not guarantee that all initially associations will be destroyed -- which I feel is beneficial / less predictable in a randomized result.

function random_disassociate(&$assoc_array)
{
    if (sizeof($assoc_array) < 2) {
        return;  // data cannot be disassociated
    }
    $keys = array_keys($assoc_array);
    shuffle($assoc_array);
    $assoc_array = array_combine($keys, $assoc_array);
}

$arr = ["a" => "apple", "b" => "banana", "c" => "capsicum", "d" => "dill"];
random_disassociate($arr);
var_export($arr);


There are a couple of minor things I'd suggest you look into:

Names matter: you're assigning the query string to a variable called $sth, and assinging the prepared statement to a variable called $q. To me, that looks wrong, and it should be the other way around. A variable called $q or $query should be a query string, and a variable called $sth or $stmt should be a prepared statement.
Transactions: if, somewhere down the line, one of the INSERT queries failed, I wouldn't carry on. To me, that smells of bad/invalid/malicious data, and I'd want to stop inserting and even undo whatever inserts that were already executed. By starting a transaction before the loop, and committing it at the end, you can do this easily
Because you are re-using a statement several times (which is good), you might want to add a closeCursor call. The MySQL drivers don't really care about this, but some other drivers do. Depending on what DB you're using, your code might behave differently if you leave it out.

Basically, using bindParam as Pinoniq suggested is a good idea. However, make sure $last_id stays valid. It's not being altered in your loop, so make sure the code between bindParam and the execute call doesn't do anything untoward with that variable.
All things aside, your code could be made to look something like this:

$query = 'INSERT INTO users_contracts (users_id,contracts_id)
    VALUES (:user,:contract)';
try
{//begin try-block here
    $conn->beginTransaction();//start the transaction
    $stmt = $conn->prepare($query);
    $stmt->bindParam('user', $lastId);
    $stmt->bindParam('contract', $contractId);
    foreach($contract as $contract => $contractId)
    {
        $stmt->execute();
        $stmt->closeCursor();//<-- doesn't hurt
    }
    $conn->commit();//everything went smoothly, save inserts
}
catch (PDOException $e)
{
    $conn->rollBack();//undo changes!
    //handle error
    printf(
        '%d - %s insert failed: (%d) %s',
        $lastId,
        $contractId,
        $e->getCode(),
        $e->getMessage()
    );
}


Find best candidates in efficient way, Django

You could use comprehensions to greater effect (here: directly build job_skills using a set comprehension) and also let got of having to put everything into a list.
You could also store your suitable candidates in a collections.Counter, to get the most_common(n) method for free.
from collections import Counter

def finder(job_id, n=50):
    job_skills = {skill.id for skill in Job.objects.get(id=job_id).skills.all()}

    candidates = Counter()
    for employee in Employee.objects.filter(title=job.title):
        employee_skills = Candidate.objects\
                                   .filter(employee__id=employee.id)\
                                   .values_list('skill', flat=True)
        common_skills = len(job_skills.intersection(employee_skills))
        if common_skills:
            candidates[employee] = common_skills
    return candidates.most_common(n)

I also followed Python's official style-guide, PEP8, which recommends not surrounding = with spaces when using it for keyword arguments, used the fact that the number 0 is falsey, while all other numbers are truthy and made the number of candidates to return configurable (with 50 the default value).

Note that this task would have been slightly easier, if the Employee object already had the skill attached, or at least a link to the Candidate object.


REST API calls to BIG-IP LTM to get the status of pool members

Regarding your performance problem there's nothing obviously wrong with the code.  I'd suggest you make sure that the server isn't throttling the responses in subsequent runs.

If that's not the case the next step would be to determine which of the calls is slow and pinpoint if it's an issue e.g. with JSON parsing or accumulating some garbage data that's not necessary.

In particular a profiler would come in handy for this, even something like cProfile would probably be enough to check for obvious problems.

The code should follow PEP8 naming conventions everywhere, i.e. make_request.
Also compatibility with Python 3 would be nice, so use print(...).


How to make Map expendible(?) safely in java

It took a long time just to understand what your program is doing and how it might be useful.
You were concerned about the unchecked casting, and that's a valid concern, but maybe it's not a problem if you make that behaviour clear, for instance, by including a failure scenario in the test case or JavaDoc, in which case you are just stating it's the responsibility of the other code that makes use of this to only pass valid arguments.
Here's a version of the same thing that's hopefully a bit better at describing what it does. With things a bit more plain to read, you can decide if you want your program to behave differently in the failure case -- maybe it should throw a checked exception instead of ClassCastException or maybe you want to actually support these cases?
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

/**
 * I am building some statistic counter in Java. Each metric could have flexible
 * depth so the implementation should able to explore the depth when value
 * insert or update.
 *
 */
public class StatisticsCounter {

    private Map<String, Object> rootMap = new HashMap<>();

    public void increment(String... paths) {
        recursiveIncrement(rootMap, paths, 0);
    }

    private void recursiveIncrement(Map<String, Object> targetMap, String[] pathToTarget,
            int pathIndex) {

        final int targetDepth = pathToTarget.length - 1;
        final String counterName = pathToTarget[pathIndex];

        if (pathIndex == targetDepth && targetMap.containsKey(counterName)) {
            // assume objects at the target depth are int
            targetMap.put(counterName, (int) targetMap.get(counterName) + 1);
        } else if (pathIndex == targetDepth) {
            // at the target depth, put ints
            targetMap.put(counterName, 1);
        } else if (targetMap.containsKey(counterName)) {
            // assume object is a map, recur into it for the next counter name
            recursiveIncrement((Map<String, Object>) targetMap.get(counterName),
                    pathToTarget, pathIndex + 1);
        } else {
            // create a new map and recur into it for the next counter name
            Map<String, Object> emptyMap = new HashMap<>();
            targetMap.put(counterName, emptyMap);
            recursiveIncrement(emptyMap, pathToTarget, pathIndex + 1);
        }
    }

    public String toString() {
        return rootMap.toString();
    }

    @Test
    public void test() {
        StatisticsCounter counters = new StatisticsCounter();
        counters.increment("USA", "California", "Los Angeles");
        counters.increment("USA", "California", "Los Angeles");
        counters.increment("USA", "California", "San Diego");
        counters.increment("USA", "California", "Bay Area", "San Francisco",
                "Financial District");
        counters.increment("USA", "Tennessee", "Memphis");
        counters.increment("USA", "Tennessee", "Memphis");
        counters.increment("Italy", "Venice");
        counters.increment("Italy", "Rome");
        counters.increment("Italy", "Venice");
        counters.increment("Vatican City");
        counters.increment("Vatican City");

        try {
            counters.increment("USA", "California");
            fail("Cannot increment a key that already has subcounters");
        } catch (ClassCastException expectedException) {
            assertEquals("java.util.HashMap cannot be cast to java.lang.Integer",
                    expectedException.getMessage());
        }

        try {
            counters.increment("USA", "Tennessee", "Memphis", "Graceland");
            fail("Cannot add subcounters to a key that already has a count");
        } catch (ClassCastException expectedException) {
            assertEquals("java.lang.Integer cannot be cast to java.util.Map",
                    expectedException.getMessage());
        }

        System.out.println(counters);
        // {USA={Tennessee={Memphis=2}, California={San Diego=1, Bay Area={San
        // Francisco={Financial District=1}}, Los Angeles=2}}, Italy={Rome=1, Venice=2},
        // Vatican City=2}
    }
}


This is already pretty simple. But I'd use the ternary operator ?: to make it a bit more compact:

function validateDateFormat(format) {
    return format.indexOf("yyyy") == -1 ? format : format.replace(/yy/g, 'y');
}

Also, perhaps you can be a bit more accurate.
There is a discrepancy between your check and the action taken:

Check if string contains "yyyy"
Replace all occurrences of "yy" with "y"

Perhaps it would be more accurate to change the action to this:

  Replace "yyyy" with "yy" (only once)

That is:

function validateDateFormat(format) {
    return format.indexOf("yyyy") == -1 ? format : format.replace(/yyyy/, 'yy');
}

Actually, and probably I should have started with this:
since the .replace method returns the original string if there is no match,
you could simplify even further:

function validateDateFormat(format) {
    return format.replace(/yyyy/, 'yy');
}


Since the intervals aren't consistent, rounding wouldn't help, but you can drop the floor condition since you're using else-if.

    if(bottomLine.length > 0) {
        if (bottomLine[0].product_score === 'undefined') {return 0;}//jshint ignore:line
        else if(bottomLine[0].product_score <=1.5)  {return 1;}// jshint ignore:line
        else if(bottomLine[0].product_score <=2) {return 2;}//jshint ignore:line
        else if(bottomLine[0].product_score <=2.5) {return 2.5;}//jshint ignore:line
        else if(bottomLine[0].product_score <=3.2) {return 3;}//jshint ignore:line
        else if(bottomLine[0].product_score <=3.7) {return 3.5;}//jshint ignore:line
        else if(bottomLine[0].product_score < 4.3) {return 4;}//jshint ignore:line
        else if(bottomLine[0].product_score < 4.75) {return 4.5;}//jshint ignore:line
        else {return 5;}//jshint ignore:line
    }

And, since you're returning each time, you can drop the "else" part of the else if for that matter.

    if(bottomLine.length > 0) {
        if (bottomLine[0].product_score === 'undefined') {return 0;}//jshint ignore:line
        if(bottomLine[0].product_score <=1.5)  {return 1;}// jshint ignore:line
        if(bottomLine[0].product_score <=2) {return 2;}//jshint ignore:line
        if(bottomLine[0].product_score <=2.5) {return 2.5;}//jshint ignore:line
        if(bottomLine[0].product_score <=3.2) {return 3;}//jshint ignore:line
        if(bottomLine[0].product_score <=3.7) {return 3.5;}//jshint ignore:line
        if(bottomLine[0].product_score < 4.3) {return 4;}//jshint ignore:line
        if(bottomLine[0].product_score < 4.75) {return 4.5;}//jshint ignore:line
        return 5; //jshint ignore:line
    }

I think you should remove the redundant floor conditions, but I can see a case made either way with leaving the "else" in place.


Improving function that parses string and returns first integer present

I believe you have either misunderstood the task, or misunderstood Number.isNaN. In any case the if doesn't do anything usefull. Number.isNaN returns true only when the value is exactly NaN, which is not a valid input for your function anyway.
Then you are not checking if search() isn't matching anything (and thus searchFrom is -1). It doesn't really matter, because substr(-1) simply returns the last character, but it would make the code better to understand.
Use const instead of let when the value doesn't change.
Personnally I'd use .match() instead of .search(), because it returns the matched string directly (in an array):
function parseFirstInt(str) {
  // Check if the paramter is a object with the method `match`
  if (!str.match) {
    return NaN;
  }
  const match = str.match(/[-+]?[0-9]+/);
  if (match && match[0]) {
    return parseInt(match[0], 10);
  }
  return NaN;
}


You can use a static weak_ptr in the function to cache the shared instance without extending its lifetime:

template<typename T>
std::shared_ptr<T> get_shared_instance()
{
    static std::mutex m;
    static std::weak_ptr<T> cache;

    std::lock_guard<std::mutex> lg(m);

    std::shared_ptr<T> shared = cache.lock();
    if (cache.expired()) {
        shared.reset(new T);
        cache = shared;
    }
    return shared;
}

So, the first caller will find a default-initialized weak_ptr counts as expired, and construct a new T.

While the first caller is active (and keeping its new T alive), concurrent callers will get the same object, cached in the weak_ptr.  When the last concurrent user is done, the object will be destroyed.

A subsequent caller will find the weak_ptr expired (same as before the first call), and create a new T ... etc. etc.


One of my favorite patterns for handling URL parameters in WebForms is the WebNavigator - http://polymorphicpodcast.com/shows/webnavigator/

If you're going through these kinds of Strongly-typed interactions for passing parameters between pages, maybe it is time you check out ASP .NET MVC - your solution looks a lot like model-binding.


Bank account balance data structure design and code

I think using dictionaries is about right for this small project.

However, the code will not scale well in terms of readability with lists of tuples. You should consider using object oriented approach, and implement some serialization, deserialization methods (for storing the data onto the disk and reading it back). That way you can add more functionalities in a more manageable way.

I don't understand why you allow negative balance!


In order to improve the performance of your script you should read cell values from an array that represents the entire range that your are going to scan.

This means that instead of repetedly calling

var status = sheet.getRange("F"+i).getValue(); //Get the value of the cell.

you should get everything in a single call like this one

var values = getRange(row, column, numRows, numColumns).getValues();

it'll give you an array that you can iterate very fast. Example:

for (var row in values) {
  for (var col in values[row]) {
      ...
  }
}

Hiding rows can be a little bit tricky if you want to optimize it becasue it requries some additional work. If you do it for each row separately then you'll loose some performance agian. This means that this is not good:

sheet.hideRows(i); // Hide the row

In my scripts that work with a few hundereds or thousands rows hiding some of them lasts no longer than 1-2 seconds.

Here's how it goes:

I have a special column that I call Visible (or whatever). I use it to store a boolean value.

When I run a loop I store the flag in a second array like var visibles = []; instead of calling hideRows each time.

After the loop is finished I update the Visible column with:

// update row visibility
var visibleRange = sheet.getRange(row, column, numRows, numColumns);
visibleRange.setValues(visibles);

This runs super fast.

Next you have to unhide all rows with:

// show all rows
sheet.showRows(rowIndex, numRows);

You have to sort them by visibility:

// sort by 'visible' and make 'true' (visible) rows first
sheet.sort(..., false);

Sorting is necessary so that you can finally hide an entire range in a blink of an eye:

// hide 'false' (not-visible) rows
var rangeToHide = sheet.getRange(.., .., ..);
SpreadsheetApp.getActiveSpreadsheet().hideRow(rangeToHide);

If you need a different order you can sort it again after hiding.

With this solution it requires just a couple of calls which will make your script really smooth.

You can read about a couople more optimization tipps on Google Apps Script - Best Practices


Optimizing javascript/jquery code for HTML creation with JSON

don't even really need jQuery for this task

here's one way to rework this script:

example jsfiddle

var domStructure = "";
    jsonObj = {
    "products": [
    {
        "ImageName": "product1.png",
        "Description": "Yummy choco"
    },
    {
        "ImageName": "product2.png",
        "Description": "candy villa"
    },
    {
        "ImageName": "product3.png",
        "Description": "vanilla icecream"
    }],
};

function getTableRow(img, desc) {
    return '\

\
            \
                \
            	\
            ' + desc + '	\

';
}

for(var key in jsonObj.products) {
    domStructure += getTableRow(jsonObj.products[key].ImageName, jsonObj.products[key].Description);
}

document.getElementById('tableProducts').getElementsByTagName('tbody')[0].innerHTML = domStructure;

or if you keep jQuery method to set the table row markup use $('#tableProducts tbody') instead of $('#tableProducts').find('tbody'), no need to have jQuery fetch the first element then find the second vs letting it works it magic on one selector. it's about the same speed on the various selectors according to this jsperf.

Tests the following html setters:

$('#tableProducts tbody').html(domStructure);
$('#tableProducts').find('tbody').html(domStructure);
$('#tableProducts').children('tbody').html(domStructure);
document.getElementById('tableProducts').getElementsByTagName('tbody')[0].innerHTML = domStructure;

in the results the pure JS method jumps ahead on Firefox 9.0.1 and Safari 5.1.2


If you have access to C++17, you can use std::filesystem instead of boost::filesystem.

This is gonna cause a ton of problems by obscuring the source of names used in the code and introducing name clashes:

using namespace std;
using namespace boost::filesystem;

Qualify names from std instead, and maybe namespace fs = std::filesystem;.

Overall, the main function is very long and requires a lot of brain energy to understand.

Declaring a lot of variables at the start of a block makes the logic hard to follow:

vector <string> str,parsed_str;
path p("./fake_pcd");
string delimiter = ".";
string token,parsed_filename;
size_t pos = 0;
int int_filename;
vector <int> int_dir;

Some of the variables have sub-optimal names.  Also consider accepting the path as an argument for more flexibility:

int main(int argc, char* argv[])
{
    // validate ...
    std::path directory{std::string{argv[1]}};
    // ...
}

This is convoluted:

//insert filenames in the directory to a string vector
for (auto i = directory_iterator(p); i != directory_iterator(); i++)
{
    if (!is_directory(i->path())) //we eliminate directories in a list
    {
    str.insert(str.end(),i->path().filename().string());
    }
    else
        continue;
}

Simplification: (note that directory_iterator is a range by itself)

std::vector<std::string> filenames;
for (const auto& entry : fs::directory_iterator{directory}) {
    if (!entry.is_directory()) {
        filenames.push_back(entry.path().filename().string());
    }
}

Sorry, I gave up trying to understand everything beyond this point.

Here's basically how I would write the same code (not tested):

#include <algorithm>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>

namespace fs = std::filesystem;

fs::directory_entry parse_args(int argc, char* argv[])
{
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <directory>\n";
        std::exit(EXIT_FAILURE);
    }

    fs::directory_entry directory{argv[1]};
    if (!directory.is_directory()) {
        std::cerr << '\'' << argv[1] << "' is not a directory\n";
        std::exit(EXIT_FAILURE);
    }
    return directory;
}

int main(int argc, char* argv[])
{
    auto directory = parse_args(argc, argv);

    std::vector<fs::path> filenames;
    for (const auto& entry : fs::directory_iterator{directory}) {
        if (entry.is_regular_file()) {
            filenames.push_back(entry.path().filename());
        }
    }

    std::sort(filenames.begin(), filenames.end(),
              [](const auto& lhs, const auto& rhs) {
                  return lhs.string() < rhs.string();
              });
    for (const auto& file : filenames) {
        std::cout << file.string() << '\n';
    }
}


You should adhere to the following:

Capitalize method names.
You don't need count variable.
Don't specify a return type, then not utilize it.

Point (1) and (3) could be rectified:

protected static void WriteToConsole(string input)
{
     Console.ForegroundColor = ConsoleColor.Cyan;
     Console.WriteLine(input);
}

The application code could then be:

var vowels = Console.ReadLine().Where(c => "aeiouAEIOU".Contains(c));

if(vowels.Any())
{
     foreach(var vowel in vowels.Distinct())
         WriteToConsole(String.Format("Your sentence contains the following vowel {0}", vowel);

    WriteToConsole(String.Format("Your sentence contains {0} vowels", vowels.Count());
}
else
{
     WriteToConsole("Your sentence doesn't have any vowels.");
}

Also to point out, in the other question to avoid duplicate entries an uneeded iterations of repeated vowels, I called .Distinct.  This alleviated that, but that would throw off your official count of how many vowels exist within the sentence.  So I call Distinct on the loop rather than the initial input.

Also to avoid an unneeded count variable, I call .Count() on the IEnumerable, the feature exist so why not use it?


C# consecutive and redundant null checks

Two things to think about:

Could you code this so it's impossible to create an invalid Theme instance thus not having to worry about it in this method?
How does a consumer know what is invalid about their instance?

For 1, you could simply have a constructor that takes all of the arguments and throws if any are invalid. A pattern that can also work well is having defaults - that way, a theme can just override part of the default theme rather than having to specify everything.
For 2, add some context to your exceptions:
throw new IncompleteThemeException("Default Password Indicator Brush was not specified");

However, I would probably lean towards having a mutable builder class with defaults and have a create method there. Consuming it could look like:
var builder = new ThemeBuilder(Theme.Default /* or existing theme etc. */)
     .WithErrorBrush(myErrorBrush)
     .WithAccentBrush(myAccentBrush);

// Now build it.
var theme = builder.Build();

That seems like it would make it easier for consumers to use a Theme as all instances would always be valid and you get the ease of use via the builder class. A nice bonus is that you can add new properties to the theme without breaking consumers. They get a sensible default that they can choose to override if needed. You don't just start throwing IncompleteThemeException.


Appending a codepoint to an UTF8 std::string using icu4c

Beauty is in the eye of the beholder. I say it is perfectly valid and correct code! The only thing you might get rid of is the static_cast<uint32_t>, as an UChar32, which is an alias forint32_t, will implicitly cast to uint32_t without warnings.
You could also use append() instead of resize(), avoiding the addition, and remove the temporary ptr, to finally get:
void utf8_append(UChar32 cp, std::string& str) {
    auto offset = str.size();
    str.append(U8_LENGTH(cp), {});
    U8_APPEND_UNSAFE(reinterpret_cast<uint8_t *>(&str[0]), offset, cp);
}

If you can use C++17, str.data() is slightly nicer than &str[0] in my opinion. Or you could write &str.front().


Find if a number is equal to the sum of its divisors

Finding divisors faster

Instead of checking all numbers until number / 2,
it's enough to search until sqrt(number),
and count the divisor pairs.
For example, in the case of 6,
initialize sum = 1, because 1 will be always part of the sum,
and then when you see 2, also add 6 / 2 to the sum.
(You can get sqrt with #include "math.h".)
Also,
you can break out of the loop when sum exceeds the target value.

There is one more important point that can slow your implementation down,
is that all the variables are double instead of int.
This is not only unnatural for the given task,
floating point math is expensive in general.
So simply rewriting the program so that number, i, m, n are all integers, will make a big difference.

Make perfectCheck return boolean

Currently perfectCheck returns the sum of divisors.
You could make it return a bool:

return sum == number;

You can get the bool type in C99+ with #include "stdbool.h".

And then you can write the main function a bit simpler:

for (i = 0; i < n; i++)
{
    scanf("%d", &m);
    printf("%d ", perfectCheck(m));
}


Asynchronous database lookups in Node.JS using Promises

Promises benefit from the new ES6 syntax, making callbacks a bit compact. If you can use Node.js 4+, then by all means take advantage of the new syntax.

Your indents could need a bit of work. You're mixing 2-space and 4-space. It doesn't really matter which one you chose as long as you are consistent.

var i, c;
ct.getIndustryById(req.user.industry)
  .then(function(industry) {
    i = industry;

Instead of putting an outsider i and c to store the values temporarily until the last then, why not pass it through as a resolved value? That way, your functions don't need to use temporary variables.

exports.renderEditProfile = function(req, res, next) {
  ct.getIndustryById(req.user.industry).then( industry => {
    return ct.getCountryById(req.user.country).then( country => ({ country, industry }) );
  }).then( data => {
    res.render('profile_edit', {
      profile: req.user,
      industry: data.industry,
      country: data.country
    });
  }).catch(function(err) {
    res.status(500).json({'message': err});
  });
};

Alternatively, both requests don't seem to depend on each other. Therefore, it makes no sense to fire them sequentially. Suggesting you fire them in parallel, and use Promise.all to listen for the response.

exports.renderEditProfile = function(req, res, next) {

  const industryPromise = ct.getIndustryById(req.user.industry);
  const countryPromise = ct.getCountryById(req.user.country)

  Promise.all([ industryPromise, countryPromise ]).then(resolution => {
    res.render('profile_edit', {
      profile: req.user,
      industry: resolution[0],
      country: resolution[1],
    });
  }).catch(function(err) {
    res.status(500).json({'message': err});
  });

};


First of all, your method is not really correct: for AAAABBBBAAB it returns [A+, B+, A+] instead of the required [A+, B+, A+, B]. That's because the last group is never added to the list of groups.

This is not very Pythonic:

if accumulate == False:

Write it this way instead:

if not accumulate:

Also, instead of iterating over the "alphabet" using indexes, it would be more Pythonic to rewrite to iterate over each letter, in the style for letter in alphabet.

"alphabets" is not a good name. It seems letters would be better.

The algorithm can be simplified, and you could eliminate several intermediary variables:

def create_groups(letters):
    """ function group the alphabets to list of A(+)s and B(+)s """
    prev = letters[0]
    count = 0
    groups = []
    for current in letters[1:] + '\0':
        if current == prev:
            count += 1
        else:
            group_indicator = prev + '+' if count > 0 else prev
            groups.append(group_indicator)
            count = 0
        prev = current
    return groups

In the for loop, I appended '\0' to the end, as a dirty trick to make the loop do one more iteration to append the last letter group to groups. For this to work, it must be a character that's different from the last letter in letters.

The above is sort of a "naive" solution, in the sense that probably there is a Python library that can do this easier. Kinda like what @jonrsharpe suggested, but he didn't complete the solution of converting [['A', 'A', 'A', 'A'], ['B', 'B', 'B', 'B'], ['A', 'A'], ['B']] in the format that you need. Based on his solution, you could do something like this:

from itertools import groupby

def create_groups(letters):
    return [x + '+' if list(g)[1:] else x for x, g in groupby(letters, str)]

What I don't like about this is the way we put the letters in a list just to know if there are 2 or more of them (the list(g)[1:] step). There might be a better way.


First of all, let the code speak! Don't unnecessarily add comments unless they are explaining a really complicated piece of code.

Basic definitions:

A magic number is defined to be:

  Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants

Can you find the magic numbers in your code?
Yes that's right, the culprits are 11 and 4.

Let's just define variables for those!

ROWS = 11
COLS = 11
GRID_ROWS = 4
GRID_COLS = 4

Next, let's replace every magic number with the appropriate variable!

Making the code shorter!

Function board_printer

Why use enumerate? Why make everything a str?

Your whole function can just be rewritten as the following:

def board_printer(board):
    """Prints the sudoku board"""

    for row in board:
        print(*row)

Function board_filler

You don't need to use for x in enumerate(board) at all!
Just use for x in range(ROWS) and change every instance of x[0] to x accordingly

Instead of

if ((x[0] + 1) % GRID_ROWS) == 0:
    for y in range(11):
        board[x].append("-")

Use

if ((x[0] + 1) % GRID_ROWS) == 0:
    board[x] = ["-"] * COLS

Use formatting!

for taking input of number, use number = input("Please enter a number for the square in row {xRead} and in column {yRead} (hit enter for no number): ") instead of using %s

Why use a dummy variable z?

Just do:

while True:
    number = input("Please enter a number for the square in column {x[0] + 1} and in row {y + 1} (hit enter for no number): ")

    try:
        number = int(number)

        if number > 9 or number < 1:
            raise ValueError
        else:
            board[x].append(number)

        break

    except (TypeError, ValueError):
        if not number:
            board[x].append(" ")
        else:
            print("Please enter an integer between 1 and 9")

Essentially, it tries to take an input, check if the value is an integer between 1 and 9, else raises an exception. If the number was indeed valid, it makes it to the end of the try statement, which causes the loop to break

Misc

Run board_printer(board_filler()) inside if __name__ == __main__:. This causes board_printer(board_filler()) not to run if it was imported from another module.
Try using list(map(int, input(f'Enter {COLS - (COLS // GRID_COLS)} space separated integers: ').split())) for each row. It is tiring to fill every single cell by hand! So ask input for a whole row. It's your personal preference though!

Hope this helps!

EDIT:

This part is to solely dedicated to removing xRead and yRead and is not related to the above improvements

First we have to change
ROWS = COLS = 11 to ROWS = COLS = 9 and
GRID_ROWS = GRID_COLS = 4 to GRID_ROWS = GRID_COLS = 3

Do not append - or | to board at all!

Just remove all statements that append - or | and also remove xRead and yRead. Now, the board would look like a sudoku board without - or |

In the board_filler use

def board_printer(board):
    """Prints the sudoku board"""

    for row in range(ROWS):
        s = ''

        for col in range(COLS):
            s += str(board[row][col]) + ' '

            if not (col + 1) % GRID_COLS:
                s += '| '

        print(s)

        if not (row + 1) % GRID_ROWS:
            print('-' * len(s))

This will print - or | according to the row or column!

Final code including all above mentioned improvements

ROWS = COLS = 9
GRID_ROWS = GRID_COLS = 3

def board_filler():
    """Creates the sudoku board from user input"""

    board = [[] for _ in range(ROWS)]

    for x in range(ROWS):
        for y in range(COLS):
            while True:
                number = input(f"Please enter an integer for the square in column {x + 1} and in row {y + 1} (hit enter for no number): ")

                try:
                    number = int(number)

                    if number > 9 or number < 1:
                        raise ValueError
                    else:
                        board[x].append(number)

                    break

                except (TypeError, ValueError):
                    if not number:
                        board[x].append(" ")
                    else:
                        print("Please enter an integer between 1 and 9")

    return board

def board_printer(board):
    """Prints the sudoku board"""

    print()

    for row in range(ROWS):
        s = ''

        for col in range(COLS):
            s += str(board[row][col]) + ' '

            if not (col + 1) % GRID_COLS:
                s += '| '

        s = s[:-1] # Removes trailing space

        print(s)

        if not (row + 1) % GRID_ROWS:
            print('-' * len(s))

if __name__ == '__main__':
    board_printer(board_filler())

NOTE: board_filler doesn't look as bloated either! The code kills 2 birds with one stone!


Implementation of Observable with multiple callback function signatures

There is a way to get rid of the integral constant dispatch without forcing the user to inherit from an observable class, but it's a bit complex.

The idea is to encapsulate runtime polymorphism inside the Observable class. The pattern looks like:

class PolymorphicBehavior {
    class Concept {
        // here are the virtual functions
    };
    template <typename ConcreteType>
    class Object {
        // here are concrete implementations of the functions
        // The class encapsulates type information
        private:
        ConcreteType value;
    };
    public:
    template <typename ConcreteType>
    PolymorphicBehavior(const ConcreteType& ct) : ptr(new Object<ConcreteType>(ct)) {}
    private:
    Concept* ptr;
};

In the case of Observable, this pattern allows you to erase the function signature (concrete type information is stored in the inner object). There's still another type erasure to perform though, because we'll need to pass arguments to the encapsulated functions. I used std::any over a tuple to create a unified interface.

Here's the full code:

#include <iostream>
#include <vector>
#include <memory>
#include <tuple>
#include <any>
#include <functional>

//deducing the tuple type from the function type
// e.g: std::function<void(float, double)> => std::tuple<float, double>
template <typename T>
struct tuple_desc;
template <typename R, typename... Args>
struct tuple_desc<std::function<R(Args...)>> {
    using type = std::tuple<Args...>;
};

// deducing the function signature from the callable
template <typename Callable>
using function_class = decltype(std::function(std::declval<Callable>()));

class Observable {

    class Observable_model { // type neutral hook
        public:
        virtual void notify(unsigned event_number, std::any& argument_wrapper) = 0;
        virtual ~Observable_model() = default;
    };

    template <typename Callback>
    class Observable_object : public Observable_model { // stores concrete type information
        public:
        Observable_object(unsigned event_class, const Callback& cbk) : event_class(event_class), callback(cbk) {}

        void notify(unsigned event_number, std::any& argument_wrapper) override {
            using Arg_tuple = typename tuple_desc<decltype(this->callback)>::type; // so tuple<int, float> for [](int a, float b) { /*...*/ }
            if (event_number == event_class) { // dynamic dispatch
                std::apply(callback, std::any_cast<Arg_tuple> (argument_wrapper));
            }
        }
        private:
        unsigned event_class;
        function_class<Callback> callback;
    };

    public:
    template <typename Callback>
    void attach(unsigned event_class, Callback&& callback) {
        auto new_obj = std::make_unique<Observable_object<Callback>>(event_class, callback);
        observations.push_back(std::move(new_obj));
    }
    template <typename... Args>
    void notify(unsigned event_number, Args&&... args) {
        std::tuple<Args...> arg_tuple(std::forward<Args>(args)...);
        std::any argument_wrapper(arg_tuple); // argument type erasure
        for (auto& obs : observations) obs->notify(event_number, argument_wrapper);
    }

    private:
    std::vector<std::unique_ptr<Observable_model>> observations;

};

// testing the interface;

enum { WILDLIFE = 0, MACHINES = 1 };

struct Buzzer {
    void go(int h) { std::cout << "drrrr... drrrr... it's " << h << " a.m, time to wake up!\n"; }
};
struct Coffee_machine {
    void make_coffee(int h) { if (h == 7) std::cout << "time to make coffee!\n"; else std::cout << "no coffee yet baby!\n"; }
};

struct Rooster {
    void sing() { std::cout << "Cocorico!\n"; }
};
struct Vampire {
    void bury() { std::cout << "Bye! I'll be in my grave!\n"; }
};

struct Sun : public Observable {
    void rise() {
        std::cout << "Waouh, the sun rises!\n";
        notify(WILDLIFE);
        notify(MACHINES, 6);
    }
};

int main() {
    Sun sun;
    Buzzer buzzer;
    Rooster rooster;
    Vampire vampire;
    Coffee_machine coffee_machine;
    sun.attach(WILDLIFE, [&rooster] {rooster.sing();});
    sun.attach(WILDLIFE, [&vampire] {vampire.bury();});
    sun.attach(MACHINES, [&buzzer](int h) {buzzer.go(h);});
    sun.attach(MACHINES, [&coffee_machine](int h) {coffee_machine.make_coffee(h);});
    sun.rise();
}


generate a 2d array that could be used to create an image with Java

You don't need to manually manage nested for loops.
int[][] pixels = new int[100][100];
for (int[] row : pixels) {
    Arrays.fill(row, 1);
}

for (int i = 20; i < 50; i++) {
    Arrays.fill(pixels[i], 20, 50, 0);
}

This will make better use of optimizations available for managing array values.
I personally don't like arr as a name for an array.  If I need a generic name, I tend to use data.  I used pixels here.  Or colors would work.
This may be more or less efficient than
int[][] pixels = new int[100][100];
int i = 0;
for (; i < 20; i++) {
    Arrays.fill(pixels[i], 1);
}
for (; i < 50; i++) {
    Arrays.fill(pixels[i], 0, 20, 1);
    Arrays.fill(pixels[i], 50, pixels[i].length, 1);
}
for (; i < pixels.length; i++) {
    Arrays.fill(pixels[i], 1);
}

That doesn't set any of the pixels twice and relies on the default values for the 0 pixels.  That may be more efficient.  Although it is also possible that it is easier to set the entire array to one value than to work with rows and parts of rows.
Note that if you are willing to change the representation, then
int[][] pixels = new int[100][100];
for (int i = 20; i < 50; i++) {
    Arrays.fill(pixels[i], 20, 50, 1);
}

would probably be better than either.  In this, black is the default 0 while 1 is the white square.
The third form is the least code and probably fastest.  The only way that I could see it being as slow or slower than either of the others is if something is happening implicitly.  For example, if there is a memory initialization that the first form skips because it immediately does its own initialization.
The first form is less code than the second.  The comparative speed would probably depend on the platform (and possibly compiler).  Platforms that allow for managing memory as blocks would probably find the first quicker, while platforms that can only address one word at a time would probably find the second quicker.
You would have to do timing tests on all platforms where you expect to run to get a real idea of the speed.
There is probably a streams-based version that is faster as well.
If you want to go further and try to pass the information for regions, you would either have to write your own solution or use a third party library.  Note that such a thing would probably be slower.  But it might be less code.  I suspect that your Python example is also slower on some platforms (albeit less code).  My guess is that Python implements it much as the first example code block in this answer.


Find all starting indices in a string which are anagrams of a word

This code looks pretty good. I don't see much I would change. This code makes good use of const and let where appropriate.

The only thing that stands out is that splitting a string into an array can be done with the spread syntax instead of calling split().

The first instance:

let sReverse = s.split('').reverse().join('');

Could be changed to

let sReverse = [...s].reverse().join('');

And the other instance:

const sortAlphabetically = x => x.toLowerCase().split('').sort().join('')

Could be changed to:

const sortAlphabetically = x => [...x.toLowerCase()].sort().join('')


Interesting question.

First off, your indentation is terrible, your code is far more readable like this:

ko.utils.arrayFirst(ko.utils.arrayFirst(self.SubSteps(),
  function(item) {
    return ko.utils.arrayFirst(item.SubSteps(),
      function(subItem) {
        return subItem.InternalName == localStorage.getItem('lastWizardPage');
      });
  }).SubSteps(), function(item) {
  return item.InternalName == localStorage.getItem('lastWizardPage');
})

Second, you are retrieving your subitem twice, because you loose track of it, simply use a 'local global' and assign your subitem to it.

var needle, found;
ko.utils.arrayFirst(self.SubSteps(),
  function(item) {
    return ko.utils.arrayFirst(item.SubSteps(),
      function(subItem) {
        found = subItem.InternalName == localStorage.getItem('lastWizardPage');
        if(found) {
          needle = subItem;
        }
        return found;
      });
  });

or, if you dont mind some sorcery (don't do this at work!)

var needle, found;
ko.utils.arrayFirst(self.SubSteps(),
  function(item) {
    return ko.utils.arrayFirst(item.SubSteps(),
      function(subItem) {
        found = subItem.InternalName == localStorage.getItem('lastWizardPage');
        return found && (needle = subItem), found;
      });
  });

Furthemore, you should consider caching localStorage.getItem('lastWizardPage') and you should consider implementing old skool loops so that you can exit immediately.


This is as good as it gets in Java. The idea of callbacks are very popular, and are the foundation of functional languages. Even Javascript offers a cleaner approach, as JQuery shows. Unfortunately for Java, anonymous inner classes (as you have) are the shortest way to create a function like this.


LRU Cache with a static variable for garbage value

Is it a good practice to have such a static variable just for garbage values?

Maybe not:

garbage_val is a Value, so if you return it, then the caller doesn't know whether the get succeeded.
If garbage_val is supposed to be a magic number (an impossible Value), different users of the class might want different magic numbers ... so why isn't garbage_val an instance member instead of a static member?
Normally container classes expect the caller to check that iterator != end() before dereferencing the iterator.

Instead, the following methods might be appropriate:

// throws an exception if key does exist.
Value get(Key key) { ... }
// tests whether key exists: use this before calling get.
bool contains(Key key) { ... }
// return true and initializes value iff key exists.
// if key doesn't exist then valueOut is not initialized.
bool tryGet(Key key, Value& valueOut) { ... }


Java-Helper library for compressing (zipping) files

Well, I benchmarked it and found that a buffer size of 10485760 (10 MB) was fastest... Kind of surprised about that and I'm thinking that's not the most efficient. I think I'll leave it at 1 MB unless someone else has any thoughts.


View for displaying nounal and verbal pages

You might consider having the controller (or some other thing that is not the view) set up all of the data, such that the view can merely do this:

- @nounals.each do |text, uri|
  %ul
    %li= link_to text, uri, target: '_blank'

and

- @verbals.each do |text, uri|
  %ul
    %li= link_to text, uri, target: '_blank'

Once the two loops are the same other than the variable, you can use a partial template to render each of them.


int, long and double are not precise enough. You should probably use BigInteger and/or BigDecimal instead.

Same problem with e=2.7182818284;. When you do 100000000000L*e you're already off by almost 6. And this is nothing compared to \$10^{100}\$.

Even if you use Math.E instead it's only 2.718281828459045. So you probably want to calculate e to an arbitrary precision (based on input n) instead. (Check here for a hint).

Note that none of those will help you with the time-limit-exceeded problem though. You'll have to find a smarter way so that you don't have to iterate all \$10^{4000}\$ numbers. Note that if you would add a number each millisecond and you ran the program for 300 years you would still only reach about \$10^{12}\$ or \$10^{13}\$. So no where close to what you want.

The best I can come up with is to keep track of the actual sum, the floored sum and the error on each order of magnitude.

So for n = 10, then n=100, then n=1000, ...

At each step you use the result of the previous one. That way you only need to do 10 iterations in the loop at that step to go up an order of magnitude.

Once you have those results you can calculate for any n the wanted result. The tricky part here is how to correct the error's at each step.

Even for \$n=10^{4000}\$ this should only result in O(10000) operations which (depending on your machine specs) runs in less than a minute. (Might also depend on how long calculations with BigInteger/BigDecimal take, I don't have much experience with those myself).

How to actually implement this I'll leave up to you, since this site is all about improving existing code, not just writing new code to solve the problem for you :)

Disclaimer: I did not test this myself yet, so not 100% sure that it will be fast enough even if implemented correctly.


Gathers pair of names (first + last) and separate them into two files

The functionality of your program seems slightly weird. You read multiple files, and each one gets split, but in doing so you (explicitly) delete the old data, is this right?

One thing I notice is this piece of code here:

open("last_names.txt", "w").close() #cleaning the last_names.txt file
open("first_names.txt", "w").close() #cleaning the first_names.txt file
lastNamesFile = open("last_names.txt", "a+", encoding="utf-8-sig")
firstNamesFile = open("first_names.txt", "a+", encoding="utf-8-sig")

This could be replaced by:

lastNamesFile = open("last_names.txt", "w", encoding="utf-8-sig")
firstNamesFile = open("first_names.txt", "w", encoding="utf-8-sig")

I'd also move it to the start of your function:

with open(fileName, "r", encoding="utf-8-sig") as namesFromFile,
     open("last_names.txt", "w", encoding="utf-8-sig") as lastNamesFile,
     open("first_names.txt", "w", encoding="utf-8-sig") as firstNamesFile:

So you can remove the close statements at the end. I'm not sure what the encoding= does, but it might not be necessary.

You can also reduce this:

    for names in namesFromFile:
        allNamesFromFile.append(tuple(names.replace("\n", "").split(" ")))

    for namesTuples in allNamesFromFile:
        try:
            lastNamesFile.write(namesTuples[1] + "\n")
        except:
            lastNamesFile.write("n/a\n")
        try:
            firstNamesFile.write(namesTuples[0] + "\n")
        except:
            firstNamesFile.write("n/a\n")

To this:

for names in namesFromFile:
    names_split = tuple(names.replace("\n", "").split(" "))
    if len(names_split) >= 1:
        firstNamesFile.write(names_split[0] + "\n")
    else:
        firstNamesFile.write("n/a\n")

    if len(names_split) >= 2:
        lastNamesFile.write(namesTuples[1] + "\n")
    else:
        lastNamesFile.write("n/a\n")

Allowing a for loop less and two less try ... except blocks as well as a global list which can now be left out:

"Global Variables:"
allNamesFromFile = []

I don't think this is necessary:

fileName = str(input("Please provide the file name with its extension: "))

Instead use:

fileName = input("Please provide the file name with its extension: ")

I'd also look at this part:

try:
    names_separator(fileName)
    print("operation completed")
    break
except:
    print("You have provided an incorrect file name...")
    continue

You are catching a lot of exceptions, try to be more precise. Instead try:

except FileNotFoundError:

Lastly, you might want to check naming conventions, variables should be in snake_case and classes in CamelCase.

So, to summarize:

check if your program does what you want it to do
open files using with
limit the amount of global variables to 0
limit the amount of try ... except blocks
be explicit in the exceptions you're catching
check pep8 style guide for naming of variables


I think answering my own question is justified here. (?)

While I have no design pattern advice for myself, I've just found a way to greatly improve the performance of setupFrequencies. The code as posted in my question iterates over the entire source text every time a new chunk is found, but it just occurred to me that such an inner loop isn't necessary at all.
Eliminating it not only shortens the code, but also reduces the runtime complexity from O(n²) to O(n) - a huge improvement, especially for longer source texts.

_setupFrequencies: function() {

    this.frequencies = {};

    // for each substring of length <order>,
    // create an array of characters that can follow it
    for (var i = 0; i < this.sourceText.length - (this.order - 1); i++) {
        var chunk = this.sourceText.substr(i, this.order);
        if (!this.frequencies.hasOwnProperty(chunk)) {
            this.frequencies[chunk] = [];
        }
        var follower = this.sourceText.substr(i + this.order, 1);
        this.frequencies[chunk].push(follower);
    }

},


A common way to create a dictionary from two lists is zipping. The zip built in takes two lists and creates a list of pairs from them. In turn, a list of pairs can be used to create a dictionary directly.

Your case has an extra twist: we need to pad the list of values to the same length as the list of keys, otherwise the keys with no corresponding values would simply get dropped.

Even with this minor complication, the function can be written simpler quite easily:

def create_dict(keys, values):
    return dict(zip(keys, values + [None] * (len(keys) - len(values))))

Btw I renamed the function with snake_case to follow recommended PEP8 conventions.

Another alternative somewhat more compact alternative is using itertools.zip_longest:

from itertools import zip_longest

def create_dict(keys, values):
    return dict(zip_longest(keys, values[:len(keys)]))


Some style comments

Add vertical spaces to group code which logically belongs together.
Don't declare multiple variables on the same line.
Name your variables as meaningfully as possible. Names like bf1 won't tell Bob the maintainer what it is about, making it harder to maintain the code.
methods should be named using PascalCase casing. See: C# naming guidelines
Usually a C# developer would expect one to use the Allman indention style; i.e. place the opening brace on the next line.
Always add a scope specifier (access modifier) to methods and variables.

This method is violating the Single responsibility principle. It is just doing too much like normalizing the given input, adding the numeric values of the chars and constructing the result.

Let us take a look at what you are doing to normalize the string

    string cNum1 = null;
    string cNum2 = null;
    if (num1.Length > num2.Length) {
        for (int i = 0; i < (num1.Length - num2.Length); i++) {
            cNum2 += "0";
        }
    } else if (num1.Length < num2.Length) {
        for (int i = 0; i < (num2.Length - num1.Length); i++) {
            cNum1 += "0";
        }
    }
    cNum1 += num1;
    cNum2 += num2;

Each time you call cNum1 += "0" or cNum2 += "0" you are creating a new string. By using the PadLeft() method together with Math.Max() and extracting the the normalization to a separate method your code will look cleaner.

private static string NormalizeValue(string value, int maxLength)
{
    return value.PadLeft(maxLength, '0');
}

This has also the advantage that you won't need cNum1 and cNum2 anymore.

static string addString(string num1, string num2) {

    int maxLength = Math.Max(num1.Length, num2.Length);
    num1 = NormalizeValue(num1, maxLength);
    num2 = NormalizeValue(num2, maxLength);

    .....

}

If you start the for loop at maxLength - 1 and decrement the index you won't need the reversing of the char arrays anymore.

Using a StringBuilder to add the results of the single additions will result in fewer created strings.

If you are sure that the passed in strings only contain digits you can use a neat little trick. You can subtract a char '0' from the current char like e.g

Assume first = '2' and second = '4' are the chars currently be processed.

int result = first - '0' + second - '0';

this boils down to

int result = '2' - '0' + '4' - '0' ;

and is subtracting the ASCII values of the chars

int result = 50 - 48 - 52 - 48;

so there is no need to call int.Parse() anymore. By extracting the two uses of '0' to a const this will be beautified.

const int doubleZeroValue = 96;
int result = first + second - doubleZeroValue;

This will lead to

private static string NormalizeValue(string value, int maxLength)
{
    return value.PadLeft(maxLength, '0');
}

private static string AddString(string firstNumber, string secondNumber)
{
    const int doubleZeroValue = 96;
    int maxLength = Math.Max(firstNumber.Length, secondNumber.Length);
    firstNumber = NormalizeValue(firstNumber, maxLength);
    secondNumber = NormalizeValue(secondNumber, maxLength);

    StringBuilder sb = new StringBuilder(maxLength + 1);
    int result = 0;
    for (int i = maxLength - 1; i >= 0; i--)
    {
        result += firstNumber[i] + secondNumber[i] - doubleZeroValue;
        if (result < 10)
        {
            sb.Append(result);
            result = 0;
            continue;
        }
        sb.Append(result - 10);
        result /= 10;

    }

    if (result > 0)
    {
        sb.Append(result);
    }

    char[] resultDigits = sb.ToString().ToCharArray();
    Array.Reverse(resultDigits);

    return new string(resultDigits);

}

It still has some magic numbers in it like

sb.Append(result - 10);
result /= 10;

which could/should be extracted to meaningful constants but I couldn't come up with the names lacking enough english.


Format raw bytes in hex and ascii in manner like Wireshark does

I think probably the first thing to do is decide whether you're really using C, or really using C++.

If you're really using C, then you need to get rid of the std::string, and allocate space for your return differently (e.g., using malloc).
If you're really using C++, then I'd at least consider using iostreams and manipulators to do most of the work. They are fairly verbose, but most people using C++ expect to deal with iostreams rather than raw buffers and C-style string manipulation.

I think I'd break the code up into a few more functions. For example, I'd probably have format_hex, which would repeatedly call format_line, which might in turn call some format_hex_value (or something on that order) to write out each individual value.
I'd probably avoid using the line placeholder, for a couple of reasons. The first (and probably most important) is that as you've done things right now, the last line is (as I see things) somewhat malformed. You've surrounded the ASCII part of the display with | as delimiters, but for that to make sense, you want the delimiter right next to the data, so that part of the last line should look like: |123456789|, so you immediately know there's no more data after the 9 (where your current display looks like there are space characters after the 9).
I'd definitely expand the addresses on the left out to at least 4 characters, and maybe more. In theory, you should probably be thinking in terms of 16 characters (allowing 64-bit addresses), but in all honesty I've rarely seen much point in hex dump of multiple gigabytes of data (but I certainly have seen good uses for more than 256 bytes).

Putting those together, one possibility (going the C++ route) might come out something on this order:

#include <cctype>
#include <iostream>
#include <iomanip>
#include <sstream>

struct hex {
    unsigned value;
    int digits;
public:
    hex(unsigned value, int digits) : value(value), digits(digits) { }

    friend std::ostream &operator<<(std::ostream &os, hex const &h) {
        auto oldfill = os.fill('0');

        // Yeah, iostreams get really verbose. Sorry.
        os << std::hex
           << std::setw(h.digits)
           << std::uppercase
           << std::setprecision(h.digits)
           << h.value;
        os.fill(oldfill);
        return os;
    }
};

void fmt_line(std::ostream &os, char const *data, size_t offset, size_t len) {
    os << hex(offset, 8) << ":";

    for (size_t i=0; i<len; i++) {
        os << " " << hex(data[offset+i], 2);
    }

    os << std::setw((16-len)*3 +2) << "|";
    for (size_t i=0; i<len; i++) {
        char ch = data[offset+i];
        os << (std::isprint((unsigned char)ch) ? ch : '.');
    }
    os << "|\n";
}

std::string format_hex(char const *data, size_t len) {
    unsigned lines = len/16;
    std::stringstream out;

    for (size_t line=0; line<lines; line++)
        fmt_line(out, data, line*16, 16);
    fmt_line(out, data, lines*16, len%16);
    return out.str();
}

int main() {
    char input[] = "hello world\02khgavsd \xb \xa\x5Xasjhlasbdas jalsjdn\xd  0123456789";
    std::cout << format_hex(input, sizeof(input));
}

This could use some further improvement. For one thing, it's probably not immediately obvious what some things like: os << std::setw((16-len)*3 +2) << "|"; are really doing, so they could undoubtedly use at least a little more work.