Sequence generators not only for potatoes but also for apples and oranges

A slightly different approach is to avoid the sublclassing and instead feed the generic DelaySequence class with a generator function. It makes it more flexible.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace CR146856
{
  public class MyDelaySequence<T> : IEnumerable<T>
  {
    Func<IEnumerable<T>> m_generator;
    int m_count = 0;

    /// <summary>
    /// A contructor for a plain sequence of regular delays
    /// </summary>
    /// <param name="count">Number of retries.</param>
    /// <param name="delay">The delay after each retry.</param>
    public MyDelaySequence(int count, T delay)
    {
      m_count = count;
      m_generator = () =>
      {
        return Enumerable.Range(1, count).Select(i => delay);
      };
    }

    /// <summary>
    /// Constructor for a custom delay generator.
    /// </summary>
    /// <param name="count">Number of retries.</param>
    /// <param name="generator">A custom generator of delays between retries.</param>
    public MyDelaySequence(int count, Func<IEnumerable<T>> generator)
    {
      m_count = count;
      m_generator = generator;
    }

    public IEnumerator<T> GetEnumerator()
    {
      return m_generator().Take(m_count).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }

  class Program
  {
    static IEnumerable<int> GeometricDelayGenerator()
    {
      int delay = 1000;
      while (true)
      {
        yield return delay;
        delay += delay;
      }
    }

    static IEnumerable<int> FibonacciIntDelayGenerator()
    {
      int first = 1000;

      yield return first;
      yield return first;

      int second = first + 3000;
      yield return second;

      while (true)
      {
        yield return first + second;
        int tmp = first;
        first = second;
        second = first + tmp;
      }
    }

    static IEnumerable<TimeSpan> FibonacciTimeSpanDelayGenerator()
    {
      TimeSpan first = TimeSpan.FromSeconds(1);

      yield return first;
      yield return first;

      TimeSpan second = first + TimeSpan.FromSeconds(3);
      yield return second;

      while (true)
      {
        yield return first + second;
        TimeSpan tmp = first;
        first = second;
        second = first + tmp;
      }
    }

    static void Main(string[] args)
    {
      try
      {
        TimeSpan seqDelay = TimeSpan.FromSeconds(1);
        int count = 7;

        foreach (var ts in new MyDelaySequence<TimeSpan>(count, FibonacciTimeSpanDelayGenerator))
        {
          Console.WriteLine(ts);
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine($"ERROR: {ex.Message}");
      }

      Console.WriteLine("END");
      Console.ReadLine();
    }
  }
}

That said I tend to think you overdo a rather simple construct:

    foreach (var delay in FibonacciIntDelayGenerator().Take(count))
    {
      Console.WriteLine($"If service not responding wait in {delay} ms and retry.");
    }

EDIT:

In case of a reusable library of functions I would do it the static way:

  public static class MyDelayGenerators
  {
    public static IEnumerable<T> DelayGenerator<T>(int retries, T initialDelay, Func<T, T> offsetFunc)
    {
      T delay = initialDelay;
      for (int i = 0; i < retries; i++)
      {
        yield return delay;
        delay = offsetFunc(delay);
      }
    }

    public static IEnumerable<T> GeometricDelayGenerator<T>(int retries, T initialDelay, Func<T, T> sum)
    {
      return DelayGenerator(retries, initialDelay, sum);
    }

    public static IEnumerable<int> GeometricDelayGenerator(int retries, int initialDelay)
    {
      return DelayGenerator(retries, initialDelay, (d) => d + d);
    }

    public static IEnumerable<TimeSpan> GeometricDelayGenerator(int retries, TimeSpan initialDelay)
    {
      return DelayGenerator(retries, initialDelay, (d) => d + d);
    }

    public static IEnumerable<int> RegularDelayGenerator(int retries, int delay)
    {
      for (int i = 0; i < retries; i++)
      {
        yield return delay;
      }
    }

    public static IEnumerable<TimeSpan> RegularDelayGenerator(int retries, TimeSpan delay)
    {
      for (int i = 0; i < retries; i++)
      {
        yield return delay;
      }
    }

    public static IEnumerable<T> FibonacciDelayGenerator<T>(int retries, T first, T firstOffset, Func<T, T, T> sum)
    {
      yield return first;
      yield return first;

      T second = sum(first, firstOffset);
      yield return second;

      retries -= 3;
      for (int i = 0; i < retries; i++)
      {
        T tmp = sum(first, second);
        yield return tmp;
        first = second;
        second = tmp;
      }
    }

    public static IEnumerable<int> FibonacciDelayGenerator(int retries, int first = 1000, int firstOffset = 1000)
    {
      return FibonacciDelayGenerator(retries, first, firstOffset, (f, s) =>
      {
        int tmp = f;
        f = s;
        s = f + tmp;
        return s;
      });
    }

    public static IEnumerable<TimeSpan> FibonacciDelayGenerator(int retries, TimeSpan first, TimeSpan firstOffset)
    {
      return FibonacciDelayGenerator(retries, first, firstOffset, (f, s) =>
      {
        TimeSpan tmp = f;
        f = s;
        s = f + tmp;
        return s;
      });
    }
  }

It has a number of predefined functions and a set of generic as well to be use on the fly.


Get default value from query params + repeating code

The validation function:
const validation = (value, min, max) => {
    if (value < min) {
        return min;
    } else if (value > max) {
        return max;
    }
    return value;
};

Bounds the value between some minimum and maximum, can can be simplified to the following:
const validation = (value, min, max) => Math.max(min, Math.min(value, max));

For the rest, each "case" abstractly searches the limitValues array for a matching object by slider type, and then bounds the input value for that case. A general purpose utility could look like the following:
const processField = (key, fieldValue) => {
  const val = limitValues.find(({ sliderType }) => sliderType === key);
  props.inputs[key] = val
    ? validation(fieldValue, val.minValue, val.maxValue)
    : fieldValue;
};

Since Array.prototype.find can potentially return undefined for no matches, you should guard check this. the second line uses a ternary to check if a defined value was returned from the find and returns the bounded field value otherwise returns the unbounded field value.
Here is your updated example code:
const validation = (value, min, max) => Math.max(min, Math.min(value, max));

...

getFromQuery = (props) => {
  const { limitValues } = props;
  const parsed = queryString.parse(location.search);

  const processField = (key, fieldValue) => {
    const val = limitValues.find(({ sliderType }) => sliderType === key);
    // Mutates props object
    props.inputs[key] = val
      ? validation(fieldValue, val.minValue, val.maxValue)
      : fieldValue;
  };

  if (parsed.price) {
    processField("PRICE", parsed.price);
  }

  if (parsed.savings) {
    processField("SAVINGS", parsed.savings);
  }

  if (parsed.maturity) {
    processField("MATURITY", parsed.maturity);
  }
};


ActiveRecord selection, modified by optional parameters

Some notes:

That's too much code for a controller method, it should be moved to the model.
The same name (@measurements) holds up to 4 different values. As a general rule, avoid variable rebinding: different values, different names.
More about how the filtering method could be written keeping it DRY: https://stackoverflow.com/a/4480285/188031

For example:

class Measurement < ActiveRecord::Base
  def self.filter(attributes)
    attributes.select { |k, v| v.present? }.reduce(all) do |scope, (key, value)|
      case key.to_sym
      when :sensor_id
        scope.where(key => value)
      when :last, :last_per_sensor
        scope.send(key, value)
      else
        scope
      end
    end
  end
end

And in the controller simply:

@measurements = Measurement.filter(params.slice(:sensor_id, :last, :last_per_sensor))


First off, I'm not an expert about TCP and Sockets, though I have had some experiences in the past.

  My problems is that on some occasions it detects disconnect where server does not, so on server I have connection left hanging while client reconnects.

If you have a client-server scenario, then one will never ever know about what is the state of the other without explicitly finding out!

Say you open the connection, client is idle for 10 seconds and now suddenly the client loses all power. The server doesn't know that the client lost it's power, the client didn't send a disconnect signal, the client was in an idle state so there is no sending/receiving that cut out midway or timed out. The only way for the server to know what is the state of the client on the 11-th second (for instance) is to query/ping the client. The term Keep-Alive applies here, although I can't think of good wording for it right now...

  I'm asking anyone who tried using this method to share experiences and maybe help make it more robust

The state of the problem isn't currently very clear to me. In what specific scenario does the problem exist? When you remove the LAN cable? When you close the client application?

So what, if the connection on the server is left hanging? You have to account for such a very likely possibility. You will need to apply some sort of timeout or keep-alive methodology, inorder to keep the server from hanging on to the connection indefinently and thus consuming and running out of resources. Accounting for all possible scenarios - that is robustness!

As I said, I'm no expert, so I won't be able to tell you exactly which Socket class properties or methods to apply to your code to help you make it more robust. But I will say this, your code example is missing Disconnect() / Close() statements, most likely even using statements. I see no timeouts being applied, surely the Connect() and Send() methods have some sort timeout mechanism (maybe a property, eg client.SendTimeout)...


Find relative filenames recursively in Emacs

Yeah don't use a dynamic variable for that, it's just confusing for the
user.

It is way easier to deal with input and output from a
function instead of having to take special variables into account, basically it's now part of your interface.  And I personally
would be really angry if a random function somewhere took a common
variable like files from outside its scope and filled it with data.

So, after that explanation, I would recommend using either a separate
function, or cl-flet/cl-labels to handle the recursive part and only
expose the necessary parts to the caller.  That means no optional
rel-dir, which isn't really part of the interface and no using files
from the outer scope.

To wit:

(defun my-get-dir-files (dir pat)
  "..."
  (let (files)
    (cl-flet ((aux (dir pat rel-dir)
                    (let ((dir-files nil)
                          (cur-dir nil))
                      (unless rel-dir (setq rel-dir ""))
                      (setq cur-dir (expand-file-name rel-dir dir))
                      (setq dir-files (directory-files cur-dir nil nil t))
                      (dolist (name dir-files)
                        (unless (or (string= name ".") (string= name ".."))
                          (let ((fn (expand-file-name name cur-dir)))
                            (if (file-directory-p fn)
                                (let ((new-rel-dir nil))
                                  (if (string= "" rel-dir)
                                      (setq new-rel-dir name)
                                    (setq new-rel-dir (concat rel-dir "/" name)))
                                  (aux dir pat new-rel-dir)) ;; recursive call
                              (when (string-match pat name)
                                (let ((rel-fn nil))
                                  (if (string= "" rel-dir)
                                      (setq rel-fn name)
                                    (setq rel-fn (concat rel-dir "/" name))
                                    (setq files (append files `(,rel-fn)))))))))))))
      (aux dir pat nil)
      files)))

Note that I just wrapped the existing function one time and put a let
around it to keep the side effect more contained.  And now that files
is lexical, everything is fine.

But really, it would be better to just use an accumulator.  You
only ever add one element to the list, in which case you should just
immediately use push instead (and if you care about the output order,
nreverse the final result).

The following changes could also be made later:

Use member instead of the or, less typing for you.
(Short variable names don't necessarily improve readability.  Even
though Elisp code seems to disagree in places.)
The explicit binding to nil isn't necessary as it's the default
anyway.
Also the setqs there are unnecessary, just put the initial binding
into the let instead, use or and other functional tools.
cond is more readable for nested conditions, if applicable.
I would use list for simple list constructions like (,foo).
(setq rel-fn name) in the if doesn't do anything as it's the only form in the true branch.

So with all that it would be like this (even though personally I'd
rename the fn to filename as well.  YMMV:

(defun my-get-dir-files (dir pat)
  (let (files)
    (cl-flet ((aux (dir path rel-dir)
                   (let ((cur-dir (expand-file-name rel-dir dir)))
                     (dolist (name (directory-files cur-dir nil nil t))
                       (unless (member name '("." ".."))
                         (let ((fn (expand-file-name name cur-dir)))
                           (cond
                            ((file-directory-p fn)
                             (aux dir pat (if (string= "" rel-dir)
                                              name
                                            (concat rel-dir "/" name))))
                            ((string-match pat name)
                             (unless (string= "" rel-dir)
                               (push (concat rel-dir "/" name) files))))))))))
      (aux dir pat "")
      files)))

I'm pretty sure all transformations kept the meaning the same; a quick
check via

(set-exclusive-or (let (files) (my-get-dir-files-1 ".." ".*") files) (my-get-dir-files ".." ".*") :test #'equal)

with -1 being the original function resulted in no difference in the
lists (except for order of course), so that was enough for me.  If you
return (nreverse files) instead the lists are exactly equal.

And at this point I'm done.  There might still be potential
optimisations during the concatenations and so on.  The recursion itself here is fine as you won't encounter directory trees deep enough to cause the recursion to fail and it's also fairly efficient now, so no need to change anything there.

You could still extract a local function for (if (string= "" rel-dir) ...) and use that there and in the other branch of the cond.

Next up:  Would be cool if the function also handled "." for dir.


Further optimization of file transfer over FIFO on linux?

Const

I consider

const char *request_string

and

free(request_string);

to be in conflict. If the contract for this function is that it is responsible for freeing the string it was given, it should not be const. Conversely, if you really think it should be const, shift responsibility of freeing it onto the caller.

Stack allocation

In C terms, support for dynamic stack allocation of the kind seen in

char full_fifo_path[strlen(FIFO_STORAGE_PATH) + strlen(request_fifo_name) + 1];

is relatively new. If I were you I would be concerned that a hostile caller could pass a huge string in request_string, which parses into a huge request_fifo_name and blows the stack. As long as you take care to free the memory yourself through the various return paths in this function, I would consider malloc safer.


Read integers from coupled lines in a text file

You're turning the whole input file into a vector of vectors. That's fine, but you state yourself that your input has structure. It would be nice to have that structure reflected in your program:

since the lines are couple in pairs I'd like to see a code block that clearly processes a pair of lines
you should then eliminate the redundancy that the second number of the 1 st line equals the number of items on the second.


That cat is entirely unnecessary. Also, multiple pipes to sed are redundant.

sed by design can take a single long expression and process the data.

As for your delimiters, I'd suggest using non-printable characters when in sed:

SED_DELIM=$(echo -en "\001")

and then:

sed "s${SED_DELIM}url=jdbc:mysql://localhost/mysql${SED_DELIM}url=jdbc:mysql://$host/mysql${SED_DELIM}; s${SED_DELIM}username=root${SED_DELIM}username=$user${SED_DELIM}; s${SED_DELIM}password=my-secret-pw${SED_DELIM}password=$pass${SED_DELIM}" $file_name

Now, that looks quite long. You can evaluate individual expressions:

sed -e "s${SED_DELIM}url=jdbc:mysql://localhost/mysql${SED_DELIM}url=jdbc:mysql://$host/mysql${SED_DELIM};" \
-e "s${SED_DELIM}username=root${SED_DELIM}username=$user${SED_DELIM};" \
-e "s${SED_DELIM}password=my-secret-pw${SED_DELIM}password=$pass${SED_DELIM}" \
$file_name

I'll go ahead and also use back-references:

sed -e "s${SED_DELIM}\(url=jdbc:mysql://\)localhost\(/mysql\)${SED_DELIM}\1$host\2${SED_DELIM};" \
-e "s${SED_DELIM}\(username=\)root${SED_DELIM}\1$user${SED_DELIM};" \
-e "s${SED_DELIM}\(password=\)my-secret-pw${SED_DELIM}\1$pass${SED_DELIM}" \
$file_name


I see some ways in which this code might be improved.

Make sure printf format specifiers match the data

In the sample main, the format specifier used is "%i" but bitmap_color_replace returns a dword which is an alias for unsigned long, so the correct format specifier would actually be "%lu" for that data.

Omit return statement in main

This line

return EXIT_SUCCESS;

is not needed with modern C compilers. Getting to the end of main implicitly means that the program has succeeded, so the compiler will include code to do that return if you simply omit it.

Rearrange the code to reduce the need for declarations

A function declaration is only needed by the compiler if it hasn't already encountered the function itself.  With that said, if the bitmap_color_replace function is moved to the top of the file, above main, the function declaration within main can be omitted, making main a single printf.

Omit unused variables

Because argc and argv are unused, you could use the alternative form of main:

int main ()

Avoid hardcoding values

The IMAGE_WIDTH, IMAGE_OFFSET_PIXELS are not valid for most images.  Rather than hardcode those, you could simply read them from the file header in the same way that fp_size is read.

Avoid uneccessary fseek calls

There are a lot of fseek calls within the current routine which are not necessary because the program moves linearly through the data anyway.  Eliminating them would likely speed up the program.

Calculate pad size just once

The padding size is the same for every row so you can calulate it based on the image width and the size of each color.

Process only the pixel data

In some version of BMP files, there is data after the pixel data, so the current code, which continues to the end of the physical file, would overwrite that data.  Better would be to calculate just the size of the pixel data which is obtained from the height and width of the image.

Don't overwrite the input file

Create a new file instead of overwriting the input file.  This helps the user as well as preventing file corruption if something goes wrong during the processing of the file. It may also speed the program.

Process larger chunks at a time in memory

Instead of reading the colors byte at a time, it would likely speed things up considerably by processing entire rows at a time, or even the entire file as a memory image.  I/O is often the bottleneck for programs like this, so minimizing it can result in considerable time savings.

Note the correct data order

BMP files contain pixel data as R,G,B in that order.  It's important to get the order right to correctly match colors.

One possibility

Here's a version of the code with some, but not all of these ideas incorporated:

// these are absolute offsets to the two most important
// items in the BMP file
#define IMAGE_PIXEL_START   10
#define IMAGE_WIDTH         18

typedef unsigned char byte;
typedef unsigned long dword;

dword
bitmap_color_replace
(char *file_name, byte old_r, byte old_g, byte old_b, byte new_r, byte new_g, byte new_b)
{
    FILE* fp = fopen(file_name, "r+b");
    dword pixels_replaced = 0;

    byte new_color[3];

    new_color[0] = new_r;
    new_color[1] = new_g;
    new_color[2] = new_b;

    byte old_color[3];

    fseek(fp, IMAGE_PIXEL_START, SEEK_SET);
    dword fp_pixelstart = fgetc(fp) + fgetc(fp)*256 + fgetc(fp)*(256*256) + fgetc(fp)*(256*256*256);
    fseek(fp, IMAGE_WIDTH, SEEK_SET);
    dword fp_width = fgetc(fp) + fgetc(fp)*256 + fgetc(fp)*(256*256) + fgetc(fp)*(256*256*256);
    dword fp_height = fgetc(fp) + fgetc(fp)*256 + fgetc(fp)*(256*256) + fgetc(fp)*(256*256*256);
    // rows are padded to a multiple of 4 bytes
    dword padsize = (4 - ( (sizeof(new_color) * fp_width) & 0x3 )) & 0x3;

    fseek(fp, fp_pixelstart, SEEK_SET);
    for (int row = fp_height; row; --row)
    {
        for (int col = fp_width; col; --col)
        {
            fread(old_color, sizeof(old_color), 1, fp);
            if(    old_color[0] == old_r
                && old_color[1] == old_g
                && old_color[2] == old_b)
            {
                fseek(fp, -sizeof(old_color), SEEK_CUR);
                fwrite(new_color, sizeof(new_color), 1, fp);
                pixels_replaced++;
            }
        }
        if (padsize)
        {
            fseek(fp, padsize, SEEK_CUR);
        }
    }
    fclose(fp);
    return pixels_replaced;
}


Optimizing the performance of html5 video manipulation

After back and forth with ChrisW and yourself, it seems I found a glaring bug

    var frameFix = function() {

        hContext.drawImage(sourceVid, 0, 0, sourceVid.videoWidth, sourceVid.videoHeight);

        var frame = hContext.getImageData(0, 0, sourceVid.videoWidth, sourceVid.videoHeight);

        var length = frame.data.length;
        for (var i = 0; i < length; i++) {
            var r = frame.data[i * 4 + 0];
            var g = frame.data[i * 4 + 1];
            var b = frame.data[i * 4 + 2];

            if (g >= 0 && g < 100 && r >= 0 && r < 100 && b >= 0 && b < 100) {
                frame.data[i * 4 + 3] = 0;
            }
        }
        dContext.putImageData(frame, 0, 0);
        return
    };

Since in frame.data you have 4 data points per pixel, you only need to go as far as frame.data.length / 4, this should make your code 4 times faster.

This observation with ChrisW's common sense observations makes for:

var frameFix = function()
{
  hContext.drawImage(sourceVid, 0, 0, sourceVid.videoWidth, sourceVid.videoHeight);

  var frame  = hContext.getImageData(0, 0, sourceVid.videoWidth, sourceVid.videoHeight),
      data   = frame.data,
      length = data.length, i;

  for (i = 0; i < length; i += 4)
    if (data[i] < 100 && data[i + 1] < 100 && data[i + 2] < 100)
      data[i + 3] = 0;

  dContext.putImageData(frame, 0, 0);
};


Find and Replace on PowerPoint Charts with Excel Sheets

This is pretty well optimized. All I can say is that some variables could have better names

pptPres - targetPresentation
sld - targetSlide
shpe - targetShape
c - targetChartObject
sht - targetSheet
fndList - wordsToFind

Otherwise, like I said, there's nothing I can really say need to be optimized.

If you don't have to change the window viewtype and activate the chart data, I'd get rid of those.


Check the address String for presence of a New Brunswick abbreviation

Depending on your requirements for word breaks the following should do nicely:

/.*\b[nN](\.)?-?[bB]\1?\s.*/

Caveat only checks for a space after N?B?

Or in as in your question language(ruby?):

return addressLine?.matches(".*\\b[nN](\\.)?-?[bB]\\1?\\s.*"


There isn't much to say about the markup here - it looks like much was stripped from the markup. One thing though:

            <Border BorderBrush="Black" BorderThickness="1">
                <Image Source="MyImage.png"/>
            </Border>

I wouldn't hard-code paths into the XAML like this; instead, bind to an ImageSource property on your ViewModel. If/when that image needs to change, you'd certainly rather modify C# code than dig up the path in the XAML markup.


Partitions of a number (backtracking) - time efficiency

Nitpicks

using namespace std;

See also Why is “using namespace std;” considered bad practice?

ofstream out("partitiinumar.out.txt");

int n, solutions[41];

As a general rule, it is bad practice to use global variables.  Obviously it won't make much difference in this program, but it's a bad habit to develop.  Given that this is C++, you could put all the functions other than main inside a class and make these member variables.  That would allow you to use them across multiple functions.

int solution(int k)
{
    int S = 0;
    for (int i = 1; i < k; i++)
        S = S + solutions[i];

The last line would be more idiomatic as

        S += solutions[i];

And a little shorter.

    if (S == n)
        return 1;
    else
        return 0;
}

I would prefer

    if (S == n)
    {
        return 1;
    }
    else
    {
        return 0;
    }

as it makes it clearer what belongs with what.  A side effect is that it makes certain types of bugs less likely.

But in this case, it's even easier to just say

    return S == n;

Rather than building an if/else to return the same thing.

However, I would actually do

    return S;

The problem is that there are really three states here but the function merges two of them into one.  The values in the solution can sum to be less than, greater than, or equal to n.  More about this later.

Performance

void backtracking(int k)
{
    if (solution(k))
    {
        for (int i = 1; i < k; i++)
            out << solutions[i] << " ";
        out << '\n';
    }
    else if (solution(k)==0 && k<=n)
    {
        solutions[k] = 0;
        while (succesor(k))
            if (valid(k))
                backtracking(k + 1);
    }

}

You engage in more backtracking than necessary.  For example, it tries "1 1 1 1 2" as a solution and then tries "1 1 1 1 3".  But "1 1 1 1 3" is farther from being a solution than "1 1 1 1 2".  So why keep trying?  If you change solution to return S instead of S == n, then you can change as follows.

void backtracking(int k)
{
    int sum = solution(k);
    if (sum == n)
    {
        for (int i = 1; i < k; i++)
            out << solutions[i] << " ";
        out << '\n';
    }
    else if (sum < n)
    {
        solutions[k] = 0;
        while (succesor(k))
            if (valid(k))
                backtracking(k + 1);
    }
}

Doing this dropped from 90 wrong solutions to 31 for when n equals 5.  When n equals 9, it reduces from 18,546 wrong solutions to 356.  Even this code finds over five million wrong solutions when n is 40.  I'm guessing that the original code finds more, as when I ran it online, it timed out at five seconds even though counting the wrong solutions from this variant only took .12 seconds.  Note that that was with minimal output, so there could still be issues.


Is this good login process in CodeIgniter?

Simply use return $this->simpleloginsecure->login($email, $password) in the login method.
redirect('/user/xxx') is enough, since location is the default redirect type.
Since you're doing a redirect(), $data['message']is probably "dead code" here. Use CodeIgniter's Flashdata instead.
<p class="error"> should be handled in the view, the controller only needs to say there's an error. For example: $data['message'] = array('error' => 'This is my error text');
Trimming passwords is dangerous: what if my password starts with a space? Also, a space will look like a real character in an HTML password form, it makes no sense to trim it.
When the validation fails, redirect to the login form and use flashdata to explain what got wrong.


Perhaps I got off track somehow, but I found run() and
_work() difficult to understand. I was puzzled by the decision to use
two methods rather than one, I did not immediately grasp why two layers
of exception handling were needed, and the intent behind
the while True loop in run() wasn't immediately obvious.
Here are a few possible edits intended to simplify and clarify. Unless
I overlooked a detail, the edits:

do little more than move your
lines of code around, putting everything under run() other than
the completely separable stuff moved to _drain_queue();
rename
result to work_items for clarity; and
add a few short comments to
provide some simple narrative guidance to any future code readers.

def run(self):
    while True:
        # Get next work item, stopping on the sentinel.
        item = self._queue.get()
        if item is END_ITEM:
            break

        # Run the handler, enqueuing any work items it yields.
        try:
            work_items = self._handler(item.value)
            if work_items:
                for item in work_items:
                    self._queue.put(WorkItem(item))

        # On error, store exception and drain queue.
        except Exception as e:
            self._exception = e
            self._drain_queue()

        # Either way, mark current task done.
        finally:
            self._queue.task_done()

def _drain_queue(self):
    while True:
        try:
            self._queue.get(False)
        except queue.Empty:
            break
        else:
            self._queue.task_done()


Is my implementation of insertion sort is correct?

By inspection, your implementation is incorrect: arr[0] can never be written to.  The only code that writes to arr is inside the while loop, and the body of the while loop will only execute when j > 0.

In addition, the style could be improved.  Any code of the form

int j = …;
while (some condition involving j)
{
    …
    j--;
}

would be more easily recognizable if written as a for-loop.

The body of the inner loop looks like it performs swaps with neighbouring elements.  You should be able to shift multiple elements over by one slot by doing fewer writes than that.


Allowing googlebot to crawl a password protected page

Is this viable

Of course it is viable but as I am pretty sure somehow everyone can fake a googlebot without a detection by your script I don't recommend it. Another aspect is mentioned by 200_success. Google policies dislike such behaviour and it is highly recommend to follow their recommendations. At the end of the answer is a sample of my idea of implementation

Is this code solid/safe

General

It looks like you are developing procedural which is not recommend. OOP (object orientend programming) is the better way to go as it is a modular approach of developing software. In oop there are classes and each has specific task to solve. Wikipedia - Object-oriented-programming

Closing php tag

In the embedded source code you close the php tag which is not recommend. It might happen that a space is after a closing php tag and if you receive a headers already sent error it can be time consuming to identifiy the file where a space is after a closing php tag.

My idea of implementation

Independent of the google policies and that only x of y details should be indexed I would not make a google check but display the x of y details always and the z of y only if a function (e.g. userHasAccess($userid); ) returns true.

Sample

<!DOCTYPE HTML>

        <title>Detail</title>
        <meta name="robots" content="index">

User: John Doe

            A description about John Doe.

        <?php
            if (userHasAccess(2))
            {
                echo "
Age: 18
";
            }
        ?>

Such an implementation allows other search engines to crawl the x of y details while the z of y details are hidden for every search engine. You don't have to implement a googlebot verfication either.

Of course this sample has to be extended.


First a review...

Long extension chains

With lengthy linq chains it's a good idea to break them into multiple lines. Especially here on CR so that we don't have to scroll horizontally.

String interpolation

string answer = pangramCheck ? "pangram" : "not pangram";

We could optimize it as:

var answer = $"{(pangramCheck ? string.Empty : "not ")}pangram";

or you can make it even prettier by encapsulating this logic in an extension:

public static string Negate(this string value, bool negate)
{
    return $"{(negate ? string.Empty : "not ")}{value}";
}

so you then have:

Console.WriteLine("pangram".Negate(isPangram));

Consistency

string text
string answer

Don't you like var for strings because you already use for the other two variables? ;-)

Magic numbers

Enumerable.Range(97, 26)

This would be easier to understand if you used constants:

const string alphabetLength = z - a + 1;
Enumerable.Range('a', alphabetLength)

Not LINQ

.Replace(" ", "").ToLower()

This two kill the linq idea of your question. Consider this instead:

text
    .Select(char.ToLower)
    .Where(char.IsLetter)

Alternative solution

Then an alternative version...

If using a HashSet<char> is still linq-ish enougth then I replaced the Distinct with the Aggregate that uses one and makes it na O(n) solution for the English aphabet:

const int alphabetLength = 'z' - 'a' + 1;
var isPangram =
    text
    .Select(char.ToLower)
    .Where(char.IsLetter)
    .Aggregate(new HashSet<char>(), (acc, next) => { acc.Add(next); return acc; })
    .Count == alphabetLength;

UPDATE

Well, I forgot that we don't have to scan the entire string. As soon as we have the required chars we can stop. So this improved version should be faster for long texts:

const int alphabetLength = 'z' - 'a' + 1;
var chars = new HashSet<char>();

var testedChars = text
    .Select(char.ToLower)
    .Where(char.IsLetter)
    .TakeWhile(x => { chars.Add(x); return chars.Count != alphabetLength; })
    .Count();

var isPangram = chars.Count == alphabetLength;


Convert 2D list to dict of list of index

Your code has two nested loops for each array row, which means that you are having to scan every row multiple times to get your result. You can almost get what you want, but with a linear algorithm, doing the following:

d = {}
for idx, val in enumerate(c):
    d.setdefault(val, []).append(idx)

>>> d
{1: [0, 3, 4], 2: [1], 3: [2]}

This is missing the empty lists for items not present in the original lists. You can create those by doing:

for j in range(max(d.keys())): # Don't need max+1, the max is already there
    d.setdefault(j, [])

>>> d
{0: [], 1: [0, 3, 4], 2: [1], 3: [2]}

If your list has n items, and its max was m, your original algorithm was doing O(n*m) operations, while this will keep that to O(n+m).

Putting the whole thing together for 2D arrays I would put all of the above in a function and then go with a dict comprehension that called it, so something like:

def list2dict(a):
    ret = {}
    for idx, val in enumerate(a):
        ret.setdefault(val, []).append(idx)
    for val in range(max(ret.keys())):
        ret.setdefault(val, [])
    return ret

result = {idx : list2dict(val) for idx, val in enumerate(a)}


You don't actually need ServerName and ServerAlias directives for your port 80. This is due to the fact that your are using port-based virtual host. The "*" in the  tag indicates that all incoming connection to port 80 will follow the rules set with within the   tags. However, it is better to keep logs about incoming connections and errors when redirecting.

Therefore, for your port 80, the configuration should be like this:

<VirtualHost *:80>

Redirect permanent / https://example.com/

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

For port 443, the Redirect directive you put there will cause a redirect loop and you will need to remove that. Furthermore, you will need to include the CGI path within the  tags.
It is recommended that you put the CGI files outside of the DocumentRoot for security reasons (malicious visitors might reveal your code and attempt to do something bad). In this case let's say your CGI executables are located under the directory /usr/local/cgi-bin/ . Following that You will need to add the ScriptAlias directive to indicate the path to the CGI directory. Lastly, you need the AddHanlder directive to tells Apache to permit the execution of CGI files.

Remember to keep the logs for HTTPS connection too.

So here you go the configuration for port 443:

<VirtualHost *:443>

    ServerName example.com
    DocumentRoot /var/www/example.com/public_html

    SSLEngine on
    SSLCertificateFile /home/username/certs/example.com.pem
    SSLCertificateKeyFile /home/username/certs/example.com.key

    ErrorLog ${APACHE_LOG_DIR}/https_error.log
    CustomLog ${APACHE_LOG_DIR}/https_access.log combined

    ScriptAlias "/cgi-bin/" "/usr/local/cgi-bin/"

    <Directory "/usr/local/cgi-bin/">
         Options +ExecCGI
         AddHandler cgi-script .cgi .pl
    </Directory>

</VirtualHost>

The tutorial section located under the Apache2.4 Documentation will give you a fairly complete overview for this.


Find next number whose sum of digits is N

This is not a review, but an extended comment.

Thou shalt not brute force. Instead of inspecting every number larger than M (it indeed takes too much time), consider partitioning N into a sum of single digit numbers, and use these partitions to form the answer.

Notice that you don't have to inspect all the partitions. The digit composition of M gives enough leads to just construct the answer.


You could try the appropriately named #all? method:

reference = tests.first.result
if tests.all? { |test| test.result == reference }
  reference
else
  'mixed'
end

Edit: As tokland points out, you'll want to check if tests is empty before any of this. Otherwise, tests.first will of course be nil.

But you could also do the check in the database layer with something like:

if Test.select(:result).distinct.count > 1
  'mixed'
else
  Test.first.try(:result)
end

Obviously you'll want to scope the query more specifically.

Also note that here, an empty collection returns a nil (because if Test.first is nil, then .try(:result) will also be nil).


You say this is common in all handlers:

client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := client.Connect(ctx)
if err != nil {
    panic(err)
}

defer client.Disconnect(ctx)
collection := client.Database("myapp").Collection("questions")

So this means you're connecting and disconnecting to MongoDB for each request. That's incredibly wasteful. The MongoDB client is safe for concurrent use, so you can reuse the connection. Because I see code like this:

question.HandleFunc("", handler.PostQuestion).Methods("POST")

I know your handler functions are methods, so why not add the client to your handler type:

type yourHandler struct {
    coll   *mongo.Collection
}

Then, in your handlers you can simply access:

func (h *yourHandler) PostQuestion(w http.ResponseWriter, r *http.Request) {
    if err := h.coll.InsertOne(r.Context(), ...); err != nil {
        // write error response
        return
    }
}

Now your main function will look a bit different, seeing as we're not disconnecting the mongo client in the handler anymore, and we're not using a context with an arbitrary timeout. I suggest something like this:

func main() {
    // create the base context, the context in which your application runs
    ctx, cfunc := context.WithCancel(ctx.Background())
    defer cfunc()
    client, err := mongo.NewClient(
        options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
    if err != nil {
        log.Fatalf("Error creating mongo client: %+v", err)
    }
    defer client.Disconnect(ctx) // add disconnect call here
    if err := client.Connect(ctx); err != nil {
        log.Fatalf("Failed to connect to MongoDB: %+v", err)
    }
    // set collection on handler
    handler.coll = client.Database("myapp").Collection("questions")
    // rest of the code here
}

So now, whenever the main function returns, the application context is cancelled (which is used to connect the client), and client.Disconnect is called. The handler has access to the collection you're using, removing a lot of duplicate code, and removing the overhead of constantly connecting and disconnecting to MongoDB.

Inside your handler, I'm not using context.WithTimeout(context.Background(), 10*time.Second). Instead I'm using the request context, which means once the request context is cancelled, the query context is. You could still set a time-limit if you want:

func (h *yourHandler) PostQuestion(w http.ResponseWriter, r *http.Request) {
    // context expires if request context does, or times out in 3 seconds
    ctx, cfunc := context.WithTimeout(r.Context(), time.Second * 3)
    defer cfunc() // good form to add this
    if err := h.coll.InsertOne(ctx, ...); err != nil {
        // error response etc...
        return
    }
    // success response
}

Currently our handler requires the field coll to be of the type *mongo.Collection, which makes it harder to test your code. Instead, you might want to change that field to take an interface:

//go:generate go run github.com/golang/mock/mockgen -destination mocks/collection_interface_mock.go -package mocks your.module.io/path/to/handler/package Collection
type Collection interface{
    InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
    Name() string
    // all methods you need
}

In your unit tests, you can now inject a mock collection interface, that you can control, allowing you to simulate error returns, etc...

Instead of exposing the coll field on your handler, then, you'll also want to create a constructor function to inject the dependencies of what I have in the main function above (handler.coll = ...):

package service

type Collection interface{} // interface as above, with go generate comment

type handler struct {
    coll Collection
}

func NewHandler(c Collection) *handler {
    return &handler{
        coll: c,
    }
}

I'll leave you with this as a starting point. Just one thing I've not yet mentioned: you're using log.Fatalf when http.ListenAndServe returns an error. That's fine. Why are you using panic(err) when client.Connect(ctx) fails?

Panic is something you should avoid as much as possible. Especially here: it adds very little (to no) value: the only information a panic dump will yield is whereabouts in the mongo package something went awry. You don't control that package, so just log.Fatalf("Mongo error: %+v", err) is to be preferred.

More details

Seeing as your handler functions are actually functions in a package, rather than methods (which I initially thought they were):

I'd refactor the handler package to contain a constructor, and have the actual handler functions as methods on a type. Something like:

package handler

type Collection interface{
    InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
    Name() string
    // and so on
}

// main handler type
type Handler struct {
    coll Collection
}

// New returns the handler
func New(c Collection) *Handler {
    return &Handler{
        coll: c,
    }
}

func (h *Handler) PostQuestion(w http.ResponseWriter, r *http.Request) {
    if err := h.coll.InsertOne(r.Context(), ...); err != nil {
        log.Errorf("Insert question error: %+v", err)
        // write response
        return
    }
    // success response
}

From your main package, this will look like this:

func main() {
    ctx, cfunc := context.WithCancel(ctx.Background())
    defer cfunc()
    client, err := mongo.NewClient(
        options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
    if err != nil {
        log.Fatalf("Error creating mongo client: %+v", err)
    }
    defer client.Disconnect(ctx) // add disconnect call here
    if err := client.Connect(ctx); err != nil {
        log.Fatalf("Failed to connect to MongoDB: %+v", err)
    }
    // create handler with collection injected
    myHandler := handler.New(client.Database("myapp").Collection("questions"))

    // configure router to call methods on myHandler as handler functions
    // the handlers will now have access to the collection we've set up here
    r := mux.NewRouter()

    question := r.PathPrefix("/question").Subrouter()
    question.HandleFunc("", myHandler.PostQuestion).Methods("POST")
    // and so on
}


Calculate amount of necessary ingredients

I see some things that may help you improve your code.

Eliminate function prototypes by ordering

If you put the calc_bag implementations above main in the source code, you don't need the function prototype.

Avoid the use of global variables

I see that cup_ingredients and lemon_ingredients, etc. are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable.  In this case, these should all be in main rather than global.

Initialize variables

Global variables are initialized for you (to 0 for numeric variables), but local variables are not.  For that reason, you should also get into the habit of initializing variables, ideally when they're  declared.  For example:

double total[4] = {0.0, 0.0, 0.0, 0.0};
double cup_req = 0.0;
double lemon_req = 0.0;

Use const where practical

The ingredients lists cup_ingredients and lemon_ingredients, as well as the bag capacities Butter_size, etc. should all be constant.  For that reason, they should all be declared static const as in:

static const struct Bags Butter_size = {.big_bag = 500, .med_bag = 250, .small_bag = 125};

Then the calc_bag function should be this:

void calc_bag(double total_ingredient, const struct Bags* bag_sizes, struct Bags* type);

Simplify by using a typedef

The code you have isn't wrong, but it's often convenient to use a typedef for structures that are used frequently.  In this case, I'd suggest that your Bags structure could be this:

typedef struct bags_s {
    int big_bag;
    int med_bag;
    int small_bag;
} Bags;

Then instead of writing struct Bags everywhere, you can simply write Bags.

Prefer multiplication to iteration

Especially when using floating point numbers, it's most often better to multiply than to use iteration.  For example, the code currently has this:

printf("How many cupcakes would you like? ");
scanf("%lf", &cup_req);

for (int x = 0; x<cup_req; x++){
    for (int y = 0; y<4; y++){
        total[y] += cup_ingredients[y];
    }
}

That could be replaced by this:

for (int i = 0; i < 4; ++i) {
    total[i] += cup_req * cup_ingredients[i];
}

Similarly, your calc_bag function could use division rather than iteration.

Break up the code into smaller functions

The main function is quite long and does a series of identifiable steps.  Rather than having everything in one long function, it would be easier to read and maintain if each discrete step were its own function.  I'd be inclined to divide it into separate input, calculation, and output stages, each with the appropriate function.

Eliminate "magic values"

The value 4 is sprinkled through the code, but it really ought to be a named constant instead.  I'd give it a meaningful name like this:

#define INGREDIENT_COUNT 4

Rethink your data structures

The only difference between the cup_ingredients and lemon_ingredients is the name.  They're parallel structures.  This relationship could be made more clear by defining another structure which includes the name.  One might write it like this:

typedef struct recipe_s {
    char *name;
    double ingredients[INGREDIENT_COUNT];
} Recipe;

With that structure in place, one might rewrite main like this:

int main() {
    static const char *ingredient_name[INGREDIENT_COUNT] = {
        "butter", "eggs", "flour", "sugar",
    };
    static const Recipe recipes[] = {
        { "cupcakes", {4.0,0.1,12.0,14.0} },
        { "lemon cakes", {80.0,4.5,240.0,300.0} },
    };
    static const int recipe_count = sizeof(recipes) / sizeof(recipes[0]);
    Recipe total = { "total", {0.0, 0.0, 0.0, 0.0} };

    for (int i = 0; i < recipe_count; ++i) {
        double qty;
        printf("How many %s would you like? ", recipes[0].name);
        scanf("%lf", &qty);
        for (int j = 0; j < INGREDIENT_COUNT; ++j) {
            total.ingredients[j] += qty * recipes[i].ingredients[j];
        }
    }

    //Structs for the amount of each ingredient a bag can hold
    static const Bags capacity[INGREDIENT_COUNT] = {
        { 500, 250, 125}, // butter
        {  12,  10,   6}, // eggs
        { 750, 500, 250}, // flour
        { 600, 400, 200}, // sugar
    };

    // make a shopping list
    Bags shopping_list[INGREDIENT_COUNT] = {
        {0, 0, 0},  // butter
        {0, 0, 0},  // eggs
        {0, 0, 0},  // flour
        {0, 0, 0},  // sugar
    };

    //Calculate the amount of each ingredient bag required
    for (int i = 0; i < INGREDIENT_COUNT; ++i) {
        calc_bag(total.ingredients[i], &capacity[i], &shopping_list[i]);
        printf("%s: %d large bags, %d medium bags, %d small bags.\n",
            ingredient_name[i],
            shopping_list[i].big_bag,
            shopping_list[i].med_bag,
            shopping_list[i].small_bag
        );
    }
}

I'll leave it to you to divide that into smaller functions, but it should help you get an idea of how to write better C.

Other enhancements

I would be very disappointed if my grocer actually handed me a "bag of eggs."  Instead, the common quantities for different things have different units of measure such as a "dozen" or a "kilogram" or a "pound".  Using a similar idea of associating a name with constants (as with the recipes shown above), you might want to associate units of measure with each kind of ingredient.

Also, our lemon cake does not appear to have lemon as an ingredient, which makes it a somewhat less appealing confection.  Consider adding the ability to create arbitrary lists of named ingredients, consolidating them into a shopping list as above.


Find non-duplicated integer in a list where every integer occurs three times except for one integer

I'm going to take @greybeard's internet points, since he apparently doesn't want them enough to type this ;-).

You need to keep in mind that \$O(x)\$ really means \$O(C \times x + ...)\$ for some value C. As long as you keep C a constant, you can do whatever you want. Thus, \$O(n)\$ can really mean \$O(2000 \times n)\$, and \$O(1)\$ can really mean \$O(10^6)\$, etc.

In this case, what @greybeard has suggested is that you count the individual set bits in all the numbers, and keep the counts in separate positions. Thus, for an array of 32-bit numbers, you would keep 32 separate counts.

Since you have to perform in \$O(n)\$, you could spend one loop through your input array determining how many bits you need to keep, so even very large numbers won't break the solution.

So let's pretend all the integers are 8-bit, just because. That doesn't mean there aren't a large number of integers, just that all the values in the array are in the range [0, 256). What does that give you?

(If you don't know, & and << are "bitwise operators."

for each element in array:
    for each bit_offset in [0..8):
        if element & (1 << bit_offset):
            count[bit_offset] += 1

What does that get you? It gets you a set of 8 separate counts, one for each bit in the 8-bit numbers. (Feel free to replace 8 with 64 if you like...)

Each count represents the number of times that bit appeared "set" in the input array. Now, according to your premise, all the numbers but one appear 3 times. So all the set bits will appear a multiple of 3 times. (Since set bits might be duplicated among numbers, it won't be "exactly 3 times" but instead "a multiple").

On the other hand, the one value that appears one time will have its set bits added to the counts one time. So there are two possibilities for each of the count[i] values (note: k[i] is some numbers that don't matter):

Either the unique value does not have this bit set: count[i] = 3 * k[i]
Or the unique value does have this bit set: count[i] = 3 * k[i] + 1

So you have to evaluate each count[i] in order, and determine which form it takes:

result = 0
for bit_offset in [0..8):
    if count[bit_offset] % 3 == 1:
        result = set_bit(result, bit_offset)

Where set_bit is spelled |= 1 << bit_offset in most C-derived languages.

In terms of efficiency, what happens?

You might process the array once by iterating over it to discover the largest number of bits required to be counted.
You create an array of N_BITS counts, initialized to zero. Since N_BITS is not related to the size of the input array, this is considered \$O(1)\$. (Actually \$O(32)\$ most likely, or maybe 64... But that's still 1 in big-O-hio!)
You iterate over the array one time, iterating over N_BITS bit values within each element. (So effectively \$O(64 \times n)\$, or less.) You compute the count values here.
You iterate over the N_BITS counts, determining the bits that will be set in the result, and setting them.
You return the result.

So your runtime is \$O(2 \times n)\$, or just n if you hard-code the N_BITS. And your memory is \$O(64)\$ or less, which is just 1.

Let's look at the example you gave in the comments:

[13, 12, 12, 3, 3, 3, 12]

First, rewrite those to binary (8 + 4 + 2 + 1):

[ 0b1101, 0b1100, 0b1100, 0b0011, 0b0011, 0b0011, 0b1100]

Now, count the set bits, just adding all the 1's in each column (no carry!):

[ 0b1101,
  0b1100,
  0b1100,
  0b0011,
  0b0011,
  0b0011,
  0b1100]
  --------
    4434 -> counts = [ 4, 4, 3, 4 ]

Next, our output will be 1 if the count is 1 (mod 3) and 0 if the count is 0 (mod 3). So [4,4,3,4] mod 3 are [1,1,0,1]:

result = 0b1101

Which is 13.


keeping separate actions on a different line and tabbing your code will go a long way with making your code readable.
avoid declaring single-use variables
I don't see $brand_string being used, so that declaration can be omitted.
I do not prefer the endforeach syntax.  Despite being declarative, I find it unnecessarily verbose.  Good tabbing is always enough to help me track the nesting of control structures and functions.
move all inline styling to an external stylesheet.  Using meaningful class names to assign appropriate colors is most logical here.
I expect all
 tags are display: block; by default -- I doubt this style declaration is necessary.
use a lookup array to swiftly translate $term->name values into class attribute values and eliminate the mostly redundant if blocks.
don't declare $key if you never intend to use it.
filter the variations array based on the lowercase value of $term->name and use a conditional break for best efficiency.  I am confidently assuming that there will only be one match in your variations array based on the trailing

your list item should be nested inside of a list tag (e.g.
)
remove the  tags -- they are unnecessary markup.  If you need to style the list items, style the
 tags
if you must have your data processing in the same script as your content outputting, then I recommend doing your processing first, then keeping your markup readable by referencing the generated variables

Code:

$colorClasses = [
    'Roze' => 'roze-kleur',
    'Grijs' => 'grijze-kleur',
];
foreach (get_the_terms($post, 'pa_kleur') as $term) {
    $lowerColor = lcfirst($term->name);
    $colorUrl = 'you_decide_the_url';
    foreach ($product->get_available_variations() as $row) {
        if ($row['attributes']['attribute_pa_kleur'] === $lowerColor) {
            $colorUrl = $value['image']['url'];
            break;
        }
    }

    echo '

name] ?? 'default-kleur') , '">

' , $colorUrl , '

';
 }


Just a couple of quick thoughts.

DoScan and GetName probably should be initialised to NULL as well.
Load doesn't call Unload for any previous loaded dlls. If Load should be called once only per SaModule, that should be detected.
A more informative exception could be thrown. "...during attempted insertion of plugin xyz", for example.
Beware of function name decoration, if that could be an issue.


Picking a pattern based on employee type or department

You can't really do much to simplify this. There are 6 cases plus one default which means 7 different results, which means 7 lines to return and 6 conditions.

Unless you don't need to return a new thing every time. Assuming Pattern is from java.util.regex, this is the case. Then you can use something like

import com.google.common.collect.ImmutableMap;

private static final Map<String, Pattern> PATTERNS_FOR_TYPE =
    ImmutableMap.of(
    "individual", new IndivualPattern(),
    "multiple", new MultiplePattern(),
    "combined", new CombinedPattern());
private static final Map<String, Pattern> PATTERNS_FOR_DEPARTMENT = ...;

public static Pattern decidePattern(Employee employee) {
    Pattern result = PATTERNS_FOR_TYPE
            .get(employee.getType().toLowerCase(Locale.ENGLISH));
    if (result!=null) {
        return result;
    }
    Pattern result = PATTERNS_FOR_DEPARTMENT
        .get(employee.getDepartment().toLowerCase(Locale.ENGLISH));
    if (result!=null) {
        return result;
    }
    return new DefaultPattern();
}

But I wouldn't call it a big improvement. What you should do instead or in addition to it, is to get rid of the Strings, that's what enums are for.

In case you insist on Strings, you should normalize them ASAP. No equalsIgnoreCase, no toLowerCase anywhere but when when you encounter the inputs the first time.

Concerning catch Exception, no method can really throw an all possible Exceptions and you should be as specific as possible.

You can (and most probably should) use enums. The annotations come from project Lombok and do exactly what they say (you can do it manually, too).

@RequiredArgsConstructor @Getter
enum Type {
    INDIVIDUAL(new IndivualPattern()),
    MULTIPLE(new MultiplePattern()),
    COMBINED(new CombinedPattern()),
    ANOTHER(null),
    YET_ANOTHER(null);

    private final Pattern pattern;
}

... enum Department ...

public static Pattern decidePattern(Employee employee) {
    Pattern result = employee.getType().getPattern();
    if (result!=null) {
        return result;
    }
    ...
}

Not always it is a good idea to define the pattern in the enum itself. Then you can use a switch

public static Pattern decidePattern(Employee employee) {
    switch (employee.getType()) {
        case INDIVIDUAL: return new new IndivualPattern();
        ...
        default: // (just to prevent "missing label" warning)
    }
    switch (employee.getType()) {
        ...
    }
    ...
}


Is there a better way to convert two-dimentional array to string?

First off, I think there may be bugs in your code. Specifically in the dimension parameters of some of the GetLowerBound() parameters. Based on a quick glance, it should be:

private static string OneRowPerLine(double[,] numbers)
{
    var ret = new StringBuilder();
    for(var i=numbers.GetLowerBound(0);i<=numbers.GetUpperBound(0);i++)
    {
        for (var j = numbers.GetLowerBound(1); j <= numbers.GetUpperBound(1); j++)
        {
            if(j>numbers.GetLowerBound(1))
            {
                ret.Append(",");
            }
            ret.Append(numbers[i, j]);
        }
        ret.Append(Environment.NewLine);
    }
    return ret.ToString();
}

I'll update this answer in a moment with some enhancements, but wanted to get this bit out of the way.

EDIT: here's a pair of methods which will do it a little more generically and without LINQ. It does employ generics (<T>) and extension methods (this), one of which is an iterator (yield return):

    private static string OneRowPerLine<T>(this T[,] numbers)
    {
        return string.Join(Environment.NewLine, numbers.FormatOneRow());
    }

    private static IEnumerable<string> FormatOneRow<T>(this T[,] numbers)
    {
        for (var i = numbers.GetLowerBound(0); i <= numbers.GetUpperBound(0); i++)
        {
            var row = new T[numbers.GetLength(1)];

            for (var j = numbers.GetLowerBound(1); j <= numbers.GetUpperBound(1); j++)
            {
                row[j] = numbers[i, j];
            }

            yield return string.Join(",", row);
        }
    }

call like this:

    double[,] stuff = {{1,2}, {3,4}, {5,6}};
    Console.WriteLine(stuff.OneRowPerLine());


Generic test serie for various solutions to the same algorithmic problem

Embrace Python's simplicity! This is a dynamic language, we care less about inheritance and complex data models and focus more on the actual problem. Of course, it has its drawbacks, but that's how it works.

The answer your question: no, in Python, we wouldn't derive classes and so on but just write the code you wrote. It's still possible to define an abstract base class A with specific methods and extend it with a few implementations, but really think about the benefits before doing this.

Note about the code: PEP 8 is a standard style guide important in the Python word: space between operators and no camelCase in variable names are the two that come to mind while reading your code.

Finally, performance is another concern than unit testing (except if you find a reliable way to test for the complexity of your algorithms). I recommend the timeit module. It doesn't say how to test for complexity, but it's a good start to measure time spent in a method.


Counting single degree vertex removal rounds (from a graph)

Naming

Explicit names can go a long way in conveying what a piece of code does. Combine that with unpacking and explicit assignments to name parts of sequences, you can get:

from collections import defaultdict

n, m = map(int, input().split())
edges = [tuple(map(int, input().split())) for _ in range(m)]
adjacents = defaultdict(set)
for node1, node2 in edges:
    adjacent[node1].add(node2)
    adjacent[node2].add(node1)

degrees = defaultdict(set)
for node, neighbours in adjacents.items():
    degrees[len(neighbours].add(node)

if len(degrees[1]) == 0:
    print('0')
else:
    count = 0
    while len(degrees[1]) > 0:
        dec = defaultdict(lambda: [list(), 0])  # Can't figure out a good name for that
        singles = degrees[1]
        while len(singles) > 0:
            single = singles.pop()
            for node in adjacent[single]:
                dec[node][0].append(single)
                dec[node][1] += 1
            del adjacent[single]
        for node, (neighbours, count_neighbours) in dec.items():
            node_degree = len(adjacent[node])
            if node in degrees[node_degree]:
                degrees[node_degree].remove(node)
                degrees[node_degree - count_neighbours].add(node)
                for neighbour in neighbours:
                    adjacent[node].remove(neighbour)
        count += 1
    print(count)

Quick simplifications

We can see from there that some parts are unnecessary complicated: for node in adjacent(single) does not need to be a loop as there must be only one node adjacent to a node with degree 1. You can use unpacking to exctract this value; it will also let you ensure that there was actually only one value there:

while len(singles) > 0:
    single = singles.pop()
    neighbour, = adjacent[single]  # Do not forget the comma here
    del adjacent[single]
    dec[neighbour][0].append(single)
    dec[neighbour][1] += 1

You also have if len(degrees[1]) == 0: ... else: while len(degrees[1]) > 0 which are pretty much the same thing. You can remove the if, if there is no node of degree 1, then the while won't execute and count will still be 0.

Pythonic constructs

Every containers (lists, dicts, strings, sets, …) are considered False in a boolean context if they are empty and True otherwise. Which mean you should write while degrees[1]: or if not degrees[1].

You may also have noticed the use of dict.items() to iterate over both the keys and the values of a dictionnary at the same time. It is more efficient than using the key to retrieve the values latter.

You also don't really need to build a list of edges before building the dictionnary of adjacent nodes:

from collections import defaultdict

_, m = map(int, input().split())

adjacents = defaultdict(set)
for _ in range(m):
    node1, node2 = map(int, input().split())
    adjacent[node1].add(node2)
    adjacent[node2].add(node1)

degrees = defaultdict(set)
for node, neighbours in adjacents.items():
    degrees[len(neighbours].add(node)

count = 0
while degrees[1]:
    dec = defaultdict(lambda: [list(), 0])  # Can't figure out a good name for that
    singles = degrees[1]
    while singles:
        single = singles.pop()
        for node in adjacent[single]:
            dec[node][0].append(single)
            dec[node][1] += 1
        del adjacent[single]
    for node, (neighbours, count_neighbours) in dec.items():
        node_degree = len(adjacent[node])
        if node in degrees[node_degree]:
            degrees[node_degree].remove(node)
            degrees[node_degree - count_neighbours].add(node)
            for neighbour in neighbours:
                adjacent[node].remove(neighbour)
    count += 1

print(count)

Adding and removing nodes

You spend quite a lot of time moving nodes around in various lists and dictionaries. You could simplify the whole thing by using a more straightforward approach:

you only need to keep track of the nodes with degree 1
for each of these nodes:

remove it from its neighbour list of neighbours
if this neighbour now has degree 1, keep track of if in a temporary set

when done, iterate with the new set of nodes with degree 1.

from collections import defaultdict

_, m = map(int, input().split())

adjacents = defaultdict(set)
for _ in range(m):
    node1, node2 = map(int, input().split())
    adjacent[node1].add(node2)
    adjacent[node2].add(node1)

singles = {node for node, neighbours in adjacents.items() if len(neighbours) == 1}
count = 0
while singles:
    new_singles = set()
    for single in singles:
        neighbour, = adjacents[single]
        adjacents[neighbour].remove(single)
        if len(adjacents[neighbour]) == 1:
            new_singles.add(neighbour)
        # del adjacents[single] if you whish but it has no added value here
    singles = new_singles
    count += 1

print(count)

Functions

Using can help make things faster as Python resolves local symbols faster than global ones. But mainly recommended to organise the flow of things better and reuse parts of code.

You should also wrap the top-level code that you don't want to put in a function under an if __name__ == '__main__' clause:

from collections import defaultdict

def remove_singles(adjacents):
    singles = {node for node, neighbours in adjacents.items()
               if len(neighbours) == 1}

    passes = 0
    while singles:
        new_singles = set()
        for single in singles:
            neighbour, = adjacents[single]
            adjacents[neighbour].remove(single)
            if len(adjacents[neighbour]) == 1:
                new_singles.add(neighbour)

        singles = new_singles
        passes += 1

    return passes

if __name__ == '__main__':
    _, m = map(int, input().split())

    graph = defaultdict(set)
    for _ in range(m):
        node1, node2 = map(int, input().split())
        graph[node1].add(node2)
        graph[node2].add(node1)

    print(remove_singles(graph))


Returning an error message instead of data is not a good approach to handling errors. Try and see what happens if you tweak your code to pass an invalid argument to find_circular_primes_under. Do you see your error message? No, the program raises an exception trying to format the return value as a number. It would be better to raise an appropriate exception instead of returning from the function.
Modifying a container while iterating over it causes undefined behavior. In is_circular you could use for _ in xrange(len(digits)): instead of for digit in digits: to be safe. The digit variable is not used anyway.
You could take advantage of collections.deque and its rotate method to produce the rotations.


Add one to integer represented as an array

Run the code through pycodestyle, then understand and apply all of the recommended changes. This is tedious the first couple times, but you'll learn to write much more idiomatic Python.
The class is pointless - you might as well just write a bare function instead. __init__ also creates a field which is then never used.
Names like A make the code harder to read. Naming your variables what they actually are makes the code much easier to read.
I would swap around your first if/else to avoid the negative comparison.
You use a number for carry, but it might as well be boolean because it can never be more than 1.
Personally I consider this code hard to understand. You reverse the list twice (making a copy both times), add and remove to it. This is my take on it:

def increment(digits):
    for index, digit in reversed(list(enumerate(digits))):
        if digit == 9:
            digits[index] = 0
        else:
            digits[index] += 1
            return digits
    digits.insert(0, 1)
    return digits

if __name__ == '__main__':
    print(increment([0]))
    print(increment([9,0,0]))
    print(increment([6,9,9]))
    print(increment([9,9,9]))
    print(increment([0,9,9,9]))
    print(increment([0,0,0,1,2,3]))

Reverse the list one element at a time
Set trailing nines to zero
If any number is not nine, increment it and we're done
If we get through the whole list, it must have been all nines, so we add a one to the start and return
This code treats an empty list as zero, which may or may not be allowed in the exercise.


Let's make this testable

With a small twist, the function can become testable.
Instead of finding the real path of the current script,
it would be better to generalize it to find the real path of any path:

real_path()
{
    result=$1

    # ...
}

Fails to follow relative symlinks correctly

Now that the script is testable, here's a test it will not pass:

mkdir -p /tmp/a
touch /tmp/a/b
(cd /tmp/a; test -L /tmp/a/c || ln -s ../a/b c)

echo $(real_path /tmp/a/c)

The output will be ../a/b instead of the expected /tmp/a/b.
Basically if there are relative links in the chain of links recursively followed, the script will break.

Alternative implementation

This is what I use in production, and I haven't seen a corner case yet where it breaks:

real_path() {
  target=$1

  (
  while true; do
    cd "$(dirname "$target")"
    target=$(basename "$target")
    test -L "$target" || break
    target=$(readlink "$target")
  done

  echo "$(pwd -P)/$target"
  )
}

Notice that the portion where the function changes the working directory is wrapped within a (...) sub-shell.
This is probably overkill,
but I think it's good to eliminate side effects as a general principle.


AngularJS recursive function call with $timeout

You're almost there. But first, a few code smells:

function getLocation(query, map, object, delay) {
    ...
    service.textSearch({ query: query }, function (results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            ...
            object.lang = loc.lng();
            object.lat = loc.lat();
            deferred.resolve(object);
        }
        ...
    ...
}

Your function returns a promise that resolves with an object containing lat and long. However, you are mutating an object called object. The problem here is the unwanted side effect. If you ever want to use this function elsewhere, you have to supply it an unnecessary object. If you also pass in an existing object, you unintentionally introduce lat and long.

if (status == google.maps.places.PlacesServiceStatus.OK) {
  ...
} else {
  if (status === "OVER_QUERY_LIMIT") {
    ...
  }
}

That google.maps.places.PlacesServiceStatus.OK is very long and visually annoying. Consider putting it in a shorter variable. Also, the if statement in the else block can be collapsed as an else if of the first if statement.

Lastly, the deferred pattern is actually an anti-pattern. Wrap your operation in a promise constructor instead of having a dangling deferred.

If I understand correctly, you need to do a location request, and retry on fail. You simply call your API. Resolve and reject accordingly.

function getLocation(query, map, retryTimeout){
  var service = new google.maps.places.PlacesService(map);
  var OK = google.maps.places.PlacesServiceStatus.OK;
  var OVER_LIMIT = 'OVER_QUERY_LIMIT';

  return new Promise(function(resolve, reject){
    service.textSearch({ query: query }, function (results, status) {
      var loc = results[0].geometry.location;

      if(status === OK ){
        resolve({ lat: loc.lat(), lang: loc.lang() });
      } else if(status === OVER_LIMIT){

        // The most interesting part. Reschedule a retry.
        setTimeout(function(){

          // When the promise of this call resolves then...
          // call the resolve/reject of the enclosing (previous) promise
          getLocation(query, map, retryTimeout).then(resolve, reject);
        }, retryTimeout);

      } else {
        reject(new Error(status));
      }
    });
  });
}

// Usage:
var object= {...}
var locationPromise = getLocation(query, map, 1000);

locationPromise.then(function(locationData){
  // Only then do you mutate. Only have getLocation get the location data.
  // Mutating object is not its concern. It's the consumer's concern.
  object.lat = locationData.lat;
  object.lang = locationData.lang;
});

Now here's the trick. In order to make getLocation act like a recursive call, you simply call getLocation again, but hand over the resolve and reject of the enclosing promise as its callbacks. When the succeeding getLocation call succeeds, it will call the previous promise's callbacks.

So in terms of execution, it's not really recursive and the entire operation is still async. However, how the promises enclose each other one call after the other and pass on their resolve and reject as callbacks to the next makes it act recursive.

Of course we cannot escape the wrath of setTimeout since we need it for delay.

Since Promises are not widely supported yet, you can use Angular's built-in $q which does the same thing, and probably more.


A first thing to note is that you are creating a lot of COMObjects in a similar manner, we can simply extract that behavior as a separate function. Then, we note that you are expecting file names as parameters where you could expect an item instead; that allows you to pass on items to Create-List3 instead, thus allowing for piping Get-ChildItem into rather than doing extra conversion calls back and forth.

As a result of this two things we're left with a lot of Split-Path calls, we can simply port them over to extracted function as well, it appared that you only needed one of the Split-Pat calls only once. After that, some small cleanup has been done (removing $test1, adding extra newlines and spaces for readability) and we already have much cleaner code to continue from:

Function Get-ShellFolder($fileItem)
{
    $folder = Split-Path $fileItem.FullName

    $shell = New-Object -COMObject Shell.Application
    return $shell.Namespace($folder)
}

Function Enumerate-Properties($fileItem)
{
    $shellfolder = Get-ShellFolder $fileItem

    0..287 | Foreach-Object {'{0} = {1}' -f $_, $shellfolder.GetDetailsOf($null, $_)}
}

Function Find-Property($fileItem, $PropertyName)
{
    $shellfolder = Get-ShellFolder $fileItem

    $found = false
    0..287 | Foreach-Object {
        if ($PropertyName -eq $shellfolder.GetDetailsOf($null, $_))
        {
            $found = true
            return $_
            break
        }
    }

    if (!$found) {
        Write-Host "Property " $PropertyName " was not found"
    }
}
Function Get-PropertyValue($fileItem, $property)
{
    $shellfolder = Get-ShellFolder $fileItem

    $file = Split-Path $fileItem.FullName -Leaf
    $shellfile = $shellfolder.ParseName($file)

    return $shellfolder.GetDetailsOf($shellfile, $property)
}
Function Create-List3($files, $property)
{
    $array = @()
    $propertyNum = Find-Property $files[0] $property
    foreach($file in $files)
    {
        $file | Add-Member -MemberType noteproperty -Name $property -Value (Get-PropertyValue $file $propertyNum).toString() -force
        $array = $array + $file
    }
    return $array
}

From here on, you could look for things that are already implemented in Powershell to make the code even more simple, as well as adding documentation to make some less obvious things easier to understand for fellow readers.


Parsing XML data to be put onto a site with jQuery

Don't use selector all the time. DOM locating waste most resource and time. as less selector as possible. use variable cache the jQuery object.

Data is look like a root:

var $data = $("Data");

Rather than parse start with "category_number", why not start with "Category"

$(xml).find('Category').each(function(){
    //do something.
});

Also, you could use filter() or map() to reduce the code:

// filter() example
function getSubCategory(pid){
    $catalist = $data.find("Category").filter(function(){
       return $(this).find("parent_number").text()==pid;
    })

    return $catalist;

}

// map() example
var subCatString=$subCatList.map(function(sum,item){
    var $subCat=$(item) ;
    var vcum=$subCat.find("category_number").text();
    return '
'+vcum+'
'
}).get().join();

Combine them together (HTML, see this JSFiddle, don't use AJAX):

var $xml= $("xml");
var $data=$xml.find("Data");
var $displayList=$("ul#category_list");

$xml.find("Category").each(function(){
    var $catageory=$(this);
    var $cnum=$catageory.find("category_number");
    var $pnum=$catageory.find("parent_number");
    var $cname=$catageory.find("category_name");

    var $subCatList=getSubCategory($cnum.text());
    var subCatString=$subCatList.map(function(sum,item){
        var $subCat=$(item) ;
        var vcum=$subCat.find("category_number").text();
        return '
'+vcum+'
'
    }).get().join();

    var $ul=$("
",{class:$cnum.text()});

    $ul.append(subCatString);

    $displayList.append($("
").html($ul));

});

function getSubCategory(pid){
    $catalist = $data.find("Category").filter(function(){
       return $(this).find("parent_number").text()==pid;
    })

    return $catalist;

}


When you have cascading conditions like you have, it can become 'messy'. At some point the design-pattern 'Chain of responsibility' becomes useful....

Consider an interface:

public interface GPSelector {
    String selectGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate);
}

Then, consider an array of concrete implementations of that interface:

private static final GPSelector[] GPRULES = new GPSelector[] {

    // 1-year rule
    new GPSelector() {
        public String selectGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate) {
            List<String> lastyear = customSubMap(gpCollection, new DateTime(i).minusMonths(12).getMillis(), calcdate);
            if (lastyear.size() == 1) [
                return lastyear.get(0);
            }
            return null;
        }
    },

    // 6-month rule
    new GPSelector() {
        public String selectGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate) {
            // return not-null String if there is a successful 6-month candidate....
        }
    },

    .......

};

OK, so now you have an ordered array of rules that progressively select the right UsualGP candidate.

I your code, you can now simply have the following:

public String selectUsualGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate) {
    for (GPSelector rule : GPRULES) {
        String gp = rule.selectGP(gpCollection, calcdate);
        if (gp != null) {
            return gp;
        }
    }
    return null; // nothing matched.... :(
}

Adding a new rule is easy, just insert it in to the chain at the appropriate place....

I hope the above is enough to show how the chain-of-responsibility pattern can be applied.


Formatting the Lengthy Parameters in a better way

Best option would be to just use *args (or **kwargs if order does not matter), as follows:

class QuickModeConverter(object):
    def run(self, *args):
        convert_to_quick_mode(*args)


Simple calculator (going H.A.M with defining functions)

Of the feedback on your earlier version of this programme, the most obvious thing that you haven't done yet is to use lower() on text inputs so that you only have to compare against lower case options. e.g.

    again = input("Again? Yes/No: ").lower()
    if again == "yes":
        break
    elif again == "no":
        sys.exit(0)

It might be useful to know that the operations you define already exist as methods of numeric variables in Python, called __mul__, __add__, etc., and are also available within the operator module. e.g. operator.add(3, 4) is equivalent to 3 + 4. So you could, for example, do this

import operator

OPTIONS = {
    'divide': operator.truediv,
    'multiply': operator.mul,
    'add': operator.add,
    'subtract': operator.sub
}

def user_input():
    while True:
        try:
            return int(input("Number: "))
        except ValueError:
            print("NOPE...")

def get_operation():
    while True:
        operation = input("Multiply/Divide/Add/Subtract: ").lower()
        try:
            return OPTIONS[operation]
        except KeyError:
            print("Not an option.")

def play_again():
    while True:
        again = input("Again? Yes/No: ").lower()
        if again == "yes":
            return True
        elif again == "no":
            return False
        else:
            print("Nope..")

while True:
    operation = get_operation()
    x = user_input()
    y = user_input()
    print(operation(x, y))
    if not play_again():
        break


Simple C# application that transfers new files (modified in the last 24 hours) from one directory to another

A few notes, not in order of importance, just as I see them. Keep in mind this is just my opinions but I think they're important especially since you're starting out. You can form bad habits later :)

Your classes and methods should always explicitly define their level of accessebility. e.g. class Functions should be public class Functions
Always check if a file or directory exists before opening: var directory = new DirectoryInfo(sourceDir); should be:

DirectoryInfo directory;
if (Directory.Exists(sourceDir))
    directory = new DirectoryInfo(sourceDir);

User input should always be compare in one case for example answerExit == "y" should be answerExit.ToLower() == "y" Unless you want to make response case sensitive.
System directories should not be explicitly entered. For example : "C:\Users\Student\Desktop\Customer Orders" should be Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"Customer Orders");
Your Functions class is superfluous. Those methods directly relate to activities in Main, they can't be used separately or anything else and should definitely be static.
Your method modified() return an IEnumerable and I think that this line also return an IEnumerable

var files = directory.GetFiles()
      .Where(file => file.LastWriteTime >= from_date &&
      file.LastWriteTime <= to_date);` So why return a .ToList()?

I think that's a good start.


You can use np.roll to compute the centered differences as a vectorised operation rather than in a for loop:

res = (np.roll(y, -1) - np.roll(y, 1)) / (np.roll(x, -1) - np.roll(x, 1))

You then still need to account for incorrect values at the boundaries.

Also note that you have a bug at the line

size = len(y0)

It should be len(y). But you don't need it anymore as you can access the last values as y[-1] or x[-2].

Lastly, consider putting your test code under an if __name__ == '__main__' clause.


AngularJS: Http API Service - any improvements / remarks?

A few ideas - nothing major :

Encapsulating the methods in self doesn't really add anything. A set of function statements or function expressions would do the job and self. could be purged all through.
The explicit promise construction antipattern should be purged.
"method" would be better understood than "verb".
Does DoRequest() not throw when data is not passed? Do range checking in doRequest() instead of ExecuteRequest().
Possibly allow for omitted uri, defaulting to empty string (browser will use current page's url). Could be useful in some use cases.
By convention Initial-caps are reserved for constructors. Change to lower-case all through.
Possibly use Function.prototype.bind() in the exposer. (Check that browser compatibility is acceptable).

angular.module("services.api").factory("apiService", [
"$http",
"$q",
"coreUtilityService",
"constantsServiceNames",
"constantsApiRequestFor",
function (
    $http,
    $q,
    coreUtilityService,
    constantsServiceNames,
    constantsApiRequestFor
) {
    // === START SERVICE === //
    // var name = constantsServiceNames.ApiService; // necessary?
    var executeRequest = function(method, fullUri, data) {
        method = method.toLowerCase();
        var httpArgs = [fullUri];
        if (data) {
            httpArgs.push(data);
        }
        return $http[method].apply(null, httpArgs).then(null, function (response) {
            throw new Error("HTTP Error: " + response.status);
        });
    };
    /*
    Do a request to any RESTful receiver. Meant for external use only, use DoViewRequest
    for internal requests.
    */
    var doRequest = function (method, uri, data) {
        uri = uri || '';
        data = (!data || !method.match(/post|put/)) ? null : data; // or similar
        return ExecuteRequest(method, coreUtilityService.GetBaseUrl(constantsApiRequestFor.WebAPI, uri), data);
    };
    /*
    This will target an MVC View of the client application. The url will be different.
    */
    var doViewRequest = function (method, uri) {
        uri = uri || '';
        var fullUrl = coreUtilityService.GetBaseUrl(constantsApiRequestFor.View, uri);
        return ExecuteRequest(method, fullUrl, null);
    };
    // === PUBLIC === //
    return {
        'get':    doRequest.bind(null, 'get'),
        'post':   doRequest.bind(null, 'post'),
        'put':    doRequest.bind(null, 'put'),
        'delete': doRequest.bind(null, 'delete'),
        'view':   doViewRequest.bind(null, 'get')
    };
    // === END SERVICE === //
}]);


Printing out JSON data from Twitter as a CSV

Put all import statements at the top.
You might leak a file descriptor, since you call open(sys.argv[1]) without closing it.  (Whether a leak actually occurs depends on the garbage collector of your Python implementation.)  Best practice is to use a with block, which automatically closes the resources when it terminates.

with open(sys.argv[1]) as in_file, \
     open(sys.argv[2]) as out_file:
    …

It would be better to define your variables in the same order as they will appear in the CSV output.
Rather than creating an empty array and appending to it in a loop, use a list comprehension.

tweets = [json.loads(line) for line in in_file]

You read all the tweets into an array of JSON objects, then slice the data "vertically" by attribute, then re-aggregate the data "horizontally".  That's inefficient in terms of memory usage as well as cache locality.
Unless you have a good reason, just transform one line of input at a time.  (A good reason might be that you want to produce no output file at all if an error occurs while processing any line.)

import json
import sys
from csv import writer

with open(sys.argv[1]) as in_file, \
     open(sys.argv[2], 'w') as out_file:
    print >> out_file, 'tweet_id, tweet_time, tweet_author, tweet_author_id,    tweet_language, tweet_geo, tweet_text'
    csv = writer(out_file)
    tweet_count = 0

    for line in in_file:
        tweet_count += 1
        tweet = json.loads(line)

        # Pull out various data from the tweets
        row = (
            tweet['id'],                    # tweet_id
            tweet['created_at'],            # tweet_time
            tweet['user']['screen_name'],   # tweet_author
            tweet['user']['id_str'],        # tweet_authod_id
            tweet['lang'],                  # tweet_language
            tweet['geo'],                   # tweet_geo
            tweet['text']                   # tweet_text
        )
        values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
        csv.writerow(values)

# print the name of the file and number of tweets imported
print "File Imported:", str(sys.argv[1])
print "# Tweets Imported:", tweet_count
print "File Exported:", str(sys.argv[2])


Constants fizz and buzz should be ALL_CAPS, by convention.

The use of status and the switch is unjustified.  Why complicate things by setting a variable to alter behaviour a few lines later?

public class FizzBuzz {

    public static final int FIZZ = 3;
    public static final int BUZZ = 5;

    public static void main(String[] args) {
        for (int fbNumber = 1; fbNumber <= 100; fbNumber++) {

            if ((fbNumber % FIZZ == 0) && (fbNumber % BUZZ == 0)) {
                System.out.println("FizzBuzz");
            } else if ((fbNumber % FIZZ == 0) && (fbNumber % BUZZ != 0)) {
                System.out.println("Fizz");
            } else if ((fbNumber % FIZZ != 0) && (fbNumber % BUZZ == 0)) {
                System.out.println("Buzz");
            } else {
                System.out.println(fbNumber);
            }
        }
    }
}


First one is hundred times better then the second one. I would avoid defining a variable if you don't really need to. Also I don't believe in one return methods. Especially I don't believe that they improve readability.

LINQ would definitely improve it:

return classScatterViews.FirstOrDefault(v => v.Tag.Equals(find));

Also I would not use as operator if I do not check result for null.


Efficiently determining if a number is prime

A faster method would be to skip all even numbers and only try up to the square root of the number.

public static boolean isPrime(int num){
    if ( num > 2 && num%2 == 0 ) {
        System.out.println(num + " is not prime");
        return false;
    }
    int top = (int)Math.sqrt(num) + 1;
    for(int i = 3; i < top; i+=2){
        if(num % i == 0){
            System.out.println(num + " is not prime");
            return false;
        }
    }
    System.out.println(num + " is prime");
    return true;
}


MySQL database connection in the constructor

A better practice is passing a created DB instance to the Users class. Imagine that you have a Products class, an Orders class etc. Will all of their constructors create a separate MySQL connection? It doesn't look a good idea since all of them could use the same database connection.

class Users {
    private $db;

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

    ....
}

class Products {
    private $db;

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

    ....
}

$db = new DB();
$users = new Users($db);
$products = new Products($db);


Some notes about the current code:

extends Objects looks unnecessary in the class declaration:

public class MultiMap<K1 extends Object, K2 extends Object, V extends Object> {

I'm not completely sure but the following seems to be the same:

public class MultiMap<K1, K2, V> {

I'd rename res to oldValue or something more descriptive.
Modern IDEs use highlighting to separate local variables from fields, so don't need to use this.. It's rather noise.
Comments like this are just noise:

 /**
 * @param map1
 * @param map2
 */

It doesn't say anything more than the code says. Furthermore, the constructor does not have any parameter like map1 or map2. (Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)


Implementing sbrk for a custom allocator in C

Interface: consider accepting larger types than int.  The Linux man page says:

Various systems use various types for the argument of sbrk().  Common are int, ssize_t, ptrdiff_t, intptr_t.

ptrdiff_t seems like the most appropriate choice.  Of course, it doesn't really matter with this implementation, as the capacity is less than 32768, and so even a minimal INT_MAX allocation will fail.

if(((char*)p_break + increment) < (char*)global_mem)

Since we have no guarantee that p_break + increment won't overflow, we should re-write that as:
if (increment < global_mem - (char*)p_break)

We know that global_mem - p_break can't overflow, as they are pointers into the same object.
Similarly,

if(((char*)p_break + increment) > (char*)final_address)

should be rewritten as
if (increment > (char*)final_address - (char*)p_break)

We can avoid all the casts here by using char* pointers rather than void* - only the public interface needs the void*.

I hope the ERR macro is compiled out in non-debug builds - users certainly won't want or expect output from sbrk.
The error paths should set errno to ENOMEM.

Modified code
#include <errno.h>

#define MEMORY_CAPACITY 20000

void *mov_sbrk(int increment)
{
    static char global_mem[MEMORY_CAPACITY] = {0};
    static char *p_break = global_mem;

    char *const limit = global_mem + MEMORY_CAPACITY;
    char *const original = p_break;

    if (increment < global_mem - p_break  ||  increment >= limit - p_break)
    {
        errno = ENOMEM;
        return (void*)-1;
    }
    p_break += increment;

    return original;
}

(I moved the global variables into the function to reduce their scope; that might not be appropriate if you also want to implement brk(), but I'm only reviewing the code I see!)


Writing many cells to sheet causes Excel to not respond, replacing vlookups

As was explained in comments elsewhere, the Excel VBA thread is sending messages to the WM message queue to process information, but the same thread is running the for/next loop(s) and will not begin as you had the code until the loops are complete.  By inserting a DoEvents, it causes the VBA code to perform slower because it then allocates some time to the O/S to take care of other pending WM messages and returns back to the VBA code.  Too many DoEvents will greatly slow down your code processing and can even be harmful in some cases where another process can actually take over (hog) more processor time.  The solution is to use DoEvents sparingly to allow Excel to process the rows a few at a time.  What the ideal number is varies by situation, but you can experiment with various batch sizes determined by using modulo arithmetic.

Modify your loop in this way:

        Next thisCol
        If (thisRow Mod 100) = 0 Then
            DoEvents
        End If
    Next thisRow

You can tweak this number by replacing 100 with 10, 50, 250, 500, etc. to see what provides the most desirable result.


Unit testing for Python function that checks whether a value is in a range

Regarding your tests.  You definitely don't have too many.  You actually could have too few.  Consider:

In one dimension, you have 5 cases you can check:

val < min
val == min
min < val < max
val == max
val > max

In another dimension, you have inclusive=True and inclusive=False.  That makes at least 10 combinations you should test.  You also have a "inclusive uses the default" which could add 5 more.

Then, you have allowed_range which expects a tuple with limits in either order.  So you should test allowed_range=(1.5, 5.1) separate from allowed_range=(5.1, 1.5).  That would further double the number of tests.

What about tests where min == max, using both inclusive and non-inclusive limits?

You don't need to write separate functions for each test; each function can easily perform a suite of several tests:

def test_unequal_limits(self):
    #          val, min, max, incl,  excl
    tests = [ (1.5, 2.5, 5.5, False, False),
              (2.5, 2.5, 5.5, True,  False),
              (3.5, 2.5, 5.5, True,  True),
              (5.5, 2.5, 5.5, True,  False),
              (6.5, 2.5, 5.5, False, False) ]
    for val, lower, upper, incl, excl in tests:
          assert is_in_range(val, (lower, upper)) == incl
          assert is_in_range(val, (lower, upper), False) == excl
          assert is_in_range(val, (upper, lower)) == incl
          assert is_in_range(val, (upper, lower), False) == excl

def test_equal_limits(self):
    #          val, limit, incl
    tests = [ (1.5, 3.5,   False),
              (3.5, 3.5,   True),
              (5.5, 3.5,   False) ]
    for val, limit, incl in tests:
          assert is_in_range(val, (limit, limit)) == incl
          assert is_in_range(val, (limit, limit), False) == False

You test exactly one case where all inputs are non-numeric strings.  You probably need to test the minimum, maximum, and value separately.

Regarding your function is_in_range() function.

Why raise a ValueError when the input is considered to be "non-numeric"?  Without the non-numeric check, is_in_range("tt", ("a","zzz")) would return True, which would be quite acceptable.

The non-numeric check causes more problems:

>>> val = 1000000000000000000
>>> is_in_range(val, (val-1, val+1))
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    is_in_range(val, (val-1, val+1))
  File "<pyshell#8>", line 11, in is_in_range
    raise ValueError("Inputs must be numeric.")
ValueError: Inputs must be numeric.

Without the non-numeric check, the function would return True, as expected.

The parameter allowed_range: (float, float) has a type-hint of "tuple of two floats", but there is nothing in Python that will enforce that.  You can provide a more than 2 values.  50 is not in the range of 1 to 10, but it is in the range of (1, 10, 100) ... whatever that means!

>>> is_in_range(50, (1, 10, 100))
True

And you are only testing the first two values for numeric-ishness.  0 is not in the range of 1 to 10, but it is in the range of [1, 10, False]!

>>> is_in_range(0, [1, 10, False])
True