Given a number: find the closest value in a list of unique and sorted numbers with some twists

The given specification is incomplete and your implementation differs from the specification.

For example, according to your specification, test.getClosest(true, false, 99).value should be 90 instead of 110, since the distance from 99 to the closest value 90 is 9 which is "smaller/equal than [the] given delta" of 12.

Also, it is not clear how strong the given assumptions are and whether or not violations of those assumptions can occur and should be dealt with.

For example, your implementation fails on lists of less than 4 values. Now, one could say that this isn't a problem due to the assumption that a "list will contain between 10-20 values". But it is  generally considered bad practice and a more robust implementation would be recommended.

In addition to that, we don't know which parts of your interface or method signature are given and which parts are subject to review. You write that we "can ignore the Test-object-wrapper". But what about the method signature with its unorthodox choice of arguments, which seems to be required by the given specification?

For all these reasons, it is hard to provide a meaningful review.

Some notes:

getClosest(offset, next, value)

the get prefix usually indicates a lookup or simple computation. If more complex computations are required instead, I prefer using another verb such as findClosest.
Also, I recommend renaming offset to something more appropriate - it clearly isn't an offset.
Most developers would probably expect the value as the first argument, similar to built-in functions such as parseInt(string, radix) or Array.prototype.includes(value, offset).

if (null === shortest || shortest > delta) { ... }

putting the literal value on the left side of the comparison operator helps to detect some typos early on, when one accidentally uses the assignment operator = instead of the comparison operator == or === within a comparison expression. However, this also makes the comparison more difficult to read. I prefer the other way around.

const offsetA = Math.abs(closest.value - value)

this is actually a delta and not an offset. I suggest const deltaNext or similar.

let closest, comparativeValue

closest is not necessarily the closest value. It is the next larger value.
Also, consistency would demand either attaching the redundant Value suffix to both identifiers or none.
Putting each variable declaration on its own line improves readability, but I also prefer giving each declaration its own let as this simplifies modifications in the future.

if (offset === true) { ... }

instead of strict comparison, I'd simply check for a truthy value via if (offset) { ... }. This duck typing approach fits better with the language. You already use it when writing if (!offset && !next) { ... } or if (comparativeValue) { ... }.

shortest = delta

now you have closest (which is actually the next larger value), comparativeValue, shortest (which is actually the minimum delta), delta, this.delta, offset (which is actually a boolean flag) etc. It is hard to follow your naming scheme. I suggest more descriptive and more consistent naming.
Also, I wouldn't declare both an instance property this.delta and a local variable delta with different semantics.

Further suggestions:

It is not obvious to me why the arguments this.values and this.delta are given as instance properties and defined within the constructor function. By doing so, you create a stateful object which is more difficult to understand and test than e.g. a simple 'pure' function.
Also, by setting the next flag, the semantics of your method are no longer compatible to the meaning of getClosest. How about two methods findClosestEntry and findCeilingEntry? The Entry suffix indicates that the return value is a complex object containing index and value, comparable to e.g. Array.prototype.entries or Object.entries. Those established methods iterate or return [index, value] arrays instead of {index, value} objects, so you might want to consider following this established pattern, too.
Instead of passing an offset flag and relying on instance properties this.delta and this.values I suggest a method signature such as findClosestEntry(array, element, delta) and passing (or not passing) a delta argument.
I would replace the many for-loops with a single const nextIndex = values.findIndex(element => element > value). You would then have to lookup const prevValue = values[nextIndex - 1] and const nextValue = values[nextIndex] and return either one depending on the given flags. Don't forget to test for the corner case when nextIndex === -1 and consider handling it appropriately.
If you had to handle more than 20 values, I'd implement a binary search and - if the number of queries for a given array of values is large, built a binary search tree first. This would improve runtime complexity from linear to logarithmic. But for just up to 20 values, the built-in Array.prototype.findIndex or even an explicit for-loop is surely faster.


Iterate on x, not y
This computation loop:

for (int y = 0; y < params->ctx->height; y++) {
    p = params->x * 3 + y * params->ctx->rgbFrame->linesize[0];
    r = params->ctx->rgbFrame->data[0][p];
    g = params->ctx->rgbFrame->data[0][p + 1];
    b = params->ctx->rgbFrame->data[0][p + 2];
    params->ctx->data[(params->x / 128) + (params->ctx->width / 128) *
          (y / 128)][((params->x % 128) + 128 * (y % 128))] = matchColor(r, g, b);
}

is inefficient because you are looping over y whereas your arrays are stored in x order.  For example, from the first iteration to the next, you will be reading from:
(y = 0) params->ctx->rgbFrame->data[0][0]
(y = 1) params->ctx->rgbFrame->data[0][linesize]

If you had iterated over x, you would be reading from:
(x = 0) params->ctx->rgbFrame->data[0][0]
(x = 1) params->ctx->rgbFrame->data[0][3]

Similarly, you are writing to:
(y = 0) params->ctx->data[0][0]
(y = 1) params->ctx->data[0][128]

If you iterated over x, you would be writing to:
(x = 0) params->ctx->data[0][0]
(x = 1) params->ctx->data[0][1]

There are two reasons why accessing nearby addresses is faster:

You will be utilizing the CPU cache efficiently by reusing the same cache lines instead of causing lots of cache misses by accessing memory all over the place.
Since your program is multithreaded, your threads will stop contending on the same cache lines.  In other words, right now each of your threads is writing to the same cache lines as each other thread, because they are writing to neighboring addresses in the data array.  By switching to x order, your threads will each write to their own separate rows in the data array, which means they will be writing to different cache lines from each other (for the most part).  This will reduce cache contention and speed things up.


I don't much about Docker, so I can't comment much on that.
I've read through the file and the steps seem to make sense.
I can comment on some details.

The comment here doesn't match what the code does,
because the find command will only delete files like .gitignore and .gitattributes, but the .git directory itself with the full history remains:

# Copy sources without version control
RUN git clone --branch=v2.0.1 \
    https://my_name:my_key@bitbucket.org/app/repository.git . \
    && find . -name ".git*" -type f -delete

If you don't need the version control history,
perhaps you can use a zip file release instead of cloning.
Or, you might want to change the find command to delete the .git directory too,
by dropping the -type f condition.

The sed commands here duplicate the variable names,
seem overcomplicated to use \S* instead of simply .*,
can be more strict to not perform the replacement in comment lines,
and can be combined into a single command:

RUN sed -i 's/APP_ENV=\S*/APP_ENV=production/' .env && \
    sed -i 's/APP_DEBUG=\S*/APP_DEBUG=false/' .env &&

Like this:

RUN sed -ie '/^APP_ENV=/s/=.*/=production/' -e '/^APP_DEBUG=/s/=.*/=false/' .env


Display relevant contents if radio button is clicked using knockout.js

Not sure how much better it is, but some would say it could look nicer to intialize everything to false, then only change when true.  Like so:

self.print_size_radio.subscribe(function(p) {

   self.print_size_standard(false);
   self.print_size_13_19(false);
   self.print_size_contact(false);
   self.print_size_custom(false);

   if (p == 'Standard') {
      self.print_size_standard(true);
   }
   else if (p == '13 x 19') {
      self.print_size_13_19(true);
   }
   else if (p == 'Contact Sheet') {
      self.print_size_contact(true);
   }
   else if (p == 'Custom Size') {
      self.print_size_custom(true);
   }
});


Homebrew std::string for use with kernel

In operator=(), you should always first check to see whether you're doing a self-assignment and do an early exit:

fixed_string &operator =(const fixed_string &other)
{
    if (this == &other) {
        return *this;
    }
    assign(other._buffer, other._length);
    return *this;
}

I would write the found assignment as the more explicit:

if (*buffer == other[found]) {
    found++;
} else {
    found = 0;
}

The compiler will generate the equivalent code to yours.

In fact, your find has a bug. Consider:

fixed_string<10> a = "abcabcd";
assert(a.find("abcd") == 3);

Your assign method calls strlcpy incorrectly. Instead of calling with _length as the third parameter, use the actual size of the buffer:

strlcpy(_buffer, string, sizeof(_buffer));

As a matter of style, I would always surround conditional blocks with braces, even if they only contain one statement:

bool operator ==(const fixed_string &other) const
{
    if(_length != other._length) {
        return false;
    }
    // ...


Graceful way to find combinations in JavaScript

You can write this better.  The best way to explain it is to see the code example in Python's itertools module:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

This generates the combinations of length 'r' efficiently using counting.  You can create all combinations by either adding length-1 'nulls' to the pool or just iterating over the lengths.

Combination generation is a bit hard to grok, and really you should step through this example until you get it.  It's a variation on the idea of manually counting used throughout many algorithms.

The base idea for combinations('ABCD', 2) is to start with 'AB' (first yield), increment the last letter 'AC' then 'AD' with the for j loop doing nothing, on the next loop i will be the index 0, so 'A' -> 'B' and the second resets to one more than the first character and you yield 'BC'.

Trace the code.  Keep hacking!  Keep notes.


Window Factory and Manager using MVVM pattern

Disclaimer: I haven't really used MVVM though am familiar with the pattern.

WindowFactory

The layers in MVVM, from upper to lower in terms of direction of dependencies (dependencies flow down), are View, ViewModel, and Model. Therefore it seems wrong to me that the ViewModel contains a View (by way of containing a ViewAdapter).

Another issue is that CreatePhoneWindow() actually displays the window. I would expect a factory to return a window, which the client can then display (or not) as and when desired. This isn't to say it is wrong, but it feels wrong (to me).

WindowManager

if (_windows.Contains(window) == false) is unnatural; use if (!_windows.Contains(window)) instead. Same for the comparison against true in the other method.

if (_windows.Count == 0) { return true; }
else { return false; }

This also can be simplified to return _windows.Count == 0;. (But is it correct that when the _windows collection is empty it means windows are open?)

Also why are you using an ObservableCollection? It appears you're not binding to it, being as it's a private field, so why not just use a standard List<Window> instead?

ViewAdapter

  Its purpose is to handle View close commands, that are coming from
  inside the View's ViewModel...

I don't understand why this class exists. If a ViewModel wants to say "time to close", it can raise an event. The View (Window) - which should have a dependency on the ViewModel - can subscribe to this event, and close itself. No need for an extra class to do its own closing. If you still want to have a WindowManager, then the WindowManager can subscribe to the Window's OnClose event and remove that object from its collection.


When you're writing code for educational purposes (or sometimes other purposes), verbose is good because it helps you understand what's really going on. So making the code shorter or snappier or whatever is not necessarily going to make it better.

With that disclaimer out of the way: one of the most common ways to condense Python code is to use list comprehensions or generators instead of loops. A list comprehension is what you use when you're constructing a list element by element: in its simplest form, instead of this,

the_list = []
for something in something_else:
    the_list.append(func(something))

you write this:

the_list = [func(something) for something in something_else]

If you're doing something else instead of creating a list, you can have Python create an object that generates the elements on demand, rather than actually creating a list out of them. An object of that sort is called a generator and you can create one like this:

the_generator = (func(something) for something in something_else)

You can omit the parentheses when the generator is passed to another function as an argument, though.

the_sum = sum(func(something) for something in something_else)

would be equivalent to, but better than,

count = 0
for something in something_else:
    count += func(something)

There are a lot of functions in Python that take iterables (list, generators, etc.) and "condense" them into one value using some sort of operation. You can also create your own, corresponding to whatever you would be doing to the result of the loop. You can convert most loops into generator expressions this way.

So let's investigate how you could use a generator to represent the sequences of consecutive throws in each trial. You can create a generator that produces 10 random numbers easily:

(random.random() for i in xrange(10))

(this is for Python 2.x; xrange was renamed to range for Python 3). Or you can create a generator that produces 10 random values which are either 0 or 1:

(random.randint(0,1) for i in xrange(10))

That saves you from having to check each random number against 0.5. In fact, you could produce a generator that produces 10 randomly chosen words, "Heads" or "Tails", like so:

(random.choice(("Heads","Tails")) for i in xrange(10))

but it'll be easier to stick with numbers. (It's usually better to represent things with numbers or objects than with strings.)

But perhaps you're thinking, "why are you telling me to make 10 numbers when I only have to check until I find a group of four consecutive heads?" For one thing, if you're just flipping 10 coins each time, it really doesn't matter because you'll make the computer flip at most 6, and on average 3, extra coins in each trial. That doesn't take very long - it'll extend the runtime of this part of your program by 50%, but we're talking 50% of a fraction of a second. It's not worth the effort to figure out how to do it for such a small number of flips. But if each flip had, say, a billion trials, then you would definitely want to stop early. Fortunately, a generator can do this for you! Since generators produce their elements only on demand, you can stop taking elements from it once you get what you want, and not waste much of any computation. I'll address this more later.

Anyway, suppose we have our generator that produces 10 binary values 0 (tails) or 1 (heads). Is there a way to go through this and check to see whether there is a sequence of four or more heads? It turns out that just such a function is provided in itertools.groupby, which takes any iterable (list, generator, etc.) and groups consecutive identical elements. An example of its usage is

for k, g in itertools.groupby([1,0,0,1,1,1,1,0,0,0]):
    print k, list(g)

and this would print out something like

1 [1]
0 [0,0]
1 [1,1,1,1]
0 [0,0,0]

So you can check for four or more consecutive heads by just looking at the length of the group and whether the key is heads or tails.

for k, g in itertools.groupby(random.randint(0,1) for i in xrange(10)):
    if k and len(g) >= 4:
        # got a run of 4 or more consecutive heads!
        # wait, what now?

(In Python, 1 is true and 0 is false in a boolean context, so if k is equivalent to if k == 1.) OK, what shall we do with our run of 4 or more consecutive heads? Well, you're trying to find the number of trials in which this occurs. So it probably makes sense to set a success flag if this happens.

success = False
for k, g in itertools.groupby(random.randint(0,1) for i in xrange(10)):
    if k and len(g) >= 4:
        success = True
        break # this stops asking the generator for new values

But wait! This is starting to look a lot like the kind of loop that can be converted to a generator expression, isn't it? The only catch is that we're not adding anything up or constructing a list. But there is another function, any, that will go through a generator until it finds an element which matches a condition, and that's just what this for loop does. So you could write this as

success = any(k and len(g) >= 4 for k, g in
                itertools.groupby(random.randint(0,1) for i in xrange(10))

Now finally, you'll want to count how many times this happens over, say, 10000 trials. So you might write that as something like this:

successes = 0
for i in xrange(10000):
    if any(k and len(g) >= 4 for k, g in
                itertools.groupby(random.randint(0,1) for i in xrange(10)):
        successes += 1

But of course, we can also convert this to a generator, since you're just adding up numbers:

successes = sum(1 for i in xrange(10000)
      if any(k and len(g) >= 4 for k, g in
              itertools.groupby(random.randint(0,1) for i in xrange(10)))

The generator produces a 1 each time it finds a group of 4 consecutive 1s among the 10 random numbers generated.

The last thing you'd want to do is divide by the total number of trials. Well, actually, what you really want to do is calculate the average instead of the sum, and in some places you can find a function mean which is kind of like sum except that it calculates the mean instead of the total. You could use such a function if you had it. But I don't know that one is in the Python standard library, so you can just do the division:

probability = sum(1 for i in xrange(10000)
      if any(k and len(g) >= 4 for k, g in
        itertools.groupby(random.randint(0,1) for i in xrange(10))) / 10000

So the task you're trying to accomplish can actually be written in one line of Python. But it's a rather complicated line, and I wouldn't necessarily recommend actually doing this. Sometimes it's good to use a good old fashioned for loop to keep the code clear. More often, though, it's better to split your code up into modular pieces that are more useful than just what you're using them for.


It seems that RippeR isn't going to write a full answer, so here's my take (especially as my comments to another answer got deleted together with the little jewel that proposed std::unordered_map).

First of all, the performance charactistics of a small function like hex digit conversion depend heavily on the context where it is used, and so it's impossible to say what's fastest until a concrete usage context has been specified.

The problem of hex digit conversion is a bit special in that it has a particular solution - the lookup table - which has excellent performance characteristics across a wide range of usages, and the smallest possible code footprint at the same time. It does, however, impose a bit of overhead for the initialisation of the lookup table, either in the form of static initialisation or initialisation with code.

Anyway: regardless of how the lookup table gets initialised, it will usually be used via a litte function wrapper (or member function, if wrapped in a class):

enum {  NOT_A_DIGIT = (1 << CHAR_BIT) - 1  };
typedef unsigned char byte;
byte DigitValue[1 << CHAR_BIT];

// ...

unsigned hex_digit_value_v3 (char c)
{
   return DigitValue[byte(c)];
}

The cast to byte (i.e. unsigned char) is necessary because char can be - and often is - signed.

Modern compilers will usually inline the code even if it resides in a .cpp somewhere, so there's no need to get cute. In an actual implementation the lookup table could be integrated with the character classification table for the scanner/lexer, but here I filled all non-digit slots with NOT_A_DIGIT. For completeness' sake, here's the initialisation code I used:

void set_lookup_range_ (byte base_value, char lo, char hi)
{
   for (byte c = byte(lo); ; ++c)
   {
      DigitValue[c] = byte(base_value + (c - byte(lo)));  // cast needed since ari widens to int

      if (c >= byte(hi))
         return;
   }
}

void initialise_lookup_table ()
{
   std::memset(DigitValue, NOT_A_DIGIT, sizeof(DigitValue));
   set_lookup_range_( 0, '0', '9');
   set_lookup_range_(10, 'A', 'F');
   set_lookup_range_(10, 'a', 'f');
}

It takes more space than static initialisation but it's more flexible, which is good for experimentation. It also makes the code independent from the execution character set in the sense that it's not necessary to know up front which character maps to which code point.

To get some timings I pitted the function against three other versions. To make the test realistic, I adapted a function from a high-performance scanner:

// to be called with read_ptr pointing at a hex digit; digits that don't fit into an unsigned get
// dropped quietly (i.e. they shifted out at the upper end)

template<unsigned hex_digit_value (char c)>
DECLSPEC_NOINLINE
unsigned extract_hex_unsigned (char const **read_ptr)
{
   char const *p = *read_ptr;
   unsigned value = hex_digit_value(*p);
   unsigned digit;

   while ((digit = hex_digit_value(*++p)) < 16)
      value = (value << 4) + digit;

   *read_ptr = p;

   return value;
}

Besides allowing tests with a bunch of 8-digit hex strings, it can also be called with huge strings to get a different take on performance characteristics. Excess digits are lost because they get shifted out but hex_digit_value() gets called for each of them and that's what matters for the timings.

The first contender is the OP's own solution:

unsigned hex_digit_value_v0 (char c)
{
   if (c == '0')  return  0;
   if (c == '1')  return  1;
   // ... 18 more not shown ...
   if (c == 'e')  return 14;
   if (c == 'f')  return 15;

   return NOT_A_DIGIT;
}

The second contender looks almost the same but it uses a switch statement instead of conditionals. If you think that it has little merit then you may be in for a little surprise when you look at the timings:

unsigned hex_digit_value_v1 (char c)
{
   switch (c)
   {
      case '0':  return  0;
      case '1':  return  1;
      // ... 18 more not shown ...
      case 'e':  return 14;
      case 'f':  return 15;
   }

   return NOT_A_DIGIT;
}

Last but not least, a reasonably straightforward solution where I lent helping hand to the compiler regarding the math (something we used to do a lot with older compilers):

unsigned hex_digit_value_v2 (char c)
{
   switch (c)
   {
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
         return byte(c - '0');
      case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
         return byte(c - 'A' + 10);
      case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
         return byte(c - 'a' + 10);
   }

   return NOT_A_DIGIT;
}

Note, however, that this depends on three character ranges being contiguous and hence might not work with execution character sets that aren't based on ASCII and its descendants. The other three solutions are completely immune to such problems.

The test frame fills a big string with random hex digits (including upper case and lower case) or with a given number of 8-digit words separated by a blank. Timings are taken with the Windows high performance counter, which is essentially the CPU's time stamp counter divided by 256.

At this low resolution the fastest version needed only 3 ticks to go through a thousand digits, hence the big test data sizes. Using the TSC directly would have been better but then the code wouldn't have been portable across compilers.

In order to exclude to vagaries caused by caches and task switches, each test was repeated a number of times and the median of the measurements returned as result. This also means that the times that got printed refer to hot caches. A global sink variable was used to make the compiler think that the produced values were actually used somehow, to keep it from simply eliding the code altogether or reducing it to bumping the read pointer.

template<unsigned digit_value_vx (char c)>
double test_m (unsigned repeats = 10)
{
   std::vector<zrbj::Timer::Ticks> measurements;
   zrbj::Timer t;

   for (unsigned repeats_left = repeats; repeats_left--; )
   {
      char const *p = test_string.c_str(), *e = p + test_string.length();
      unsigned x = 0;
      t.Start();
      while (p < e)
      {
         x += extract_hex_unsigned<digit_value_vx>(&p);
         ++p;  // skip the character that caused the scanning to stop
      }
      t.Stop();
      g_sink += x;
      measurements.push_back(t.Elapsed());
   }

   std::sort(measurements.begin(), measurements.end());

   return t.ms(measurements[measurements.size() / 2]) * 1000;
}

So here's the timings in microseconds for three compilers; the test sizes are given as (number of strings) x (string length).

*** BC++ 7.10 (RX/Seattle) 64 *** CLANG 3.3.1 (35465.f352ad3.17344af)

1 x   1000:           9.9 v0         13.2 v1          4.2 v2          1.9 v3
1 x  10000:         135.4 v0        147.6 v1         87.9 v2         18.9 v3
1 x 100000:        1359.6 v0       1472.6 v1        964.4 v2        192.5 v3
   100 x 8:           7.4 v0         10.6 v1          3.5 v2          1.9 v3
  1000 x 8:         110.4 v0        114.2 v1         74.1 v2         18.9 v3
 10000 x 8:        1124.5 v0       1182.5 v1        825.2 v2        183.5 v3

*** VC++ 12.0 (x64) *** RTTI _CPPUNWIND 180031101.0

1 x   1000:           8.3 v0          5.5 v1          2.2 v2          0.6 v3
1 x  10000:         118.4 v0        122.9 v1         60.3 v2          5.5 v3
1 x 100000:        1214.6 v0       1250.9 v1        623.0 v2         51.3 v3
   100 x 8:           6.4 v0          3.5 v1          1.9 v2          0.6 v3
  1000 x 8:          96.6 v0        120.9 v1         48.1 v2          5.5 v3
 10000 x 8:         961.5 v0        995.5 v1        553.1 v2         56.5 v3

*** g++ 4.8.1 64 ***

1 x   1000:           3.2 v0          0.6 v1          1.3 v2          0.6 v3
1 x  10000:          88.9 v0          6.7 v1         45.9 v2          5.5 v3
1 x 100000:         940.3 v0         70.3 v1        484.8 v2         52.6 v3
   100 x 8:           2.2 v0          0.6 v1          1.3 v2          0.3 v3
  1000 x 8:          67.1 v0          5.8 v1         33.4 v2          3.2 v3
 10000 x 8:         723.5 v0         58.7 v1        390.4 v2         33.4 v3

As you can see, the version with the lookup table (v3) performs best with all three compilers. And gcc manages to make v1 (with the simple switch case '0': return 0; and so on) almost as fast as the lookup-based version. I was a bit disappointed with the other two for not doing the same, though. VC++ is normally quite decent at sorting out the messy stuff under the hood without a lot of hand-holding by the programmer, and I'd have expected more of Emborlandero's clang-based compiler, after the long years of waiting for it.

As regards code size, v3 wins hands-down as it compiles to at most two machine instructions and so there's no need to keep over-eager compilers from bloating the code with overly aggressive inlining.


Let's start from your code. The recursion can be implemented in a much clearer way if the method returns the collection of all child folders, instead of updating parent folder's ChildItems collection. In this case it could look as simple as

private IEnumerable<Node> GetChildFolderNodes(IRepository<Folder> folderRepo, int folderId)
{
    var childFolders = folderRepo.FindByExp(f => f.ParentFolderID == folderId).ToArray();

    return childFolders.Select(folder => new Node
    {
        Id = folder.FolderID,
        ParentId = folder.ParentFolderID,
        DisplayText = folder.FolderName,
        DefaultState = false,
        ChildItems = GetChildFolderNodes(folderRepo, folder.FolderID).ToList()
    });
}

There are a number of articles describing why a IRepository<T> is quite a bad idea when defined on top of ORM framework. Main reasons are leaked abstractions and abstraction on top of abstraction. And your example shows why - any optimization requires the knowledge of underlying implementation (Entity Framework).

Running this process in multiple threads may help, but will put additional load on the database server and thus is not scalable. Note that Entity Framework's DbContext is not thread-safe, so you cannot share the IRepository in multiple threads unless you spin up a new DbContext per request there (which I wouldn't recommend doing).

Assuming that you're using Entity Framework 6.0, FindByExp method returns IQueryable<Folder>, you can try asynchronous implementation of the data retrieval:

private async Task<List<Node>> GetChildFolderNodesAsync(Func<IRepository<Folder>> folderRepoFactory, int folderId)
{
    Folder[] childFolders;
    using (var folderRepo = folderRepoFactory())
    {
        childFolders = await folderRepo.FindByExp(f => f.ParentFolderID == folderId).ToArrayAsync();
    }

    return (await Task.WhenAll(childFolders.Select(async folder => new Node
    {
        Id = folder.FolderID,
        ParentId = folder.ParentFolderID,
        DisplayText = folder.FolderName,
        DefaultState = false,
        ChildItems = await GetChildFolderNodesAsync(folderRepoFactory, folder.FolderID)
    }))).ToList();
}

Note that in this case you would need to spin up a new DbContext per request (which I expressed as a repository factory).

And finally, assuming that this is a critical path in your application, the best way to optimize the code you're running is to reduce the number of round trips to database server, instead of trying to squeeze microseconds on a .NET layer.

For example, if your underlying DB engine is SQL Server, you can leverage the recursive CTE to load full folder hierarchy in one go. It can be optimized even further if CTE returns the depth level for folders, but I'll leave it for you as an exercise:

private List<Node> GetChildFolderNodesAsync(DbSet<Folder> folderSet, int folderId)
{
    var allFolders = folderSet.SqlQuery(@"WITH cte (FolderID, ParentFolderID, FolderName) AS
    (
        SELECT  FolderID, ParentFolderID, FolderName
        FROM    Folders
        WHERE   ParentFolderID = @p0
    UNION ALL
        SELECT  F.FolderID, F.ParentFolderID, F.FolderName
        FROM    Folders F
        JOIN    cte
        ON      F.ParentFolderID = cte.FolderID
    )
    SELECT  *
    FROM cte", folderId).AsNoTracking();

    //Converting all folders into nodes, but skipping the ChildItems property for now...
    var nodesByParent = allFolders
        .GroupBy(folder => folder.ParentFolderID)
        .ToDictionary(folders => folders.Key, folders => folders.Select(folder => new Node
        {
            Id = folder.FolderID,
            ParentId = folder.ParentFolderID,
            DisplayText = folder.FolderName,
            DefaultState = false,
        }).ToList());

    List<Node> childNodes;

    //Now that we have all nodes grouped by parent, we can look up and assign ChildItems for all nodes
    foreach (var node in nodesByParent.Values.SelectMany(nodes => nodes))
    {
        node.ChildItems = nodesByParent.TryGetValue(node.Id, out childNodes)
            ? childNodes
            : new List<Node>();
    }

    return nodesByParent.TryGetValue(folderId, out childNodes)
        ? childNodes
        : new List<Node>();
}


I'm pretty much a n00b to programming myself, so take my advice with a grain of salt... but I would try making each of your "get..." functions into a method of a class (let's say YoutubeVid). It's __init__ would set all the attributes at once, without printing. A seperate function, let's say print_attributes could do the printing. Once you code that part, you would replace this:

            else:
                r = requests.get(url)
                soup = BeautifulSoup(r.text)
                f.write(url+',')
                print('\t%s') % (url)
                getTitle()
                getStats()
                getDescription()
                getLinks()
                getRelated()
                f.write('\n')
                print('\n')
                visited.append(url)
                time.sleep(3)

With something like this:

            else:
                r = requests.get(url)
                soup = BeautifulSoup(r.text)
                video_page = YoutubeVid(soup)
                print_attributes(video_page)

I'm sorry I don't have the time to work out a more detailed example, but if that makes any sense to you, maybe you can give it a try and post what you come up with.

Also, a minor detail regarding function names... Mixed case like getTitle() is depricated. Lowercase with underscores like get_title() is prefered. See the PEP Style Guide.


Given two strings, a and b, determine the minimum number of character deletions required to make a and b anagrams

I'm trying to figure out how my code could be improved. I solved a HackerRank problem from the Cracking the Coding Interview section, and am thinking that it should be able to be solved a simpler than what I did.

Probably. But these hacker problems are usually very specific. You can probably google a perfect solution in 10 minutes.

  What is a better, more efficient way of solving this problem?

Create a count of the number of each letter from both strings. To be anagrams these counts must be the same. So look across the counts and sum the differences.

  I am using C++, and since strings are immutable,

No they are not. Strings are perfectly mutable.

  what I decided to do was to create two int arrays (vectors, actually) that hold the ASCII value of the chars in each string. Then I would sort the vectors. Then I would iterate through the arrays together, counting the number of elements that don't exist in the other.

The complexity of this is (ignoring the copy to a vector)

O(n1.log(n1))      // Sort first string
O(n2.log(n2))      // Sort second string
O(max(n1,n2))      // Loop Over counting.

That seems to work. I like getting the count of each letter better. The difference in the counts is the number of letters to be deleted.

O(n1)             // Count each character into an array.
O(n2)             // Count each character into an array.
O(1)              // count the diffs.
                  // There is a loop over 255 characters (26 if you only count lower case letters).
                  // This is constant and not dependant on the size of
                  // the input and thus is `1`

Code Review.

Using Namespace

Please stop doing this.

using namespace std;

Its a bad habit that will cause you grief one day. See every other C++ code review for a good explanation.

Pass by const reference

You are passing the parameters by value. This will cause both the vectors to be copied.

int calcDeletions(vector<int> a, vector<int> b) {

Since you don't modify the values it can be made simpler by passing a const reference of each parameter. Thus having no copy.

int calcDeletions(vector<int> const& a, vector<int> const& b) {

Prefer Pre Increment

            deletions++;
            ai++;

Yes. Yes. It makes no difference for integers. But it does no harm to use pre-increment on integers either. But again it's one of those habits you should get into. There are situations where it does make a difference so it's best to pre-increment and then it will always be correct (even if you change the types of your objects).

Prefer operator[] over at()

The difference between the two is that at() performs bounds checking.

    for (int i = 0; i < a.length(); i++) {
        aInt.push_back((int)a.at(i));
    }

In this context you are guaranteed that there is no out of bounds access as you are already checking that i is smaller than a.length(). Thus you are effectively doing the check twice.

Don't use C style casts.

C style casts are hard to spot.

 (int)a.at(i)
 ^^^^^

They are also extremely dangerous (they basically tell the compiler to shut up and do what you're told as I the programmer am god and know better than you the simple compiler). In reality this is usually wrong: the compiler always knows better than you and telling it to shut up is usually hiding an error message.

As a result, C++ has its own casts. There are actually four of them:

static_cast<>()
const_cast<>()
reinterpret_cast<>()
dynamic_cast<>()

Your above cast is actually best done by a static_cast<>()

static_cast<int>(a.at(i));

BUT There is no actual need to cast a char to an integer. This will happen automatically (as a char is an integer type the conversion is automatic) with no loss in precision.

Is there a need to put the largest first.

I don't see you taking advantage of this in the function above!

    // call calcDeletions function with the longer vector passed as first arg
    if (aInt.size() > bInt.size()) {
        return calcDeletions(aInt, bInt);
    }
    else {
        return calcDeletions(bInt, aInt);
    }

Looking at the Cool Shark implementation you provided it still has a couple of issues.


Extract indices of visible nodes in a tree where only some nodes are expanded

You are right to want to avoid creating the nested structure to begin with. I imagine you read my answer in the question you linked (the second one). As there, here the solution is to use mapcat instead of map. And as I also say in the comments there, while mapcat-indexed does not exist, you can just pass an extra (range) argument to get numbering.

(defn visible-nodes [tree]
  (mapcat (fn [idx ele]
            (map #(cons idx %)
                 (cons []
                       (when (:expanded ele)
                         (visible-nodes (:children ele))))))
          (range), tree))


First, I would replace the dictionary

var workoutsPerWeek = [Int: Int]()

by an array. A dictionary could be memory-saving if you have "few" keys in a "large range",
e.g. 1, 20, 300, 4000, as a "sparse-array" emulation. But that is not the case here:
The bucket numbers range from 0 to 9, so that an array is more appropriate,
easier to initialize, and easier to access (no forced unwraps needed).

It is unclear in your code how many entries are needed: You
initialize entries for 0...100, update entries for 0...9, and finally
evaluate entries 0...10. If you want to collect the data for the last 10 weeks then it would be

var workoutsPerWeek = Array(repeating: 0, count: 10)

Now you can use the computed bucket number as an index into the array and
replace the switch statement by

let rawBucket = Int((startDateInterval - workoutTimeInterval) / numberOfSecondsInAWeek)
if rawBucket >= 0 && rawBucket < workoutsPerWeek.count {
    workoutsPerWeek[rawBucket] += 1
}

The range check for the bucket number can also be done as

if workoutsPerWeek.indices.contains(rawBucket) { ... }

There are more things which can be improved: In

let workoutTimeInterval = Double((userWorkout.completionDate?.timeIntervalSinceNow)!)

the conversion to Double is not needed. And what if completionDate is nil?
Your code would crash in that case.

But my main point of criticism is how the bucket is computed.
A day does not necessarily have 24 hours. In regions with daylight saving time,
a day can have 23 or 25 hours if the clocks are adjusted one hour back or forward.
Applied to your code: A week does not necessarily have 604,800 seconds.

The proper way to compute calendar differences is to use the Calendar methods
and DateComponents:

for userWorkout in userWorkouts {
    // Ensure that completionDate is set, otherwise ignore this entry
    guard let completionDate = userWorkout.completionDate else { continue }

    // Compute #of weeks between completionDate and startDate
    let weeksAgo = Calendar.current.dateComponents([.weekOfMonth], from: completionDate, to: startDate).weekOfMonth!

    // Update corresponding bucket
    if workoutsPerWeek.indices.contains(weeksAgo) {
        workoutsPerWeek[weeksAgo] += 1
    }
}

Finally, the calculation of the number of consecutive weeks where the goal has been reached can be simplified to

let numberOfGoodBuckets = workoutsPerWeek.prefix(while: { $0 >= target }).count


Golang async but sequential enqueue with buffered channel

I believe that you are correct. The channel buffer really doesn't matter here because you are manually building an un-bounded buffer here:

go func(cbr callbackRequest) {
    queue <- cbReq
}(cbReq)

The queue <- cbReq line will block until queue has room, but since it is running in its own goroutine, it won't block progress for the entire program. Once there is room in queue, the goroutine will progress and immediately terminate, having deposited cbReq in the queue.

You can think about it as a bunch of people waiting in line to drop off packages at a post office for shipping. As the postal employee gets time, he removes the packages from the counter in the order they were brought in (maybe they are on a conveyor belt) and sends them on their way. If the counter (or conveyor belt) is large enough, several packages can be placed on it at one time. In this case, once a person has deposited her package on the counter, she may leave. If the counter was smaller, the people would have to wait in line longer, but their packages would still ship in the same order.

That is kind of a complicated analogy, but maybe it will help. The idea is that the queue either happens in the channel buffer, or in the blocked goroutines.

The one wrinkle here is that I am not entirely sure about the semantics of a blocked channel insertion operation. It appears from your output that the first goroutine to attempt to insert to a channel will be the first goroutine to be allowed to insert to that channel, but I couldn't find a reference to back that up.


Function to sort items with an array of keys

That's not how the comparison function for Array.sort() works at all: it should return negative, zero, or positive.

Eating up all or part of the props argument (due to your array.shift() call) is bad practice.

The usage is cumbersome:

array.sort(function(a,b) { return comparePropsOfAWithB(a,b,["a","b","c"]) })

Wouldn't it be nicer to write a propertyComparator(…) function that returns a function?

array.sort(propertyComparator('a', 'b', 'c'))

Something like this:

function propertyComparator() {
    var props = arguments;
    return function(a, b) {
        for (var i = 0; i < props.length; i++) {
            var aProp = a[props[i]];
            var bProp = b[props[i]];
            if (aProp < bProp) return -1;
            if (aProp > bProp) return +1;
        }
        return 0;
    };
}


C++ edit distance / string similarity function based on the Jaro-Winkler algorithm

Here are a few things that I immediately see in this code that have room for improvement:

template <typename T = float>

Assuming you only want floating point values passed as template parameters (Since you do floating point arithmetic later on), you could add:

static_assert(std::is_floating_point<T>::value,
              "jaro can only be used with floating point types");

const unsigned sl = source.length();
const unsigned tl = target.length();

While the above may work for your code, the type for the length of the std::string_view isn't always guaranteed to be a plain unsigned int. Consider using std::size_t as the variable type, or std::string_view::size_type.

auto source_matches = new bool[sl] {0};
auto target_matches = new bool[tl] {0};

The use of auto is confusing here. It is hard to tell at first glance that you are meaning to use a dynamic array. auto doesn't shorten the type much either, so you may want to remove it.
Raw dynamic arrays are a large source of error. Consider using std::vector instead. This will also allow you to remove the deletes later on in your code.

for (unsigned i = 0; i < sl; ++i)

You could use std::size_t here. Don't make assumptions about unsigned types.

delete[] source_matches;
delete[] target_matches;

Using a std::vector would allow you to remove this.

(unsigned)std::min(source.length(), target.length())

If you have to use a cast, prefer using static_cast, as it makes your intent clearer.


Validation

# validate params
window_size = int(round(window_size))
req_angles = int(round(req_angles))
window_step = int(round(window_size * (1 - overlap)))

This does... some validation, but not a lot. It will validate that the arguments are numeric, but nothing else. If you cared about validation, you should probably also check ranges, especially that the window size and step are non-negative, etc.

Numpy vectorized conditionals

This:

    for idx, val in enumerate(flattened):
        if val < lower_b:
            valley_inds.append(idx + ind)
        elif val > upper_b:
            peak_inds.append(idx + ind)

should not use a loop. Read about vectorized conditionals here:
https://stackoverflow.com/questions/45768262/numpy-equivalent-of-if-else-without-loop#45768290

Stricter events

    curr_event = 'peak'

shouldn't use a string. Use enum.Enum instead and include event values for PEAK and VALLEY.

Direct booleans

    if x in pk_inds:
        is_peak = True
    else:
        is_peak = False

should be

is_peak = x in pk_inds


Replacing certain characters in a QString

I would start by separating the data from the logic:

std::vector<std::pair<QString, QString>> replacements {
    { "/", "-" },
    { "|", ""  },
    // ...
    { "ï", "i" }
};

for ( auto const &r : replacements) {
    str.replace(r.first, r.second);
}

I'm not sure the comments about the groups of letters being replaced really add a lot though.

Then I'd at least consider moving the data out of the program itself, and into a data file the program uses, so the replacements you do can be adjusted without re-compiling the code (this is the sort of thing that frequently seems to need a fair amount of "tweaking", since there's no one way of doing it that's obviously correct and the other ways are wrong).


It looks to me like your function is actually doing 2 things:

It's checking to see if an entry exists in the dictionary, and if so return it
If it doesn't exist, then it creates a new one

So I would break it into 2 functions:

VERTICE_INDEX FindVerticeInDict(const float x, const float y,
    const ChunkGenerator::chunkConfig& cfg, VERTICE_INDEX& current_index);
VERTICE_INDEX GetOrCreateVertice(const float x, const float y,
    ChunkGenerator::chunkConfig *cfg);

Note that I made x and y constants because they aren't changed by either function. Also, in the Find method, I made the cfg argument const because it's not being changed there either. It is modified in GetOrCreate though, so I left it as a pointer. (It could also be a non-const reference, if you prefer that style.)

I would create a named constant for the "entry not found" value:

const VERTICE_INDEX ENTRY_NOT_FOUND = 0xFFFF;

So it would look something like this:

VERTICE_INDEX FindVerticeInDict(const float x, const float y,
    const ChunkGenerator::chunkConfig& cfg, VERTICE_INDEX& current_index)
{
    int x_pos = int((x*POSARR_ADJ_F) + 0.5f);
    int y_pos = int((y*POSARR_ADJ_F) + 0.5f);

    int dict_index = x_pos + (y_pos * cfg.subdivisions_adj);

    VERTICE_INDEX dict_entry = cfg.vertice_pool.vertice_dict[dict_index];
    current_index = cfg.vertice_pool.current_vertice_index;

    if (dict_entry >= 0 && dict_entry < ENTRY_NOT_FOUND && current_index > 0)
        return dict_entry;

    return ENTRY_NOT_FOUND;
}

For your vertex array, you really should create a struct that contains the members you're going to use rather than looking them up in a 1D array of floats. It's error prone, hard-to-read, and hard-to-maintain the way you're doing it now. I'd create a struct like this:

typedef struct Vertex {
    Point3D vertex_coord; // This might be the same as LVecBase3f?
    Point2D texture_coord; // This might be the same as LVecBase2f?
} Vertex;

Where Point3D is just:

typedef struct Point3D {
    float x;
    float y;
    float z;
} Point3D;

and Point2D just has an x and y float values. Doing this will allow you to remove the magical pool_index = ((int)current_index) * 5;, and have names for the values you're writing.

Also, you don't need to use the inline directive. The compiler can decide to ignore it, and it can decide to make something you didn't mark as inline inline. So there's not a lot of reason to use it.

You can reduce the verbosity of your code, and possibly reduce the number of pointer dereferences the compiler produces by getting the address of the vertex you want and assigning all its members through that one pointer.

Given the above, your function would now look like this:

VERTICE_INDEX GetOrCreateVertice(const float x, const float y,
    ChunkGenerator::chunkConfig *cfg)
{
    VERTICE_INDEX current_index = 0;
    VERTICE_INDEX dict_entry = FindVerticeInDict(x, y, *cfg, current_index);
    if (dict_entry != ENTRY_NOT_FOUND)
        return dict_entry;

    LVecBase3f* offset      = cfg->base_position;
    LVecBase2f* dim         = cfg->dimensions;
    LVecBase2f* tex_offset  = cfg->texture_offset;
    LVecBase2f* tex_scale   = cfg->texture_scale;

    float base_scale = 1.0 / (cfg->subdivisions_f-1.0);
    float x_scaled = x * base_scale;
    float y_scaled = y * base_scale;

    Vertex* vertex = &cfg->vertice_pool.vertice_arry [ current_index ];
    vertex->vertex_coord.x = offset->get_x() + (x_scaled * dim->get_x());
    vertex->vertex_coord.y = offset->get_y() + (y_scaled * dim->get_y());
    vertex->vertex_coord.z = offset->get_z();
    vertex->texture_coord.x = tex_offset->get_x() + (x_scaled * tex_scale->get_x());
    vertex->texture_coord.y = tex_offset->get_y() + (y_scaled * tex_scale->get_y());

    cfg->vertice_pool.vertice_dict[dict_index] = current_index;
    cfg->vertice_pool.current_vertice_index++;

    return current_index;
}


I already posted the incremental improvement answer. Here's the home run answer.

Consider the number 4,666,777. This number happens to chain into 89. That takes some amount of work to figure out. But eventually we get there. What does this tell us? Since we're only interested in the sum of the squares of the digits, the actual ordering of the digits is irrelevant. That is... once we know that 4,666,777 is valid, we also know that 6,466,777 is valid, and 7,664,776 is valid, and ... All 140 unique permutations of the digits 4666777 are things we want to count. The key is: once we're done with 4666777, we do not even need to consider the other 139!

There are only 11,440 unique digit combinations from 1 to 10,000,000. Any solution checking all of them is thus doing ~900x more work than necessary. We can use itertools.combinations_with_replacement to get the unique digit combinations, and then use itertools.groupby to help determine how many such combinations there are.

Still with the memoized my_square_chain:

def euler89():
    count_89 = 0
    fact7 = fact(7)
    digits = range(10)

    for num in itertools.combinations_with_replacement(digits, 7):
        cur = sum(d**2 for d in num)
        if cur > 0 and my_square_chain(cur) == 89:
            count = fact7
            for _, g in itertools.groupby(num):
                count /= fact(len(list(g)))
            count_89 += count
    return count_89

This runs in 0.120s on my box. A performance improvement of 265x from my incremental changes, and 381x from the original solution.


Interesting question,

I will not comment on making this more rails-like, I have no clue there. But I can observe that you in essence do 3 things: so you could perhaps group your error handling into 3 locations.

Furthermore, I want to point out that your code handles some error situations silently, that's never a good idea.

Other than that the code is very straightforward and easy enough to follow.

For my counter proposal I would start with a function that takes a request and checks for mandatory fields:

function validateMandatoryRequestFields( req , fields ){
  for( var i = 0 ; i < fields.length ; i++){
    if( !req.body[fields[i]] ){
      return fields[i] + ' was not provided';
    }
  }
  return '';
}

So that your function can do something like this in the beginning:

exports.updateUser = function(req, res, next) {
  //Do we have all we need ?
  var mandatoryFields = [ 'password', 'name' , 'email' ],
    errorMessage = validateMandatoryRequestFields( req , mandatoryFields );
  //Do we have what we need ?
  if(errorMessage){
    return next(errorMessage);
  }

You should always make sure that the request has what you need upfront.

Then, for callbacks I tend to mangle the err handling and bogus data handling into 1 if statement with 1 return statement:

  //Encrypt password
  User.passwordToSecretWithBcrypt(req.body.password, function(err, secret) {
    if (err || !secret ) {
      return next(err || new Error('Password encryption failed') );
    }

If you keep applying this to all of the code, you end up with something like this:

function validateMandatoryRequestFields( req , fields ){
  for( var i = 0 ; i < fields.length ; i++){
    if( !req.body[fields[i]] ){
      return fields[i] + ' was not provided';
    }
  }
  return '';
}

exports.updateUser = function(req, res, next) {
  //Do we have all we need ?
  var mandatoryFields = [ 'password', 'name' , 'email' ],
    errorMessage = validateMandatoryRequestFields( req , mandatoryFields );
  //Do we have what we need ?
  if(errorMessage){
    return next(errorMessage);
  }
  //Encrypt password
  User.passwordToSecretWithBcrypt(req.body.password, function(err, secret) {
    if (err || !secret ) {
      return next(err || new Error('Password encryption failed') );
    }
    //Find user
    User.findById(req.user.id).exec(function(err, user) {
      if (err || !user){
        return next(err || new Error('no user found'));
      }
      //Update user
      user.save(function(err, user) {
        if (err || !user) {
          return next(err || new Error('user not saved') );
        }
        res.json(user);
      });
    });
  });
};


Generic wrapper with variable number of arguments

private <R, A1, A2, A3> R executeCommand(Command<R, A1, A2, A3> command) {
    R result = null;
    for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
        try {
            return command.execute(command.getBundle());
        } catch (Exception e) {
            logger.error("Exception during performing operation, retrying for the " + attempt + " time", e);
            sleepForNMinutes(attempt);
            loginToApp();
        }
    }
    return result;
}

You never set result outside the initial declaration.   So you could just get rid of the declaration and return null at the end.

You retry on any exception, but the only retry condition that you mention is a disconnect.  Why not create a DisconnectException and only catch that?  The current code will retry things like command being null or a divide by zero error, even though those will never succeed.

You sleep and log into the app after the final attempt.  Why?  What happens if the log in action fails?  What happens if the exception isn't caused by something that breaks the login session?

You sleep for 0 minutes after the first attempt.

You log that you are retrying for the 0, 1, or 2 time.  That's incorrect.  Particularly on the last time, when you don't retry.  The grammar also doesn't quite work.

private <R, A1, A2, A3> R executeCommand(Command<R, A1, A2, A3> command) {
    int attempt = 0;
    while (true) {
        try {
            return command.execute(command.getBundle());
        } catch (DisconnectException e) {
            logger.error("Exception while performing operation, attempt " + ++attempt, e);
        }

        if (attempt >= MAX_ATTEMPTS) {
            return null;
        }

        sleepForNMinutes(attempt);
        loginToApp();
    }
}

This version does give up using a for loop to track the attempts.  This allows us to move the end condition to the middle of the loop rather than the beginning.  This may or may not be what you want.  But if you do, this is one way you could do it.


A large number of math type equations and functions in a python module

Am I doing this right?

Almost.

  as in is this the best practice to code utility functions?

These aren't "utility" functions.  They appear to be central to your app.  There are rarely "utility" functions in any app.

What we used to call "utility" functions are almost always part of a standard library.

  should I be separating all the mini calculations into separate functions

Yes.

  but then have to deal with 200 functions instead of the current 50?

You still have the calculations.  You're just giving them names and keeping them separate.  Giving them separate names makes them more reusable, easier to test and easier to find.

The most important thing here is to avoid creating a (nearly) useless class who's only job is to contain a bunch of functions.

Your code uses no instance variables and simply uses another function that happens to be in the class.  Both of these could be @staticmethod method functions.

There's no reason -- in Python -- to create a class unless you have instance variables and a change in state of some kind.

[In Java, you must often create "all-static" classes because there's no other place to put stateless math like this.]

You can simply put these functions into a simple module and avoid the class definitions.


Script for saving/sorting/sending emails based on their subject

Readability

Proper indentation is important for readability. Everything inside of Sub...End Sub should be indented one tab (or four spaces). Else If statements should line up with their corresponding If statements. For example:

Public Sub foo
    dim variable as boolean
    If variable Then
        'do something
    Else
        'do something different
    End If
End Sub

Variable and routine names are overly abbreviated. We're no longer in the bad ol' days when the length of variable names were limited. Instead of attName, try attachmentName. Apply this to all of your variable names and Mr. Maintainer will thank you.
As a matter of opinion, Sub and Function names should be PascalCase. Instead of saveattachtodisk, try SaveAttachmentToDisk. I do like that you're following the verb-noun naming schema for them though. You did a good job there.
Back to over abbreviation. There are single letter parameter names. They tell me nothing about what I'm supposed to pass into them.

Functionality

What happens if "C:\Users\USER\Desktop\Staging" doesn't exist on the client machine? The code crashes. Adding some error handling in will help, but the routine should also either let the user pick a folder, or build the directory itself. It's looks like it's a temporary structure, so I recommend the latter.
Let's talk about this section for a minute.

If whatIs = "PDF" Then
    objAtt.SaveAsFile saveFolder & "\" & UCase(saveName) & ".pdf"
ElseIf whatIs = "DOC" Then
    objAtt.SaveAsFile saveFolder & "\" & "DOC 14-" & stripNums(saveName) & ".pdf"
    emailAttach = saveFolder + "\" + "DOC 14-" + stripNums(saveName) + ".pdf"
    attName = stripNums(saveName)
    sendDOC emailAttach, attName
ElseIf whatIs = "other" Then
    objAtt.SaveAsFile saveFolder & "\" & saveName & ".pdf"
End If

This works great for now, but what happens when I want to expand it to include other document types? I'm thinking a DocType enum could go a long way toward making it easier to extend, as well as improve readability.

Public Enum DocType
    PDF
    DOC
End Enum

Select Case whatIs
    Case PDF
        objAtt.SaveAsFile saveFolder & "\" & UCase(saveName) & ".pdf"
    Case DOC
        objAtt.SaveAsFile saveFolder & "\" & "DOC 14-" & stripNums(saveName) & ".pdf"
        emailAttach = saveFolder + "\" + "DOC 14-" + stripNums(saveName) + ".pdf"
        attName = stripNums(saveName)
        sendDOC emailAttach, attName
    Case Else
        objAtt.SaveAsFile saveFolder & "\" & saveName & ".pdf"
End Case

The "Doc 14-" string show up a lot. Store it in a constant at the module scope.
saveFolder should be a constant at the procedure scope. If it doesn't change, declare it as a constant so Mr. Maintainer doesn't try to assign it a new value at runtime in the future.
You can break out of the for loop in isPDF() as soon as it finds the value it's looking for. There's also no reason for the returnValue variable to exist. Just assign the function value directly. Booleans are implicitly false upon creation, so isPDF() could look more like this.

'Checks to see if document is PDF type docement
Function isPDF(s As String) As Boolean
    For i = 1 To Len(s)
        If Mid(s, i, 2) = "1f" Then
            isPDF = True
            Exit For
        End If
    Next
End Function

There are probably a couple of other things that could be said, but I'll leave those to another reviewer.


How can I refactor Api::SessionsController?

Put the common error methods in a Module and include it in each Controller where you need them (in a similar way like you already include Devise::Controllers::Helpers, but this time with your own namespace and module name.)

As for the method signatures

def error type, context=nil
def error_message type, context
def render_status state

it's common to leave the parenthesis out when calling class methods in class context (because they oftentimes make up a nice DSL), but please don't do it when defining methods, that can lead to annoying ambiguities.


sscanf is not safe

It's not part of your stack but part of your driver code, but scanf() is not a good function to use.  There are many reasons for this, but the basic problem in this case is that if the user enters a letter rather than a digit for input in push() for example, the program will loop forever.

Better, in this case, would be to use something like getchar().

separate stack operations from input/output

Having a function like push() only do one thing (pushing an item to the stack) is generally better design because it makes it easier to re-use your code.  In this code, push() cannot be easily re-used because it is tied directly to user I/O.  Better would be to cleanly separate all stack operations from the I/O to better foster re-use.

operations should operate on passed parameters

In this code, there can only be one stack because it's globally defined and used by all stack operation functions.  A better scheme would be to pass the address of the stack structure to each function to make it more flexible and more general.

Additionally, a function like push() should also require an argument that speccifies what is to be pushed onto the stack, and a function like pop() should return either a copy of or a pointer to the data item that was popped from the stack.

use C idioms to make the code shorter and easier to read

Writing code such as

s.top = s.top + 1;
s.stk[s.top] = num;

is not incorrect, but is not idiomatic C.  The C way of writing that would be

s.stk[++s.top] = num;

Writing code in this way will make it easier for others to understand you, in the same way that speaking, say, idiomatic Italian will make it easier for native Italian speakers to understand you.

avoid non-portable code

The clrscr() call is not in <stdio.h> and is not portable.  I had to comment out that line to get the code to compile and run.  Ideally, you'd avoid all non-portable code.  If you can't avoid that, however, you should state what dependencies the code has and also include the header files that clearly indicate those dependencies.

think about the user of your code

It's good that you avoided using "magic numbers" and instead you wisely chose to define MAXSIZE to indicate the size of your stack.  However, it would be useful to have a comment indicating what it's for, and also to maybe rename it to something a little more descriptive, such as MAXSTACKSIZE.

avoid single-letter variable names

While i or j might be perfectly fine variable names for looping indexes, naming your stack s is not very user-friendly.  We are long beyond the days that each line of code had to fit on an 80-character punch card!

I hope these items inspire you to write more code, and to strive to continuously improve the quality of the code that you write.


Scrabble helper: find the highest score with any 7 letters

Your algorithm appears to be "generate all possible permutations of the tiles and check to see which are legal scrabble words".  That's a very inefficient way to solve the problem.

A better way is to construct a new dictionary which is a map from letter-sorted strings to legal words.  For example, suppose your dictionary is BAD, DAB, OPTS, POTS, STOP. You want to construct a map:

ABD --> { BAD, DAB }
OPST --> { OPTS, POTS, STOP }

Now when you have a rack and you're looking to see what words it forms you sort the rack by letter order first and then you only have to consider the combinations and permutations of letters in alphabetical order to look up which ones are legal scrabble words. That is enormously less work.

How much less work? Suppose you have NVSAIET on your rack and you wish to know all the seven letter bingos. In your original approach you generate the 5040 possible re-orderings of that rack and check them all.  With my approach you sort it to AEINSTV and look that up in your map to discover that the three seven letter words you can make with those letters are NAIVEST NATIVES VAINEST: that's one lookup instead of 5040.

How do you find the sixes? You look up EINSTV, AINSTV, AENSTV, AEISTV, AEINTV, AEINSV and AEINST. Now you are doing seven lookups instead of looking up each of the (again) 5040 six letter permutations from a rack of seven.

You end up doing only 120 lookups total, instead of the tens of thousands of lookups your present approach is doing.

An even better technique though is to construct a trie or a dawg (a Directed Acyclic Word Graph) from your dictionary, and recursively descend through the graph to discover what words can be made from the rack. Find yourself a good tutorial on tries, and learn how they work. Once you've mastered them, move on to dawgs.


Deleting a node in a singly linked list?

Mark variables that will remain constant as const.
Initialise variables right away when they're created, if possible. You're just adding one extra line with no benefit.
Limit the scope of variables by creating them only when they're required, not at the top. They'll go unused in certain conditions. Also one won't have to sanity check the whole function to see if the variable has been modified since it was created.
Use a more descriptive function name. del_node_at_index is even better.

void delete_node(Node **head, const int index)
{
  // Initialise curr when it's defined.
  Node *curr = *head;

  if (head == NULL) {
    return;
  }
  if (index == 0) {
    // Keep the scope of temp limited.
    // Initialise temp when it's defined.
    Node *temp = curr->next;
    *head = temp;
    free(curr);
  }
  else {
    // Keep the scope of prev limited.
    Node *prev;
    // Define pos if and when needed.
    for (int pos = 0; pos < index; pos++) {
      prev = curr;
      curr = curr->next;
    }
    prev->next = curr->next;

    free(curr);
  }
}


I'm not overly fond of the tmp.push_back(std::string());.

I'd rather some of the names were clearer and more readable--for example, I'm not entirely sure what rescnt is supposed to mean.

Under the circumstances, I'd tend to wonder whether we're getting enough good out of the stringstream to justify its existence either. They can be handy, but here we don't seem to be putting the capabilities to a whole lot of use.

std::vector<std::string> split(std::string const &in, std::string const &word) {
    std::vector<std::string> ret;

    int begin = 0;
    int end = 0;

    while (std::string::npos != (end = in.find(word, begin))) {
        ret.push_back(in.substr(begin, end-begin));
        begin = end + word.length()+1;
        while (::isspace(in[begin]))
          ++begin;
    }
    ret.push_back(in.substr(begin));
    return ret;
}


Counting nonexisting records with foreign key

Database modeling

Is the presence of check-in/check-out dates on both tables intentional?

If RoomDate is more like a reservations table, then having the check-in and check-out dates in it makes sense. How is the pair of date columns in the Room table used then?

Determining occupancy

Getting occupancy by using an = check is quite simplistic, as that does not take into account later check-ins, or earlier check-outs. If you want the check to be more robust, it can be something along the lines of:

-- please check if BETWEEN includes the values or not
d.checkInDate BETWEEN :checkInDate AND :checkOutDate OR
d.checkOutDate BETWEEN :checkInDate AND :checkOutDate OR
d.checkInDate <= :checkInDate AND d.checkOutDate >= :checkOutDate

This counts existing reservations with check-in or check-out dates that either fall within or span over the requested date range.

Efficient SELECT

  Could you not use a GROUP BY SQL statement (or the HQL equivalent) so that you make one query instead of three? - myself

I'm not very familiar with Hibernate, and we don't even know your choice of DBMS, so the following is borderline pseudo-query:

SELECT r.roomType, r.total - b.booked AS remaining FROM
    ((SELECT roomType, COUNT(1) AS total FROM Room GROUP BY roomType) AS r JOIN
        (SELECT roomType, COUNT(1) AS booked FROM RoomDate d JOIN Room USING roomID
            WHERE d.checkInDate BETWEEN :checkInDate AND :checkOutDate OR
                d.checkOutDate BETWEEN :checkInDate AND :checkOutDate OR
                d.checkInDate <= :checkInDate AND d.checkOutDate >= :checkOutDate
            GROUP BY roomType) AS b USING roomType
    )

The idea here is not to fire 6 separate SQL statements, as you have found to be 'unsatisfactory' and 'inefficient'. What you need is one representation from your Room table that shows the total rooms:

$$\begin{array} {|r|r|}
\hline
roomType & total \\
\hline
0 & 5 \\
\hline
1 & 6 \\
\hline
2 & 7 \\
\hline
\end{array}$$

A representation from your RoomDate table that shows the booked, i.e. unavailable rooms (e.g. after the five-single-rooms booking is done):

$$\begin{array} {|r|r|}
\hline
roomType & booked \\
\hline
0 & 5 \\
\hline
1 & 0 \\
\hline
2 & 0 \\
\hline
\end{array}$$

Joining both on the roomType column:

$$\begin{array} {|r|r|r|}
\hline
roomType & total & booked \\
\hline
0 &5 &5 \\
\hline
1 &6 &0 \\
\hline
2 &7 &0\\
\hline
\end{array}$$

And finally subtract the two columns:

$$\begin{array} {|r|r|}
\hline
roomType & remaining \\
\hline
0 & 0 \\
\hline
1 & 6 \\
\hline
2 & 7 \\
\hline
\end{array}$$

You may want to consider if the modeling can be further improved to remove the inner JOIN. This is just something to get you started with.

edit This might be how you can do it in Hibernate/HQL... Again, I'm not familiar with Hibernate, and the casting may be done incorrectly... please test and experiment carefully.

// Assuming you now have a RoomType `enum`
Map<RoomType, Integer> map = new EnumMap<>(RoomType.class);
for (Object[] row : session.createQuery(query).list()) {
    map.put(RoomType.values()[(int)row[0]], row[1]);
}
System.out.println("Room type and free rooms:\n" + map);

Java code review

As you can see, the main solution to your problem lies in doing a more efficient SELECT once. With that out of the way, you may want to consider using a model class to represent the results, instead of a simply long[] array. It is not evident from the array itself how the indices are being mapped... if you decide to use a non-contiguous values to represent new room types, you may encounter issues mapping those.

You can also consider modeling your room types as a Java enum type, for starters.


Timers are pretty simple to use.  There are only a few things to worry about and they are called out in the documentation.  From that page:

  "As long as you are using a Timer, you must keep a reference to it. As
  with any managed object, a Timer is subject to garbage collection when
  there are no references to it. The fact that a Timer is still active
  does not prevent it from being collected."

In your code, the reference to the Timer isn't stored anywhere.  This means it's eligible for garbage collection, and when that happens it will stop firing events.  So you need to store a reference somewhere, in your code it looks like a static field on the UserTimer class would make sense.

The other thing is if it's possible for the callback to run longer than the interval, you might want to detect this case and have the second callback not do any work.  If this is a possibility I'll have a line of code like:

if (!Monitor.TryEnter(timerLock))
    return;

Of course you need to release the monitor in a finally block in your callback.


Multiplying corresponding integers using streams

Streams are not designed to naturally fit every computational situation in Java. As you have found, you have needed to perform a number of compound/stream/Iterator/array state changes.

Your data starts as a compound structure in a single file
you scan that using a Scanner, using the Scanner's next structures.
You split the lines in to a 2-element array
you split each element using regex mapped to a parser to get two int arrays
you use the array-stream to convert the two arrays to int streams
you convert the streams to lock-step primitive int iterators
you re-combine the lock-step product result in to another primitive int iterator
you convert that iterator in to a stream
you map the product stream to strings
you collect-and-print the results as a single line.

Note that your work contains far more data state changes than would be necessary using non-stream functionality. The fact that you have to scan the entire line and convert all values to ints means that all the data is in int[] arrays already, and there is no real benefit for any optimization in the streams using short circuiting.
Additionally, your result is not able to be run on a parallel stream because it would not survive in the Iterator stage.
Correlating two active streams is not an operation that is supported using any 'natural' mechanism in Java8.
But, there are ways to do it using non-stream mechanisms, and also much more natural Java8 ways too.
Stream Solution
First up, use a stream for the file IO. Files.lines(...) provides a stream of the lines in a file. Next up, instead of streaming over the values in the source arrays, use a stream of what the two arrays have in common, the indices. Stream over the indices.
By streaming the indices you can process the data in a natural stream way and pull the data by index from the corresponding positions in the sources.
Finally, the product operator should be supplied as an input lambda, and not built in to the stream-iterator-stream translation.
The solution I would use, if forced to use streams for as much as possible, would be:
public static void main(String[] args) throws IOException {
    try (Stream<String> lineStream = args.length > 0
            ? Files.lines(Paths.get(args[0]), StandardCharsets.UTF_8)
            : new BufferedReader(new InputStreamReader(System.in)).lines()) {

        lineStream.map(line -> processLineWithOperator(line, (a, b) -> a * b))
            .forEach(outLine -> System.out.println(outLine));

    }
}

private static String processLineWithOperator(String line, IntBinaryOperator operator) {
    String[] halves = line.split("\\|");
    int[] halfA = toInts(halves[0]);
    int[] halfB = toInts(halves[1]);

    return IntStream.range(0, halfA.length)
            .map(index -> operator.applyAsInt(halfA[index], halfB[index]))
            .mapToObj(String::valueOf)
            .collect(Collectors.joining(" "));

}

private static int[] toInts(String spaceDelimitedInts) {
    return Arrays.stream(spaceDelimitedInts.split("\\s+"))
              .mapToInt(Integer::parseInt)
              .toArray();
}


Generating a dynamically expandable form with multiple similar categories

Answering your questions:

  Is this fine, as long as I'm getting the right output?

Not really, by your own admission, the possibility of more fields means you'll have blocks and blocks and blocks of the same code. See Structure below.

  I'm concerned about the repetition of code. Is there any way to improve this code if this is a bad practice of coding?

See The code below.

Structure:

Although the code given could be greatly simplified, I think to a degree your methodology is at fault.

Currently, you would have seven variables for each dynamic field, as the number (currently five) increases, the amount of localised variables would be out of control!

Rather than having such a large number of these, consider using a dictionary.

For example:

$content = [];
$content['featured_artist'] = $variable;

Additionally, considering the DRY (don't repeat yourself) principles, the count(array_filter($_FILES[ statements should be turned into a function, and returned to a variable, which can be inserted into the theoretical $content described above.

The code:

Using the following code as a base, with some re-structuring, and maybe some good old fashioned wizardry, the code can be reborn!

if (count(array_filter($_FILES['featured_artist']['name'])) > 0) {

    $featured_artist_status= true;

    $featured_artist= $_FILES['featured_artist'];
    $featured_artist['tmp_name']['image'] = true;
    $featured_artist_field= Field::incrementFieldComparison($attraction['tmp_name'], $request->post('featured_artist_name'), $request->post('featured_artist_description'));

    $featured_artist_name = implode('|', $featured_artist_field->field_1);
    $featured_artist_description = implode('|', $featured_artist_field->field_2);
    $featured_artist_image = implode('|', $featured_artist_field->reference);
}

Such wizardry may look like this:

$completeFieldDict = [];
foreach ($_FILES as $key => $value){
    if (count(array_filter($value["name"])) > 0){
        $completeFieldDict[$key] = buildField($key);
    }
}
function buildField($name){

    $fieldDictionary = [];
    $fieldDictionary['status'] = true;

    $fieldDictionary['content'] = $_FILES[$name];
    $fieldDictionary['content']['tmp_name']['image'] = true;
    $fieldDictionary['field'] = Field::incrementFieldComparison($fieldDictionary['content']['tmp_name'], $request->post($key . '_name'), $request->post($key . '_description'));

    $fieldDictionary['name']        = implode('|', $fieldDictionary['field']->field_1);
    $fieldDictionary['description'] = implode('|', $fieldDictionary['field']->field_2);
    $fieldDictionary['image']       = implode('|', $fieldDictionary['field']->reference);

    return $fieldDictionary;
}

Although, the limitations of this are notable, in form of such a large dictionary.
But, as previously mentioned this could be greatly improved upon refactoring the structure.

Personally, I'd suggest having a database transaction embedded within buildField(), and not saving variables locally.


Extending functionality of org.springframework.batch.item.file.transform.DefaultFieldSet

The real issue here is that you do not need a PropertiesFieldSetFactory. Take a look at how you currently use it:

@Override
public Car mapFieldSet(FieldSet fieldSet) throws BindException {
    Properties fieldProperties = fieldSet.getProperties();

    fieldProperties.put("modelDescription", fieldProperties.get("model"));

    removeDummyIndicator(fieldSet, fieldProperties);

    // build field from properties derived / transformed from the original field set
    FieldSet domainObjectFieldSet = PropertiesFieldSetFactory.create(fieldProperties);

    return super.mapFieldSet(domainObjectFieldSet);
}

This code is taking as input the FieldSet that was tokenized by the LineTokenizer you are using. It adds car-specific values to the Properties of that FieldSet, removes a value in case a dummy parameter is set, and reconstructs a FieldSet back from those properties. Those hoops are needed because FieldSet is immutable.

But look at this again: you don't need to fiddle with the FieldSet, only to have everything set-up automagically by the BeanWrapperFieldSetMapper. Store the result of super.mapFieldSet (invoked with the fieldSet given to the mapper) to a local car and do the necessary logic on that car:

public class CarFieldSetMapper extends BeanWrapperFieldSetMapper<Car> {

    @Override
    public void afterPropertiesSet() throws Exception {
        setStrict(false); // <-- ignore the non-existant "dummyIndicator"
        setTargetType(Car.class);
        super.afterPropertiesSet();
    }

    @Override
    public Car mapFieldSet(FieldSet fieldSet) throws BindException {
        Car car = super.mapFieldSet(fieldSet);
        car.setModelDescription(car.getModel());
        if (fieldSet.readString("dummyIndicator").equalsIgnoreCase("Y")) {
            car.setModel(null);
        }
        return car;
    }

}

The Spring Batch approach to reading a file is:

Take a LineMapper which is supposed to read a line and map it into your domain objects.
This mapper tokenizes the line into a FieldSet with a LineTokenizer and maps this FieldSet into your domain object with a FieldSetMapper. As you can see, it is the tokenizer role to make a FieldSet out of the line, which is then used by the mapper to create the final domain object.
By default, the line tokenizer creates FieldSet instances using a FieldSetFactory. It gets the names you configured and the values come from the parsed line.

So once the FieldSet has been constructed by the LineTokenizer, it should not be re-created: it contains the data as specified in the line that was read. This data is then transformed into your domain object; hence the only place to implement domain-specific logic is in the mapper, directly with the instance to be returned, and not in the FieldSet.


Planned Economy Bakery - Trying to scale a nested loop with a heap

I think I understood your problem.
Problem description
Given:

num_items - the number of available items
targets - a list of potential targets, each having a value
threshold - a cutoff limit

Task:

Choose the first num_items elements of targets, whose values are above or equal to threshold.
Return the array index of the last chosen element from targets (starting with 1), or 0 if not enough targets are available. (Odd decision, I would have gone with indices starting at 0 and return len(targets) if none found, but fine)
Optimize for speed. targets and num_items are identical every time, threshold is the only value that changes.

Example
num_items = 3
targets = [5,3,4,1,3,3,7,4]
threshold = 4

Chosen targets would be the ones at the positions [0,2,6], with the values [5,4,7], as those are the first 3 values that are above or equal to threshold. We only search the index of the last one, which in this case would be 6.

Approach
Your original idea was to iterate through all the people which is very fast if the threshold is very low, but becomes really slow if the threshold is higher, as we need to iterate through all the people until we find a candidate.
I rewrote your original idea to iterate through all of them, as I wasn't able to understand your code:
def choose_first_n(num_items, targets, threshold):
    for target_id, target in enumerate(targets):
        if target >= threshold:
            num_items -= 1
            if num_items == 0:
                return target_id + 1
    return 0

def baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):
    results = []
    for today_baking_time in required_baking_times:
        results.append(choose_first_n(num_loaves_per_day, people_max_waiting_time, today_baking_time))
    return results

print(baker_queue(3,
                  [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],
                  [1, 2, 5, 4, 5, 4, 7]))
# Returns: [3, 4, 15, 7, 15, 7, 19], as in the original code.

Using a heap is an interesting idea, but I don't think we benefit from that in any way. Heaps are only really fast for item removal/insertion, which we don't do. We just iterate over them.
The fastest way that I could think of is to pre-process the threshold list into something more efficient, as if, create an 'index' of the last target.
Demonstration:
We use our previous code, and look at the results based on the threshold value:
def choose_first_n(num_items, targets, threshold):
    for target_id, target in enumerate(targets):
        if target >= threshold:
            num_items -= 1
            if num_items == 0:
                return target_id + 1
    return 0

targets = [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8]
num_items = 3

for threshold in range (10):
    result = choose_first_n(num_items, targets, threshold)
    print(f"Threshold: {threshold}, Result: {result}")

Threshold: 0, Result: 3
Threshold: 1, Result: 3
Threshold: 2, Result: 4
Threshold: 3, Result: 4
Threshold: 4, Result: 7
Threshold: 5, Result: 15
Threshold: 6, Result: 15
Threshold: 7, Result: 19
Threshold: 8, Result: 19
Threshold: 9, Result: 0

You can see that if the threshold goes up, the result goes up. There is a steadily increasing relationship between the threshold and the result.
If we can compute the values at which the result changes, we can compute the result directly via a divide-and-conquer search, which is a LOT faster than iterating through the list. (O(logn) instead of O(n), in case you are familiar with Big-O notation)
One thing to note here is that the last result is 0, which breaks that scheme. That is the reason why it is benefitial to let the indices start with 0 instead of 1, and have the 'error' case be len(targets) instead of 0.
Preprocessing
The hardest thing is the preprocessing to get to that mapping.
Let's look at it from the other way round.
For the sake of simplicity, let's say num_items is 3, and we have 10 targets.
Will the chosen targets be within the first 5 targets?
The answer is: yes, IF at least 3 of the first 5 targets are above or equal to the threshold. Or in other words, the 3rd largest number in the list is the deciding factor. If the threshold is above the 3rd largest number, the first 5 targets will not provide all the chosen targets.
Therefore, for all items, we need to compute the 3rd largest number. Funnily, this is actually where a heap WILL come in handy ;)
Implementation
import heapq
import bisect

def preprocess(targets, num_items):
    # Special case if we have more items than targets, would break later.
    # Return an empty lookup table with len(targets) as fallback, so the
    # result will always be len(targets)
    if num_items > len(targets):
        lookup_table = ([], [], len(targets))
        return lookup_table

    # our heap, will contain the first num_items smallest targets
    largest_targets_heap = []

    # Our first preprocessing result, will contain the
    # third large number between the first item and the current item,
    # for every item.
    third_largest_number_per_target = []

    # Compute the third largest previous value for every target
    for target in targets:
        heapq.heappush(largest_targets_heap, target)
        if len(largest_targets_heap) > num_items:
            heapq.heappop(largest_targets_heap)

        current_third_largest = largest_targets_heap[0]
        third_largest_number_per_target.append(current_third_largest)

    # We now have the third largest number for every target.
    # Now, consolidate that data into a lookup table, to prevent duplication.
    # Therefore, find the first occurrence of every number
    lookup_table_indices = []
    lookup_table_values = []
    current_value = third_largest_number_per_target[num_items - 1]

    # Push the (num_items-1)th value to account for the fact our heap wasn't filled up until the
    # first num_items were processed
    lookup_table_indices.append(num_items - 1)
    lookup_table_values.append(current_value)

    # Fill the rest of the lookup table
    for index, value in enumerate(third_largest_number_per_target):
        if index < num_items - 1:
            continue
        if value != current_value:
            lookup_table_indices.append(index)
            lookup_table_values.append(value)
            current_value = value

    # The lookup table we have, consisting of values, indices and a maximum value
    lookup_table = (lookup_table_values, lookup_table_indices, len(targets))

    return lookup_table

def choose_first_n_preprocessed(lookup_table, threshold):
    (lookup_table_values, lookup_table_indices, max_value) = lookup_table

    # We need to find the first (value,index) pair in lookup table where value is larger or equal to threshold
    # We do this by using bisect, which is really fast. This is only possible because of our preprocessing.
    position = bisect.bisect_left(lookup_table_values, threshold)

    # If we didn't find a result in the preprocessed table, we return the max value, to indicate that the
    # threshold ist too high.
    if position >= len(lookup_table_indices):
        return max_value

    # Read the result from the table of incides
    value = lookup_table_indices[position]
    return value

def baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):
    # Create the preprocessed lookup table
    lookup_table = preprocess(people_max_waiting_time, num_loaves_per_day)

    # For every day, compute the result
    results = []
    for today_baking_time in required_baking_times:
        # Use our fast lookup based algorithm now
        result = choose_first_n_preprocessed(lookup_table, today_baking_time)

        # Convert indices back to starting with 1, and 0 in error case, as
        # the original format was
        if result == len(people_max_waiting_time):
            results.append(0)
        else:
            results.append(result + 1)
    return results

print(baker_queue(3,
                  [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],
                  [1, 2, 5, 4, 5, 4, 7]))
# [3, 4, 15, 7, 15, 7, 19]

Theoretical Analysis
This should now be a LOT faster, especially for a large number of days, but also for a large number of people.
The complexity of the naive implementation was
O(days * people)

The complexity of the preprocessed implementation is
O(people * log(bread) + days * log(people))

This doesn't sound a lot different, but it is. It basically says if the limiting factor is the people, it doesn't matter how many days, and if the limiting factor is the days, it doesn't matter how many people.
Benchmarking Results
Setup was:

900 bread per day
10,000 people
10,000 days

Result:

Naive: 2.13 seconds
Preprocessed: 0.012 seconds

I then tried to push the algorithm so far that it also takes 2 seconds, and got those numbers:

90,000 bread per day
1,000,000 people
1,000,000 days

I didn't run those numbers on the naive algorithm, but the math says it would have taken about 20,000 seconds, or 5.5 hours.
The benchmark code can be found at https://ideone.com/2ZMBVH or here:
import heapq
import bisect
import random
import time

def choose_first_n(num_items, targets, threshold):
    for target_id, target in enumerate(targets):
        if target >= threshold:
            num_items -= 1
            if num_items == 0:
                return target_id
    return len(targets)

# 2s for optimised
#num_bread = 90000
#num_days = 1000000
#num_people = 1000000

# 2s for unoptimized
num_bread = 900
num_days = 10000
num_people = 10000

targets = [random.random() for _ in range(num_people)]

result_sum = 0
algo_naive_start = time.time()
for threshold in range(num_days):
    result = choose_first_n(num_bread, targets, threshold/num_days)
    result_sum += result
    #print(f"Threshold: {threshold}, Result: {result}")
algo_naive_end = time.time()
print(f"Result naive: {result_sum}")

def preprocess(targets, num_items):
    # Special case if we have more items than targets, would break later.
    # Return an empty lookup table with len(targets) as fallback, so the
    # result will always be len(targets)
    if num_items > len(targets):
        lookup_table = ([], [], num_items, len(targets))
        return lookup_table

    # our heap, will contain the first num_items smallest targets
    largest_targets_heap = []

    # Our first preprocessing result, will contain the
    # third large number between the first item and the current item,
    # for every item.
    third_largest_number_per_target = []

    # Compute the third largest previous value for every target
    for target in targets:
        heapq.heappush(largest_targets_heap, target)
        if len(largest_targets_heap) > num_items:
            heapq.heappop(largest_targets_heap)

        current_third_largest = largest_targets_heap[0]
        third_largest_number_per_target.append(current_third_largest)

    # We now have the third largest number for every target.
    # Now, consolidate that data into a lookup table, to prevent duplication.
    # Therefore, find the first occurrence of every number
    lookup_table_indices = []
    lookup_table_values = []
    current_value = third_largest_number_per_target[num_items - 1]

    # Push the (num_items-1)th value to account for the fact our heap wasn't filled up until the
    # first num_items were processed
    lookup_table_indices.append(num_items - 1)
    lookup_table_values.append(current_value)

    # Fill the rest of the lookup table
    for index, value in enumerate(third_largest_number_per_target):
        if index < num_items - 1:
            continue
        if value != current_value:
            lookup_table_indices.append(index)
            lookup_table_values.append(value)
            current_value = value

    # The lookup table we have, consisting of values, indices, a minimum and a maximum value
    lookup_table = (lookup_table_values, lookup_table_indices, num_items, len(targets))

    return lookup_table

def choose_first_n_preprocessed(lookup_table, threshold):
    (lookup_table_values, lookup_table_indices, min_value, max_value) = lookup_table

    # We need to find the first (value,index) pair in lookup table where value is larger or equal to threshold
    # We do this by using bisect, which is really fast. This is only possible because of our preprocessing.
    position = bisect.bisect_left(lookup_table_values, threshold)

    # If we didn't find a result in the preprocessed table, we return the max value, to indicate that the
    # threshold ist too high.
    if position >= len(lookup_table_indices):
        return max_value

    # Read the result from the table of incides
    value = lookup_table_indices[position]
    return value

def baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):
    # Create the preprocessed lookup table
    lookup_table = preprocess(people_max_waiting_time, num_loaves_per_day)

    # For every day, compute the result
    results = []
    for today_baking_time in required_baking_times:
        # Use our fast lookup based algorithm now
        result = choose_first_n_preprocessed(lookup_table, today_baking_time)

        # Convert indices back to starting with 1, and 0 in error case, as
        # the original format was
        if result == len(people_max_waiting_time):
            results.append(0)
        else:
            results.append(result + 1)
    return results

algo_preprocessed_start = time.time()

lookup_table = preprocess(targets, num_bread)

algo_preprocessed_mid = time.time()
#print(lookup_table)

result_sum = 0
for threshold in range(num_days):
    result = choose_first_n_preprocessed(lookup_table, threshold/num_days)
    result_sum += result
    #print(f"Threshold: {threshold}, Result: {result}")
algo_preprocessed_end = time.time()
print(f"Result preprocessed: {result_sum}")

print(f"Time naive: {algo_naive_end - algo_naive_start} s")
print(f"Time preprocessed (preprocessing step): {algo_preprocessed_mid - algo_preprocessed_start} s")
print(f"Time preprocessed (evaluation step): {algo_preprocessed_end - algo_preprocessed_mid} s")
print(f"Time preprocessed total: {algo_preprocessed_end - algo_preprocessed_start} s")

Well that took a while, I hope it was worth it ;)
I think this was my biggest post yet, it was a really interesting task!
I hope you appreciate it.
Greetings