If statement, is the shortened version readable enough?

The second part of the condition in the first method (someVar2[i].disabled = (someVar3.find("." + someVar4).length == 0)) is only an assignment and is always evaluated to true.

It is clearer to use only the first part of the condition as a condition in if (someVar1 !== "someString") and move assignment inside the if statement, similarly as you did in the second method.

Regarding the second method, I would avoid using names such as bool as they are keywords. Use another name instead.

Also, in this particular case you are assigning value to variable 'bool' and then use it only once. You could assign the value directly to someVar2[i].disabled.

if (someVar1 !== "someString") {
  someVar2[i].disabled = someVar3.find("." + someVar4).length == 0;
}

You could also use inline if:

someVar2[i].disabled = (someVar1 !== "someString") ? (someVar3.find("." + someVar4).length == 0) : <defaultValue>;


Boolean expression complexity and bitwise operators

If it’s a complex bitwise operation, like:

result = a & b | c | d & x & y

then it would make perfect sense to raise a violation. On the other hand, this looks like an "innocent" bitmask:

mask = a | b | c | d

An automated tool cannot judge if this is dangerous or not, so it's understandable to raise a flag for this. But in this particular case, it's clearly a false positive.

I put // NOSONAR on the offending line of code to make the warning go away, like this:

public static final int DEFAULT_MASK = Mask.BASE  // NOSONAR
    | Mask.SECTOR
    | Mask.GROUP
    | Mask.INDUSTRY
    | Mask.NAME
    | Mask.COUNTRY;


Big Bad Issue:
The callback function for threads libraries are usually a C-function pointer. As such the thread library depends on the callback having a C ABI (not a C++ ABI). This means the function you pass into the threading API must be declared:
extern "C" void* XXXX(void*); // Assuming return and take void* parameters.
                              // Which is basically all you can do with a C API.

Note the extern "C" must be there for it to be a valid C++ program.
You are using a static member function as your callback.
static DWORD WINAPI ThreadProc(LPVOID p)

It may look like it is working but this is just pure coincidence that the ABI for static member function happens to be the same on your platform as the ABI for C functions (there is no requirement in the standard). Nor do any OS that I know give guarantees that they will not change this ABI.
You should declare it like this:
// I also suspect the you are using windows
// They also have some special macro magic you may want to look at to force
// specific calling conventions.:
//
// __cdecl    =>  One of those magic double underscore reserved identifiers.
// http://msdn.microsoft.com/en-us/library/kdzttdcb.aspx
//
extern "C" DWORD WINAPI ThreadProc(LPVOID p)
{
    CThread* pThreadObj = reinterpret_cast<CThread *>(p);
    return pThreadObj->Execute();
}

class CCreateRestorePointThread: public CThread
{
    friend DWORD WINAPI ThreadProc(LPVOID p);
    ...
};


First of all, a minor complaint, but be careful when using 'use strict'; at a file level—when concatenating JavaScript files for minification, this can have adverse affects. Whenever possible, use it at the top of a function instead.

Anyway, on to the actual code. Your arrayAverage function is fine, but it could be improved and made more explicit by using a more functional style. The .reduce function is perfect for this case, turning the function into a simple one-liner:

function arrayAverage(array) {
  return array.reduce(function (a, b) { return a + b; }) / array.length;
}

Your compare function is, frankly, rather odd. I see three main problems with it:

It does not handle arrays that have equal averages very well. Simply preferring the second array is not a good compromise.
Returning strings for the result is a little strange and unnatural. While there are no enums in a language like JavaScript, using string literals is not a good replacement.
The name compare is very generic and doesn't explain what the function does at all.

To fix all these problems, I propose the following function:

function arrayCompare(arrayA, arrayB) {
  var averageA = arrayAverage(arrayA),
      averageB = arrayAverage(arrayB);
  return averageA < averageB ? -1
       : averageA > averageB ?  1
                             :  0;
}

This is clearer, and it handles the equality case more elegantly. If you really hate nested conditional expressions with a passion, you could use a set of if statements instead, but I think this is perfectly readable when properly formatted.

This change eliminates the need for the largestAveragedArray function entirely, simplifying the code somewhat. As a final note, document.write makes me cringe, but I understand that it's useful in code snippets, so I'll let it slide here. Just don't use it in a real project.

(function () {
  'use strict';

  // returns the average of a single array
  function arrayAverage(array) {
    return array.reduce(function (a, b) { return a + b; }) / array.length;
  }

  // compares two arrays;
  // returns -1 if avg(a) < avg(b), 1 if avg(a) > avg(b), or 0 if avg(a) = avg(b)
  function arrayCompare(arrayA, arrayB) {
    var averageA = arrayAverage(arrayA),
        averageB = arrayAverage(arrayB);
    return averageA < averageB ? -1
         : averageA > averageB ?  1
                               :  0;
  }

  var smaller = [100, 80],
      larger = [100, 100];

  document.write(arrayCompare(smaller, larger) + '
' + arrayCompare(larger, smaller) + '
' + arrayCompare(smaller, smaller));
})();


Infinitely iterable list class in Python

This seems kind of complicated compared to something like this:

def cycle(seq):
    "Generator that yields the elements of a non-empty sequence cyclically."
    i = 0
    while True:
        yield seq[i]
        i = (i + 1) % len(seq)

Or, as Joe Wallis points out in comments:

def cycle(seq):
    "Generator that yields the elements of a non-empty sequence cyclically."
    while True:
        yield from seq


Is the "current connected user" an information that should be shared with the domain?

I'd create an UserProfilePageDTO to separate that information:

public class UserProfilePageDTO {

    private UserProfileDTO userProfile;

    private Boolean isCurrentUser;
    private Boolean isfollowedByCurrentUser;
    ...
}

UserNameDoesntExist - it seem unusual a little bit because of the nt. I'd call it UsernameDoesNotExists or UserNotFoundException (same pattern as ClassNotFoundException and FileNotFoundException from JDK).
I'd consider using a guard clause:

public User getUserProfile(String username, Long currentUserId)
        throws UserNotFoundException {
    UserProfileDTO user = dataController.getUserByUsername(username);
    if (user == null) {
        throw new UserNotFoundException(...);
    }
    user.setIsCurrentUser(currentUserId == user.getId());
    user.setIsFollowedByCurrentUser(dataController.isFollowed(user.getId(), currentUserId));
    ...
}


I spend some more time refining the solutions. Also found a relevant question that asks to find the min/max of the array here.
Problem Context
Searching a value in an array can be up to O(n) in time complexity - you have to iterate through the array and check for each element if it's equal the search value. But - if the array is sorted, this is reduced to O(log(n)) due to a strategy called Binary Search. Binary search allows us at each time cut half of the options to consider. You check the middle element in the array, if the search value is bigger you can discard the lower half, if it's lower you can discard the upper half, and now you do the same for the remaining array - until you either find the value or end up with an empty/1-element array - in that case the element is not in the array.
Here there is a problem that the array is swapped - the question is can we still reduce the time complexity to O(log(n)) ?
The key insight here is that even though the array itself is not perfectly sorted, at least half of it IS - and so we can always tell something about that half, and reduce our scope. This is true for every sub-division we make of the array - at least half of it will be sorted (and in some cases, both halves).
If we are looking for the min/max value, we basically don't care about the part that is sorted, because the pivot value will be in the other half (though the mid value should be included, as it can be the min/max value) - so we can discard the sorted part.
If we are looking for a specific value - we can automatically check if our value is in the range of the sorted half, if it is we discard the non-sorted half, and focus on the sorted. If it's not we focus on the non-sorted - and do the same.
Find Min value
Here is a solution in python - here we check if the right half is sorted. If it is, we reduce our scope to the left half. If not, we reduce our scope to the right half (note that in that case we can safely discard the mid point and move beyond it).
def findMin(arr):
    start = 0
    end = len(arr) - 1
    while(start < end):
        mid = (start + end) // 2
        rightSorted = arr[mid] < arr[end]
        if rightSorted:
            end = mid
        else:
            start = mid + 1
    return arr[start]

The decision to check the right is not arbitrary - it is necessary in case we search for a min value. If we instead search the left, and find out it is sorted - we could not confidently discard that half, as the array might be perfectly sorted - in that case the 0th element is the minimum. So we choose the right in order to be completely sure we still have the min value in the sub array.
Find Max value
In python this is actually very easy - you just need to go one element before the minimum - and even if the min is in 0 position, python interprets -1 as the last element of the array. So you could just use the same code as above, but with return arr[start-1].
Alternatively, we could reverse the min function above:
def findMax(arr):
    start = 0
    end = len(arr) - 1
    while(start < end):
        mid = (start + end) // 2
        leftSorted = arr[mid] > arr[start]
        if leftSorted:
            start = mid
        else:
            end = mid - 1
    return arr[start]

Finding a specific value
If we want to check if a specific value exists in the array - the same key insight hold.
def findVal(arr, val):
    start = 0
    end = len(arr) - 1
    while(start < end):
        mid = (start + end) // 2
        leftSorted = arr[start] <= arr[mid]
        if leftSorted:
            if val >= arr[start] and val <= arr[mid]:
                end = mid
            else:
                start = mid + 1
        else:
            if val >= arr[mid] and val <= arr[end]:
                start = mid
            else:
                end = mid - 1
    return val == arr[start]

A few differences:

we have to check if our value is in the sorted half, and if not discard it.

we have to watch out for the case of 2 elements in an ordered array. The issue here is that if we are not careful, we can end up in an endless loop - because the mid point will be either the 1st or the 2nd, depending if we are using a floor or a ceil operation. Since the default python // operation is a floor, mid will be equal to start, and we have to check the left side in order to either choose the 1st or discard it. [if we use ceil, we should check the right side]


In general, using the "new" keyword in any class is bad practice, because you're creating an implicit dependency. Instead, you should follow the "ask, don't look" design philosophy and require that the database object be passed to the class, rather than letting the class fetch it. Dependency injection is a common solve to this problem, and I'd recommend looking at how PIMPLE is used. Here's a good article: "Dependency Injection with Pimple".

Many people, like deceze, will deride you (rightfully so) for doing things like this, because it's one of the easiest (and probably most common) things you can do to kill the possibility of testing your code. If you were to write a unit test for this model, you'd have a database object being constructed with each test. Since the whole point of unit tests is to run code in isolation (to verify the tested code's accuracy), it would be impossible to test this model without a database.

On that note, the JavaScript guru, Misko Hevery, published a really superb article on writing testable code: "Top 10 things which make your code hard to test". While this is specifically in the context of code testing, it's also very good general programming information.


I'd suggest that you "translate" the comparisons into meaningful names:

if self.BlockedInFront():
    left = -self.MAX_SPEED/2

if self.BlockedRight():
    right = -self.MAX_SPEED/2


Function for getting strings consisting of random characters

My immediate thought is that the function is just doing too many things.

It'd be simpler to just return a mixed-case string of a specific length. Done.

Want that string to be all-uppercase? Just call getRandomString(n).toUpperCase().
All-lowercase. Call getRandomString(n).toUpperCase().

Want it to have a separator between each letter? Call getRandomString(n).split('').join(separator).

Want it be be somewhere between x and y characters long? Pick a random length yourself, and pass that to the function.

This just seems like a function built for a very narrow purpose. For instance, what if (for whatever reason) you only want a separator every 4 characters? Do you add yet another argument to the function, or do you write a separate function to chopping and glueing the way you want it?

Even if you need a single function to do everything, it'd be simpler to have it just call out to other functions that comprise the building blocks. Lots of the functions you need already exist (toUpperCase, toLowerCase, split, and join), so it's only the randomness you need to add.

A simple and crude structure might be:

function getRandomInt(min, max) {
  var span = parseInt(max, 10) - parseInt(min, 10);
  if(span <= 0) {
    throw { message: 'Min must be less than max.' };
  }
  return min + Math.round(Math.random() * span);
}

function getRandomLetter() {
  var asc = getRandomInt(65, 116);
  if(asc > 90) asc += 6;
  return String.fromCharCode(asc);
}

function getRandomString(length) {
  var i, letters = [];
  length = parseInt(length, 10);

  for(i = 0 ; i < length ; i++) {
    letters.push(getRandomLetter());
  }
  return letters.join('');
}

// this is the equivalent of original function
function getCustomRandomString(separator, min, max, style) {
  var string = getRandomString(getRandomInt(min, max));

  if(style === 'upper') {
    string = string.toUpperCase();
  } else if(style != 'both') {
    string = string.toLowerCase();
  }

  if(separator) {
    string = string.split('').join(separator);
  }

  return string;
}


Call a text-editor from within a Python script to get user input

click is a great library for command line processing and it has some utilities, click.edit() is portable and uses the EDITOR environment variable.  I typed the line, stuff, into the editor.  Notice it is returned as a string. Nice.

So, rather then write any code, you could consider replacing what your working on with these two lines:

(venv) /tmp/editor $ export EDITOR='=mvim -f'
(venv) /tmp/editor $ python
>>> import click
>>> click.edit()
'stuff\n'

Check out the docs https://click.palletsprojects.com/en/7.x/utils/#launching-editors  My entire experience:

/tmp $ mkdir editor
/tmp $ cd editor
/tmp/editor $ python3 -m venv venv
/tmp/editor $ source venv/bin/activate
(venv) /tmp/editor $ pip install click
Collecting click
  Using cached https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl
Installing collected packages: click
Successfully installed click-7.0
You are using pip version 19.0.3, however version 19.3.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
(venv) /tmp/editor $ export EDITOR='=mvim -f'
(venv) /tmp/editor $ python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import click
>>> click.edit()
'stuff\n'
>>>

I would check out the source code for click.edit() if you want to write your own.


Handling singularities in squircle parametric equations

Here's a different solution.  The singularities occur when sin(_t) or cos(_t) is zero.  So check for those conditions.

def FG_param(r, s, t):
    x = np.ones_like(t)
    y = np.ones_like(t)

    for i, _t in enumerate(t):
        sin_t = sin(_t)
        cos_t = cos(_t)

        if np.isclose(sin_t, 0.0):
            x[i] = -r if np.isclose(_t, pi) else r
            y[i] = 0.0

        elif np.isclose(cos_t, 0.0):
            x[i] = 0.0
            y[i] = r if _t < pi else -r

        else:
            radical = sqrt(1 - sqrt(1 - s**2 * sin(2*_t)**2))

            x[i] = r*sign(cos_t) / (s*sqrt(2)*np.abs(sin_t)) * radical
            y[i] = r*sign(sin_t) / (s*sqrt(2)*np.abs(cos_t)) * radical

    return x, y


Mail merge (Parsec string formatting) example

Instead of notFollowedBy, you can use noneOf in chunk:

chunk :: Parser (Merge String)
chunk = Chunk <$> many1 (noneOf "<") <|> try (sequence [char '<', noneOf "<"])

That prevents a lookahead but it is no longer that nice to look at.

format can be rewritten without explicit recursion if we use concatMap:

format :: HM.HashMap String String -> [Merge String] -> String
format hmap xs = concatMap go xs
  where
    go (Chunk c) = c
    go (Key   k) = maybe (error $ "missing key: " ++ k) id (HM.lookup k hmap)

However, this would make our function partial, which we try to prevent. So let's use Either instead:

format :: HM.HashMap String String -> [Merge String] -> Either String String
format hmap xs = concat <$> mapM go xs
  where
    go (Chunk c) = Right c
    go (Key   k) = maybe (Left $ "missing key: " ++ k) Right (HM.lookup k hmap)


Security

The echo should be vulnerable to XSS via the file extension (but it's not exploitable - at least not easily; Still, I would HTML encode it when echoing).

Otherwise it looks good to me. Regarding the various checks:

checkMime: Can easily be bypassed. Checking the mimetype is generally not very secure, so it doesn't matter that much, but as defense in depth it's not a bad idea. getimagesize isn't a good function for this though, finfo_file generally gives better results. [see eg here]
checkExtension: This is the important check. There are no known vulnerabilities for pathinfo, so this should be secure.
checkByExif: Can very easily be bypassed, as exif_imagetype only checks the first bytes. It's not a security check in any way, but may help with usability (although in this case I don't see the use for it).
checkSize: important check, should be secure.
checkImageName: Not needed as you change the image name anyways. The function itself looks pretty bad though; strpbrk($imagename, "\\/?%*' :|\"<>") === FALSE&&$imagename isn't very readable.

To add additional security as defense in depth, you could move the upload dir outside the web root and check the content of the file (eg that it doesn't contain opening PHP tags).

Returning Early

Your ifs are quite nested. If you return early, you can avoid this, and make it more obvious what condition returns what error. Eg:

if(empty($_FILES['fileToUpload']['name'][0])) {
    return "No Image Is selected";
}
if(too many images){
    return "Only 30 Images are allowed";
}
foreach($_FILES["fileToUpload"]['tmp_name'] as $key=>$imgLocation){
    uploadImage($_FILES["fileToUpload"]['tmp_name'][$key], $imgLocation);
}

checkImageName

Instead of this:

function checkImageName($imagename){
    $imagename = pathinfo($imagename, PATHINFO_FILENAME);
    if(strpbrk($imagename, "\\/?%*' :|\"<>") === FALSE&&$imagename){
        if (strlen($imagename) >= 1 && strlen($imagename)<= 30){
            return true;
        }else{
            return false;
        //HandleError('Invalid file name');
        }
    }else{
        return false;
    }
}

You can use this:

function checkImageName($imagename){
    if (preg_match("/[\\\\\/?%*' :|\"<>]/", $imagename)) {
       return false;
    }
    return strlen($imagename) >= 1 && strlen($imagename) <= 30;
}

preg_match is a more fitting function, as you want to see if the string matches certain characters, and this also gets rid of the nested if structure.

Personally, I would prefer a whitelist check on a-zA-Z0-9 here.

Misc

why do you have an empty foreach loop? Seems unnecessary.
I would add a function for the upload of a single image.
Your formatting could use some work. Always use curly brackets, always put statements on their own line, be more consistent with your spacing, etc. Any IDE can fix these issues for you.
be more consistent with your variable names. Eg imagename vs imageName vs image_tmpName, imageName vs imgLocation, etc.


Getting CSS files based on production or development

One quick one.

if(!defined("ENVIRONMENT") or ENVIRONMENT == 'development')

If ENVIRONMENT has only two defined values e.g. 'development' and 'production' then use:

if(ENVIRONMENT != 'production')

For the Group loop:

foreach(array_keys($groups) as $css_group_file)

array_keys is not needed:

 foreach($groups as $css_group_file => $val)

As far as optimization of two loops to one, it does not matter as these two loops would execute in less than a millisecond, I would guess about about 400 microseconds.

I would rather see ENVIRONMENT equal to 0 instead of 'development'
and 1 instead of 'production'

This is so if it is undefined it will equate to zero with intval().

if (intval(ENVIRONMENT)){}

The following is rather unconventional but it is simple and fast.

Run this only when CSS files needs editing:

$css_files = array(
    array('path' =>'css/jquery.gritter.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/jquery-ui.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/bootstrap-select.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/select2.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/font-awesome.min.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/jquery.loadmask.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/token-input-facebook.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/KeyTips.min.css', 'media' => 'all', 'group' => '1.css'),
    array('path' =>'css/bootstrap-colorpicker.min.css', 'media' => 'all', 'group' => '2.css'),
    array('path' =>'css/jquery.ml-keyboard.css', 'media' => 'all', 'group' => '2.css')
);
if(!defined("ENVIRONMENT") or ENVIRONMENT == 'development'){
   $fp = '/home/user/css/p0.ser','w');
   fwrite($fp,serialize($css_files));
   fclose($fp);
   $css_files[] = array('path' =>'css/rtl.css', 'media' => 'all');
   $fp = '/home/user/css/p1.ser','w');
   fwrite($fp,serialize($css_files));
   fclose($fp);
   $groups = array();
   foreach($css_files as $css){
     $groups[$css['group']] = TRUE;
   }
   foreach(array_keys($groups) as $css_group_file){
        $return[] = array('path' =>"css/$css_group_file", 'media' => 'all');
   }
   $fp = '/home/user/css/d0.ser','w');
   fwrite($fp,serialize($return));
   fclose($fp);
   $return[] = array('path' =>'css/rtl.css', 'media' => 'all');
   $fp = '/home/user/css/d1.ser','w');
   fwrite($fp,serialize($return));
   fclose($fp);

New Production Function:

This is based on is_rtl_lang() returning a value of zero or one and

$CI =& get_instance();
$css_file = array();
$css_file ['production'][0]) = '/home/user/css/p0.ser';
$css_file ['production'][1]) = '/home/user/css/p1.ser';
$css_file ['development'][0]) = '/home/user/css/d0.ser';
$css_file ['development'][1]) ='/home/user/css/d1.ser' ;
return unserialize(file_get_contents($css_files[ENVIRONMENT][is_rtl_lang()]);

If these more efficient changes were made:

From: ENVIRONMENT = 'production';
To:   ENVIRONMENT = 1 ;

From: ENVIRONMENT = 'development';
To:   ENVIRONMENT = 0 ;

Then:

$css_file [1][0]) = '/home/user/css/p0.ser';  // production without RTL
$css_file [1][1]) = '/home/user/css/p1.ser';  // production with RTL
$css_file [0][0]) = '/home/user/css/d0.ser';  // development without RTL
$css_file [0][1]) ='/home/user/css/d1.ser' ;  // development with RTL

unserialize(file_get_contents($css_files[intval(ENVIRONMENT)][is_rtl_lang()]);

NOTE:  intval() was added to $css_files[ENVIRONMENT]   to become: $css_files[intval(ENVIRONMENT)]

Where intval(ENVIRONMENT) takes care of the undefined condition.

Better Yet:

Seeing you are using PHP to populate the CSS links, there is an even better method.

Because each CSS file requires a round trip HTTP Request/Response, why not reduce it to one.
This is especially beneficial on a mobile phone Browser.  To conserve battery a smartphone will drop the radio signal between requests.  It can take seconds for the phone to reestablish the radio connection.
This is why it is important that each file loaded by the Browser contain Connection: keep-alive in the Request Header.

Furthermore because the Browser will not begin rendering until all the CSS is loaded, it is advantageous to bring it in with a single HTTP Request.

$css = file_get_contents('/home/user/public_html/css/css/jquery.gritter.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/jquery-ui.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/bootstrap-select.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/select2.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/font-awesome.min.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/jquery.loadmask.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/token-input-facebook.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/KeyTips.min.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/bootstrap-colorpicker.min.css') . "\n";
$css .= file_get_contents('/home/user/public_html/css/css/jquery.ml-keyboard.css') . "\n";
$fp = '/home/user/public_html/css/styles.css';
fwrite($fp,$css);
fclose($fp);


I'd re-structure (the Win32 part of) the open function to something like this:

#ifdef WIN32

    wchar_t unicodeMode[MAX_PATH];
    wchar_t unicodeName[MAX_PATH];

    if (MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, MAX_PATH) &&
        MultiByteToWideChar( CP_UTF8, 0, mode, -1, unicodeMode, MAX_PATH) &&
        (handle = _wfopen( unicodeName, unicodeMode)) != NULL)
    {
        *file = handle;
        return true;
    }
    return false;

#else

You don't need to call MultiByteToWideChar twice for each conversion -- the first call not only returns the length, but does the conversion as well. As it stands, your code has potential buffer overruns as well -- it used the first call to MultiByteToWideChar to measure the length that would be needed for the result, but never checked that this was less than or equal to the buffer space you provided.

It can be legitimate to do the two consecutive calls, especially if (for example) you want to ensure you can handle any possible input by using the first call the measure the necessary length, then allocating the necessary space dynamically, and then doing the second call using the dynamically allocated space.

Several places, you have things like:

return ( fclose( file ) == 0 ) ? true : false;

These should be written as:

return fclose(file) == 0;

or just:

return !fclose(file);

There's no need to select and return a Boolean literal -- the Boolean values yielded by == and ! will work nicely as-is.

Edit: You also have a couple of things like:

#ifdef WIN32
    *curPos = _ftelli64( file );
#else
    *curPos =  ftello64( file );
#endif

spread throughout the code. Where you're just dealing with different function names like this, I think I'd have one block up-front to deal with the name differences, and then use a single name through the rest of the code:

#ifdef WIN32
    #define ftello64(x) _ftelli64(x)
    #define fseeko64(x) _fseeki64(x)
#endif

/* ... */

Bool_T OsFile_Seek( IN FILE * file, IN Int64_T offset, IN int origin )
{
    return !fseeko64(file, offset, origin);
}

You might want to read #ifdef considered harmful for more about what to do and what to avoid.


Plot random generated 'n' non-colliding circles using Matplotlib

I would pull out the generation of the next circle and the generation of all circles into their own functions. This allows you to test those parts without having to plot the result, allowing some speed comparisons:

def place_circle(centers, rads, size_x, size_y, size_r):
    center = random.uniform(*size_x), random.uniform(*size_y)
    rad = random.uniform(*size_r)
    if centers and rads:
        while collide(center, rad, centers, rads):
            center = random.uniform(*size_x), random.uniform(*size_y)
            rad = random.uniform(*size_r)
    return center, rad

def place_circles(ncirle, size_x, size_y, size_r):
    centers, rads = [], []
    for n in range(ncircle):
        center, rad = place_circle(centers, rads, size_x, size_y, size_r)
        centers.append(center)
        rads.append(rad)
        # print(n)
    return centers, rads

You can then use this like this in your main function:

centers, rads = place_circles(ncircle, sizex, sizey, (min_r, max_r))
for center, rad in zip(centers, rads):
    add_circle(ax, center=center, r=rad, face_color=color, edge_color=BLACK)

Note that I made (0, 0, 0, 0) global constant called BLACK and removed the whitespace around = for keywords (as recommended by Python's official style-guide, PEP8).

Now, we can test how long it takes to find a place for 1000 circles:

%timeit place_circles(1000, (0, 1000), (0, 1000), (1, 200))
3.33 s ± 139 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

With this baseline, you can try to improve the performance.


Readability counts
You follow PEP8 naming conventions but fail to follow layout ones. The result is a big block of code that get harder to read than necessary. Use spaces and blank lines to give the reader some rest.
You should also get yourself familiar with the if __name__ == '__main__' idiom and remove some unnecessary stuff:

return at the end of a function has no added value;
same for sys.exit(0) at the end of a program.

Break functionnality into tinier function
As it stand, your main function does 3 things:

Compute the required value;
Parse the input for information about computing such value;
Parse the input to repeat such computation for a number of trips.

You should use 3 functions instead, each responsible of its own task. Or at least split the "parse input for a trip and compute the value for this trip" part into its own function.
Define variables when you need them
Python is a dynamic language, you don't need to define variables before using them, nor preallocate memory for them. Just declare a new variable when you need it.
You should also aim at removing the number of intermediate variables that you use only once.
Use builtins
input, max, sum and list-comprehensions can help you express your thoughts in a more straighforward way.
str.format can help you with rounding and formatting output.
Proposed improvements
import math
from decimal import Decimal

def compute_expenses_for_a_trip(students_count):
    students_spending = [float(input()) for _ in range(students_count)]
    average_spending = sum(students_spending) / students_count

    # these following two variables account for the fact that we can never get to the exact average.
    lower_average_spending = math.floor(average_spending * 100) / 100
    upper_average_spending = math.ceil(average_spending * 100) / 100

    pos_difference = sum(element - upper_average_spending for element in students_spending if element > average_spending)
    neg_difference = sum(lower_average_spending - element for element in students_spending if element < average_spending)
    return Decimal(max(pos_difference, neg_difference))

def trip_programming_challenge():
    while True:
        num_students = int(input())  # read number of students
        if not num_students:
            break
        amount_exchanged = compute_expenses_for_a_trip(num_students)
        print('${:.2f}'.format(amount_exchanged))

if __name__ == '__main__':
    trip_programming_challenge()

I didn't enforce a line length of 80 characters but you might want to.
I'm also unsure why you introduced Decimal that late into the computation. Either you use them all along or you remove them, but introducing them halfway through kind of defeat their purpose.
Also note that the two summed differences are mainly proposed as an alternative syntax but since they iterate two times over the same list you may find your for loop faster. If it matters, profile and choose the best.


In this code, you set sDone = true in both branches of the if-else:

if (next.size()) {
    next.addClass("secondary");
    sDone = true;
} else {
    images.filter(":first").addClass("secondary");
    sDone = true;
}

So you could move that line outside of the if-else:

if (next.size()) {
    next.addClass("secondary");
} else {
    images.filter(":first").addClass("secondary");
}
sDone = true;

At the top you declared the current variable,
but then you don't use it. If you don't need it, then remove it.


Applying Function to `Seq[B]` in `Seq[Either[A, B]]`

The problem with @hayden.sikh's answer (the one that preserves order) is that it has a suboptimal complexity, and is especially inefficient if the Seq is a List (which it is in your REPL session). Appending an element to a list with :+ has linear complexity. Calling contains on a sequence too. So this is O(n^2).

It would be easy to adapt the answer by using a Set in the foldLeft accumulator, appending with +: and reversing the list at the end.
Or, to avoid the complexity and the cost of maintaining an immutable Set, simply use a mutable one and a flatMap:

val seen = mutable.HashSet[Int]()
xs flatMap { case Right(x) => if (seen(x)) None else { seen += x; Some(Right(x)) }
             case x => Some(x) }

Mutability is fine as long as it's kept local, for example as a detail in an algorithm's implementation (most of the algorithms of the Scala standard library use mutability too, including distinct!).


JavaScript: Repeat a function X times at I intervals

I don't see anything problematic with your code, but just for fun, here are some alternative approaches to various parts of the code. It's 100% DRY, and functionally identical to the original.

function repeatXI(callback, interval, repeats, immediate) {
  var timer, trigger;
  trigger = function () {
    callback();
    --repeats || clearInterval(timer);
  };

  interval = interval <= 0 ? 1000 : interval; // default: 1000ms
  repeats  = parseInt(repeats, 10) || 0;      // default: repeat forever
  timer    = setInterval(trigger, interval);

  if( !!immediate ) { // Coerce boolean
    trigger();
  }
}

And here's a jsfiddle demo

If you want, you can return timer from the function (as I do in the demo), so you can clear it (i.e. cancel the repeater) elsewhere in your code.

Regardless of the implementation-specifics it's worth noting that timers are unreliable at the best of times (since JS is single-threaded). Depending on your needs it may not be a good idea to set n timeouts at n * interval as you do for finite repeats. If a few of the timeouts get blocked long enough, they'll all queue up, and fire at once, once the thread clears. With setInterval though, you're guaranteed that there'll be at least interval time between the callbacks.

So it depends on your needs how you want to implement it.


Concept

Internet "speed" actually consists of multiple factors, including bandwidth, latency, and packet loss.  What exactly are you trying to measure?  If it's bandwidth (data transfer speed in bits per second), then you should also measure transfers of larger payloads, because the time to complete small transfers will tend to be dominated by latency effects.  If it's latency (milliseconds for a round trip) that you are want to measure, then a tiny packet (typically an ICMP echo request, commonly called a "ping") would be more appropriate.

In addition, there are confounding issues:

Upload vs. download speed: Residential Internet connections tend to significantly favour downloads, since that's what most consumers care about.
Traffic shaping: Some ISPs will throttle the bandwidth to penalize very large transfers, so that smaller responses feel more responsive.
Server performance: It does take a few milliseconds for Google's server to formulate the response payload; that delay would be a more significant fraction of the measured round-trip time for a short response than for a long response.
HTTP and HTTPS overhead: You're considering only the size of the HTTP response payload.  Since you're using HTTPS, there are also multiple TCP round trips needed to perform the TLS handshake, and a few kilobytes to transfer the certificates.  The HTTP headers could add another kilobyte or so.  All of this is significant when the payload is only ~10 kB short.
DNS overhead: Resolving the google.com hostname to an IP address might involve a DNS lookup, which would add a few milliseconds.  The time for that DNS lookup is accounted for in your benchmark, but not the traffic.
Proximity: The "Internet" is not one entity.  Connectivity to various parts of the Internet will have different performance characteristics.

Time calculation bug

When you do str(datetime.datetime.now()), you are converting the timestamp from a datetime object that is suitable for arithmetic into a string, which is a horrible format for calculations.  You then try to salvage the information by dropping the first 17 characters of the string and converting the seconds portion back into a float.

What happens if the start and end times straddle a minute boundary?  You'll get an elapsed time of approximately -60 seconds!

A better way would be:

start = datetime.datetime.now()
…     # Do some work here…
end = datetime.datetime.now()
diff = (end - start).total_seconds()

Inefficiencies

The code expects a path as sys.argv[0].  What is it for?  It seems to be used only to derive a directory to use for a temporary file, and the temporary file is used just to determine the length of the response payload.

All you had to do to obtain the length was len(urllib2.urlopen('https://google.com')).  No filesystem access is needed!

Lint

By PEP 8, getInternetSpeed() should be get_internet_speed().  The function should probably accept a parameter for the URL to test.  Furthermore, if the function is named "getSomething", I would expect it to return a value rather than print its result.
For filename manipulation, use the os.path module.
Avoid redefining variables, especially in a way that changes their type:

x = urllib2.urlopen('https://google.com')
…
x = x.read()

x is a very poor variable name, by the way.  I suggest req.
open() should almost always be used in the context of a with block, so that the closure will be handled correctly for you:

 with open(os.path.join(temp_dir, 'TEMP.txt'), 'w') as f:
     f.write(x)

To generate temporary files, use the tempfile library to guarantee that you will not overwrite an existing file.


That does look a little confusing.  The example you looked at is for C, not Java.  I would do this:

int random = (int) Math.floor(Math.random() * (max - min + 1) ) + min;

It works like this:  Math.random() returns a double between 0 and 1 (although never actually equal to 1).  The full range of values you want is (max - min + 1) (the +1 is because you probably want max to min inclusive), so this will scale the number over the correct number of integer values.  We floor it (round down) because we want an int, and finally shift it upwards by adding min to put the numbers in the correct range.  We also cast to an int since we don't want it as a double.

EDIT: On further inspection, this is better; no casting and rounding of doubles:

Random rand = new Random();
int random = rand.nextInt(max - min + 1) + min;


Imrpove the following code without if/else

I would separate them out into functions to make the code more readable. So the first if/else would become:

if (decode)
  doDecode()
else
  doEncodeSingle();

I would also break the doDocdeSingle up:

Quagga.decodeSingle({...},
  handleDecodeResult );

The last if/else is currently structured as:

if (result) {
  if (result.codeResult) {
    // Handle Code
  } else {
    // Handle no-code
  }
} else {
  // No result
}

I often find it cleaner to reverse the condition and structure it as:

if (!result) {
  // No result
} else if (result.codeResult) {
  // Handle Code
} else {
  // Handle no-code
}

Which removes a level of nesting. Again I would try and make each if section a single function call.


I like the consistency of your braces and indentation - well done!

The name Stack_Array should be StackArray, since as member names are camelCase, type names ought to be PascalCase, not Upper_Snake_Case.

You'll want to implement a constructor so that the capacity of the object can be parameterized, and then the calling code can look like this:

StackArray foo = new StackArray(42);
foo.push(bar);

The underlying capacity static field would need to be changed a bit though; you'll want it to be an instance field, so that each object can have its own independent value. I'd keep it final though, because it's not a value you want to be able to modify during the lifetime of an instance - beyond the constructor, nothing should be allowed to modify that value.

You'll want to throw an appropriate exception in exceptional situations:

if(top >= capacity) {
    System.out.println("StackOverflow !!");

A Stack is a data structure; other code will rely on its correct behavior, and expect a number of errors to occur in certain specific situations - for example when the caller attempts to push an element into an instance that already contains as many items as it can hold.

That said, I'd prefer a Stack implementation that simply increases its capacity as items are pushed. In any case, printing "StackOverflow !!" isn't appropriate. Making the method return a bool that the calling code can evaluate to determine whether the push/pull succeeded or not, would be a better alternative if you really want a fixed capacity.

Printing to the console isn't the job of a data structure, printStack should be replaced by a method that returns a new data structure that contains a copy of the internal array. Such a toArray method would leave it up to the calling code to decide whether they want to print the items to the console, or dump them into a log file, or whatever.

Your implementation is pretty bare-bones, you'll want to look at the java.util.Stack<E> members and possibly dig into generics. The C# System.Collections.Generics.Stack<T> class could also be an inspiration.

The pop method would be expected to return the popped item. A peek method is missing, to "peek" at the next item without popping it out of the stack.

Other observations

Between push and pop, the two have an if conditional, but one is no-op in the positive branch, while the other is no-op in the negative branch (/else block). It would be better to decide whether you test for the error condition [to throw an error and fail early] or if you test for the success condition [and throw an error in the else block] - it's usually better to fail early and reduce the indentation level:

public void foo() {
    if ({error condition}) {
        throw new SomeException();
    }
    doSomething();
}

Watch the spacing on either side of comparison operators:

for(int i = top; i >=0; i--) {

Give it the same whitespace as for the = assignment operator:

for(int i = top; i >= 0; i--) {


PHP code for blacklisting and rewriting/redirecting URLs

I think it looks good, a little verbose. Could be simplified to this

$oldurl = JUri::getInstance();
$bad_urls = ['match1','match2','match3'];
$newurl = str_replace($bad_urls, 'rewritewiththis', $oldurl);

if(in_array($oldurl, $bad_urls))
    exit(header("Location: $newurl", true, 301));

If you need to use something like this in many locations, or you need to elaborate on what are considered bad urls a router system/class may be a better way to go.

If you're asking if there's a different way to re-route without using header() I don't think there is. Any router system I have seen uses header() to re-route, no matter how much code surrounds and abstracts them.


I doubt that this code actually works. Especially pullwhitespace doesn't do what you probably intended (hint: it doesn't modify the argument, it makes a copy of the pointer and advances it). Have you tested it before submitting it for review here?

Anyway: You might want to have a look here for alternative ways to implement a state machine. You approach is similar to Remo.D's answer in the linked question but I think his macros make it more readable.

A few things I noticed:

When you are in NORMAL and read a white space you do this *outptr++ = '\0'; Given that strings in C are NULL terminated character sequences this seems dodgy as it will terminate the output right there unless you tell someone to read further by supplying a length. If you intend to split on white space then you should store the results in a char ** like argv.
Again in NORMAL:

case '\\':
        if (((a = *input++)) == '\n') {
                break;
        } else if (a) {
                *outptr++ = a;
                goto NORMAL;
        } else {
                goto FAIL;
        }

So if you find a \ followed by a newline you break the switch which is followed by an assert(0). Normally assert should be used to state invariants as "this function expects this condition to be true and it is probably a bug in the program if it is not". Specifically assert(0) should be used as "should never execute this code path". It seems weird that external user input can trigger an assert just because the program doesn't like he input. Especially since you have a FAIL state anyway.

Also the else condition evaluation depends on the side effect of the if condition evaluation - not very nice. You should read the next character first in a separate line and then evaluate. This makes it much clearer. So this case could probably have been written as:

case '\\':
        a = *input++;
        if (a && a != '\n') {
               *outptr++ = a;
               goto NORMAL;
        }
        goto FAIL;

If you are in DQUOTE and encounter a \ then you read another character from the input. However that character simply gets swallowed because in the default case you do this: *outptr++ = a; which will write the \ to the output and skip the current character (held in b).


Min / Max function of 1D array in C / C++

It's not quite the best.  There's some things IMHO that is hindering its performance and usefulness.

There's no point in declaring val as a static variable.  In fact, you've killed any chance of it being usable in multi-threaded programs.

The body of the loop is performing an assignment in every single iteration when it doesn't need to.  If you want it to be its best, you should only be doing so when it is required.

Your overall structure is fine, assuming we can expect well-formed inputs where array is nonempty and size is positive, I'd just change it so it's more like this:

double min(const double *arr, size_t length) {
    // returns the minimum value of array
    size_t i;
    double minimum = arr[0];
    for (i = 1; i < length; ++i) {
        if (minimum > arr[i]) {
            minimum = arr[i];
        }
    }
    return minimum;
}


Relational schema and query for multiplayer tabletop game

Good work on schema

Overall, I think your schema is clean, easy to follow, and makes sense (in the limited scope of your scenario). Granted the overarching or "whole" schema for something like this would be much larger, but if you kept following this sort of normalization it should be fine.

Aliases

I see at least 5 unclear aliases: p, t, m, pt, pm. Mr. Maintainer would have to read through your entire script to even grasp what these stand for. Your column names are short enough, I really don't think aliases are of much use, and they just make your script more confusing to review. Imagine this kind of notation used on 1000 lines of codes in a real business setting, this should drive my point home.

Common Table Expressions

You have a rather large subquery (which I will address next point) and in SQL Server and several other RDBMS, you can simplify the way it reads by using a CTE. So this:

from (
    select m.Id as MatchId,
        m.CompletionDate,
        t.Id as TeamId,
        t.IsWinningTeam as Won
    from Players p
    inner join PlayerTeams pt
        on p.Id = pt.PlayerId
    inner join Teams t
        on pt.TeamID = t.Id
    inner join Matches m
        on t.MatchId = m.Id
    where m.IsComplete = 1 and p.Id = 1
) pm

You could instead write, at the very beginning of your script:

with pm as (
        select m.Id as MatchId,
            m.CompletionDate,
            t.Id as TeamId,
            t.IsWinningTeam as Won
        from Players p
        inner join PlayerTeams pt
            on p.Id = pt.PlayerId
        inner join Teams t
            on pt.TeamID = t.Id
        inner join Matches m
            on t.MatchId = m.Id
        where m.IsComplete = 1 and p.Id = 1
    )
select /* bunch of work here */
from pm    -- reference CTE in main query as if it were a table

Redundancy

I noticed your subquery (or CTE) is joining some of the same stuff your main query is doing. Look:

from (
    select m.Id as MatchId,
        m.CompletionDate,
        t.Id as TeamId,
        t.IsWinningTeam as Won
    from Players p
    inner join PlayerTeams pt
        on p.Id = pt.PlayerId  -- (1)
    inner join Teams t
        on pt.TeamID = t.Id  -- (2)
    inner join Matches m
        on t.MatchId = m.Id
    where m.IsComplete = 1 and p.Id = 1
) pm
inner join Teams t
    on pm.MatchId = t.MatchId
inner join PlayerTeams pt
    on t.Id = pt.TeamId  -- (2)
inner join Players p
    on pt.PlayerId = p.Id  -- (1)

Best to avoid redundant operations, especially expensive join's, as it makes the execution slower. Only one of each should be needed in most cases.

Nitpick

This preferably should not be used: where p.Id != 1

Instead, use this: where p.Id <> 1

Although both work just the same, != is not ANSI-92 standard.


User model with user roles in Codeigniter PHP/MySQL

I think the schema is fine with one possible exception. I don't see any value in the status column in the user_user_role table. The same effect is achieved by removing the row connecting the user and a given role. If the connections isn't there then that role is 'disabled' for that user.

Unless you intend to add functionality that adds, removes or otherwise manages roles then one model is all you need.

Roles as a param to insert makes sense but perhaps a default value (beyond an empty array) should be provided. Otherwise, you could end up with users that don't have permission to do anything. Or, keep the definition $roles = [] and then if(empty($roles)), throw an exception.

I think you have a problem in the line

if ( $user_id = $this->db->insert( $this->table_name, $user_data ) ) {

$this->db->insert() returns either true or false. To get the id for the newly inserted records you will need to use $this->db->insert_id(); perhaps like this.

if ($this->db->insert( $this->table_name, $user_data ) ) {
    $user_id = $this->db->insert_id();
    ...

Also, in the interest of elegant code instead of

return $user_id;
} else {
    return FALSE;
}

use

} //end of if ($this->db->insert(...

return isset($user_id) ? $user_id : FALSE;


This is clearly Python2. To have better inheritance in Python2 you have to inherit from object.
Inheriting from object is classed as a new-style class, and is better than old ones.

class Parent(object):
    pass

class Child1(Parent): # No need to inherit object again.
    pass

You don't use __init__...
In your example code it may be bad to use it, since you are adding spells anyway.
And you're overwriting self.name in your class anyway, so it's quite pointless.

But lets say you wanted to have a default name for Child1,
and you could assign it to something else,
so you don't have to supply the name on every function.
You can do almost exactly the same as you are doing on every function.

def Parent(object):
    def __init__(self, name="Player", lives=3):
        self.name = name
        self.lives = lives

    def run(self):
        print "%s is running." % self.name

As for your print statements you should use str.format rather than the old 'sprintf'-like %.
There are quirks with % and str.format is a lot stronger.

print "{} is running.".format(self.name)

The above is exactly the same as your above prints, but I'm sure at one point you will want to print the name and the lives.
You can change the contents of the {}'s to allow you to use the name instead.
Which allows for greater readability, as now we know '[player name] is running'.

print "{0.name} is running.".format(self)

Why stop there you can show lives to!

print "{0.name} has {0.lives} live(s).".format(self)

As just saying 'use new style classes they are better than old style ones' isn't a compelling reason.
There is something that you can do with new-style classes, which is calling it's parents functions.
For example if we wanted to have the default name for Child1 as Luigi, you can do the following:

class Child1(Parent):
    def __init__(name="Luigi", **args):
        super(Child1, self).__init__(name=name, **args)

It's one good thing about new style classes, which get's improved in Python3 to:

class Child1(Parent):
    def __init__(name="Luigi", **args):
        super().__init__(name=name, **args)

This will now change the 'calling object' code to:

player1 = Child1('Jay')
player2 = Child1('Joe')

player1.run()
player1.jump()
player1.grow()
player2.run()

Here is Parent and Child1 with the above changes, note I removed all the self.name = name's.

class Parent(object):
    def __init__(name="Player", lives=3):
        self.name = name
        self.lives = lives

    def run(self):
        print "{0.name} is running.".format(self)

    def jump(self):
        print "{0.name} jumps over enemy. TOINK TOINK".format(self)

    def grow(self):
        print "{0.name} sarting to Grow".format(self)

class Child1(Parent):
    def __init__(name="Luigi", **args):
        super(Child1, self).__init__(name=name, **args)

    def blazing_fire(self):
        print "{0.name} used his blazingFire".format(self)


Commenting

Almost universally, comments go before the code they're commenting, rather than after. Conforming to what people expect will make it much easier to read.

Comments should describe why, not what.

# the game continues
while play == 'yes':

# sets a max of 20 guesses
while guessesTaken < 20:
        print ('Take a guess!')

# adds to the guess counter
guessesTaken += 1

That's all examples of where you're describing something that's kind of obvious from looking at the code. This makes it harder to read, because they's more going on. Here's an example of a better comment:

try:
    # If the user enters a number out of range, still counts as a guess
    guess = int(input())
except:
    print ("I'm sorry...")
    continue

Code to show intentions

I'm guessing you haven't learned about functions, so I won't say too much here. They're a good tool that would help a lot to make things more clear. Instead, let's talk about your main loop.

while play != 'yes' and play != 'no':
    print ("I'm sorry, I didn't understand that. Please type yes or no.")
    play = input ()

This looks like a section to do input validation. This is why @Graipher asked if the indentation afterward was correct. To make it more clear, break up the continuation from the validation:

while play != "no":

    #Invalid input
    if play != "yes":
        print ("I'm sorry, I didn't understand that. Please type yes or no.")
        play = input ()
        continue

It's also common to do something like while True, then explicitly break out whenever you're done.

Now, guessesTaken is in a lot of places it doesn't really need to be, which makes it hard to keep track of. Instead of setting it at the beginning, just set it at the beginning of the loop.

while play == 'yes':
    number = random.randint (1,100)
    guessesTaken = 0

This way, your initialization happens in one place, when you use the variable you don't have to go back as far to see what it is, and you don't have to reset it at the end.

Everything is kind of running together. You can use blank lines (and functions!) to break it into logical sections. In the play loop, you can put a blank line in between when you get the guess, and when you check it. Indenting your comments to align with the rest of the code will also make it easier to see the blocks.

Finally, while play == 'yes': This should really be if instead of while. Right now, you have three different loops, which makes it hard to keep track of where the breaks and continues are sending you.


Function wrapper like std::function that uses "small buffer" allocation

Generally, I can't see any real problems, but there are a few things that I'm going to point out:

In the assignment operator, you use std::swap(storage, rhs.storage) and declare it as noexcept. This should probably be conditionally noexcept, based on whether the swap implementation for the given array type (in this case, array<long>) is noexcept. That being said, I'd be really, really surprised if this wasn't always true.

The only other issues I can see are to do with alignment and storage size, which you've basically dealt with thanks to the two static_asserts in the constructor for Function (although they should both have a string detailing exactly what happened if either of them fails). As you're probably aware, there are precious few guarantees about function pointer sizes (especially when you start dealing with a combination of member functions, virtual functions, and multiple inheritance). 4 * sizeof(long) should be enough space to hold anything like this, but this is implementation defined; there are no guarantees.

With regards to alignment, I'm less confident. long is only guaranteed by the standard to be at least 4 bytes, and this is true even for 64-bit platforms. Since storage is actually holding the function itself, the alignment should be made more explicit, and shouldn't rely on the (potentially less stringent) alignment of long. I'd personally suggest:

alignas(std::intptr_t) Storage storage;

which (as far as I can see) should ensure storage will be aligned on the correct boundary.


Testing whether today is the second or fourth Saturday of the month

A few suggestions

collections.defaultdict

holidays = {}
for month in range(1, 13):
    holidays[month] = []
    ...

There is a module for dictionaries starting with a basic datatype

from collections import defaultdict
holidays = defaultdict(tuple)

Secondly you first init it as a list, and afterwards you make it a tuple this is odd. Pick one and stick with it
You don't have to calculate all the months only the specific month

Since you already know which month it is now, just calculate only the month you are interested in

To do this you would have to give the month as a second parameter

def second_fourth_saturday(year, month):
    cal = calendar.monthcalendar(year, month)
    ...

Don't Repeat Yourself

if cal[0][calendar.SATURDAY]:
    holidays[month] = (
        cal[1][calendar.SATURDAY],
        cal[3][calendar.SATURDAY]
    )
else:
    holidays[month] = (
        cal[2][calendar.SATURDAY],
        cal[4][calendar.SATURDAY]
    )

If you calculate the weeks beforehand you don't have to repeat yourself

second_fourth_saturday = (1, 3) if cal[0][calendar.SATURDAY] else (2, 4)

Return what is asked

Instead of return a dict of month with second/fourth saturdays, I think it would be more clear if the function returns a boolean value if the day is a second or fourth saturday

Code

from calendar import monthcalendar, SATURDAY
from datetime import datetime

def second_fourth_saturday(date):
    month_calender = monthcalendar(date.year, date.month)
    second_fourth_saturday = (1, 3) if month_calender[0][SATURDAY] else (2, 4)
    return any(date.day == month_calender[i][SATURDAY] for i in second_fourth_saturday)

if __name__ == "__main__":
    is_second_fourth_saturday = second_fourth_saturday(datetime.today())
    print("Enjoy" if is_second_fourth_saturday else "Start working")


Compare elements of each list of lists to corresponding ones in different list

Your algorithm uses the list.index function to get the indices of the sublists which is an \$O(n)\$ operation. You are also iterating through all the rows and columns of the data which is an \$O(k \times m)\$ operation where \$k\$ is the number of rows and \$m\$ is the number of columns. In the end it is an \$O(n \times k \times m)\$ algorithm.

In my algorithm getting the intersection of the keys is an \$O(\min(\text{len}(A), \text{len}(B)))\$ complexity then iterating the sublists is an \$O(m)\$ which results in an \$O(\min(\text{len}(A), \text{len}(B)) \times m)\$ complexity.

My alternate solution is based on the fact that the first element of each sublist is unique.
I would structure the data in a different way and use dictionaries instead of lists.
As each first element is unique this would be the key and the rest of the sublist would be the value in the dictionary.
After inserting all the data in the dicts, taking the intersection of the keys would result in a (hopefully) smaller set of data.
The output would be also a dictionary created while iterating through the resulting keys.

output = defaultdict(list) # from collections
keys = A.keys() & B.keys() # intersect the keys
for key in keys:
    # create output based on sublists
    output[key] = ['ok^ok' if a==b else '{}^{}'.format(a,b) for a,b in zip(A[key],B[key])]

For execution time I generated random strings for keys and values. Each key and sublist element was a randomly generated unique string of length 10. Each key had 50% chance to be included in both A and B and each sublist element also had a 50% to be the same for the corresponding element in the other dictionary. I created 50k keys and 104 sublist element for each key.

Generating the data took me around 26 seconds and creating the output took less than 1 second. The results depend on the matching key ratio of the two datasets but it never took more than 2 seconds to finish.


Listing the differences between corresponding elements of two arrays or two objects

The simplest answer is to remove deltaArray and use deltaHash for everything. As long as your arrays don't have any extra properties, the results will be identical, except the keys are stored as strings instead of numbers.

I'm not sure it's useful to store the keys in one array and the values in another. Storing the keys in an array could be useful if ordering the keys is important, but that doesn't apply here (since we got the keys from a for...in loop, we encountered them in an undefined order). So, you could let the keys be keys and let the values be values, and if you need an array of keys, use Object.keys.

var deltaHash = function(a, b) {
    var delta = {};
    for (var key in b)
        if (a[key] !== b[key])
            delta[key] = b[key];
    return delta;
};

If you still want a separate function for arrays, it would look like this:

var deltaArray = function(a, b) {
    var delta = {};
    for (var i = 0, l = a.length; i < l; ++i)
        if (a[i] !== b[i])
            delta[i] = b[i];
    return delta;
};

You'd still probably want to eliminate redundancy in this case. We could extract the duplicated code into a separate function and end up with something like this:

var diff = function(a, b, delta, key){
    if (a[key] !== b[key])
        delta[key] = b[key];
};

var deltaHash = function(a, b) {
    var delta = {};
    for (var key in b)
        diff(a, b, delta, key);
    return delta;
};

var deltaArray = function(a, b) {
    var delta = {};
    for (var i = 0, l = a.length; i < l; ++i)
        diff(a, b, delta, i);
    return delta;
};

Somehow that's not very satisfying, though; it still feels redundant. What we have at this point really feels like it wants to be more of a classical design:

function Delta() { }

Delta.prototype.diff = function(a, b, key) {
    if (a[key] !== b[key])
        this[key] = b[key];
};

Delta.prototype.initFromArrays = function(a, b) {
    for (var i = 0, l = a.length; i < l; ++i)
        this.diff(a, b, i);
};

Delta.prototype.initFromObjects = function(a, b) {
    for (var key in b)
        this.diff(a, b, key);
};

But again, most of this is not necessary if you decide to build deltas for arrays the same way you build them for other objects, using something like your original deltaHash for both. Aside from some possible naming and stylistic issues, and the awkwardness of having the keys in a separate array, it should do the trick (although you might want to add a hasOwnProperty check, and use push).

Hope this gives you some ideas.


Do not use single-character names for variables.  This will make your code harder to understand.  Give them names based on their significance to the program.
Put your two arrays on separate lines for clarity:

char a[] = {'1','2','3','4'};
char b[] = {'\0','\0','\0','\0','\0'};

Arguments to a function that aren't modified within the function should be const.

This applies to a[] in main():

const char a[] = {'1','2','3','4'};

Parameters that aren't modified within a function could be const in order to prevent any accidental modifications.

This applies to all parameters in this program except for b[].
Since you declare your for loop counters inside the loop statement, and you're using bools, then it appears you're using C99.

Two things you should be doing here:

Consistently declare your loop counters inside the statements.  You're doing it the pre-C99 way in isUnique().
Your code does not compile with the bools.  To use them, you must include <stdbool.h>.

You're inconsistently declaring your loop counters inside and outside the for loop statements.  Since you initialize them inside in one instance, you must be using C99.  If so, then this should be consistent for each of these loops.
In perm(), you should have curly braces for the else, just as you have them for the if.  Make sure to maintain such consistencies throughout your program.

You should also do this for the for loops and ifs in isUnique().  It is especially important here as it helps with maintenance and will allow you to add additional lines if needed.
Functions in C that have no parameters should have a void parameter:

int main(void) {}

The return 0 at the end of main() is unneeded; the compiler will do this automatically.

With these changes, I've come up with the following code (also tested on Ideone):

#include <stdbool.h>
#include <stdio.h>

bool isUnique(const char x[], const int y)
{
    for (int i = 0; i < (y-1); i++)
    {
        for (int j = i+1; j < y; j++)
        {
            if (x[i] == x[j])
            {
                return false;
            }
        }
    }

    return true;
}

void perm(const char a[], char b[], const int x, const int y)
{
    if ((y == x) && isUnique(b, x))
    {
        b[y] = '\0';
        printf("%s\n", b);
    }
    else
    {
        for (int i = 0; i < x; i++)
        {
            b[y] = a[i];

            if (y < x)
            {
                perm(a, b, x, y+1);
            }
        }
    }
}

int main(void)
{
    const char a[] = { '1', '2', '3', '4' };
    char b[] = { '\0', '\0', '\0', '\0', '\0' };

    perm(a, b, 4, 0);
}


Program to top-up phone with conditions in Python

You can divide your whole program into parts, this way it becomes easy while debugging and increases modularity in the code.
You can divide into multiple functions like

Selecting service.
Add top-up
Restart logic

Refractored code
AVAILABLE_SERVICES = {"Green", "Blue", "Red"}
AVAILABLE_TOPUPS = {50, 100, 300, 500, 1000}

def select_service():
    while True:
        service = input("Please enter Green, Blue or Red: ").title()
        if service in AVAILABLE_SERVICES:
            print("Welcome to Top-up Service")
            break
    return service

def top_up(service):
    times_topup = int(input("How many times do you want to top up? "))
    topups_selected = []
    for _ in range(times_topup):
        while True:
            topup = int(input("Please enter 50,100,300,500 or 1000: "))
            if topup in AVAILABLE_TOPUPS:
                topups_selected.append(topup)
                break
            else:
                print("Try Again!, Wrong Top-up")

    print("Top up(s) information : ", topups_selected)
    print("Total top up(s): ", sum(topups_selected))

def process():
    restart = "Y"
    while restart == "Y":
        service = select_service()
        top_up(service)
        restart = input("Do you want to start again?,Y or else: ").upper()
    print("Thank you for using our service")

if __name__ == "__main__":
    process()

Output:
Please enter Green, Blue or Red: Blue
Welcome to Top-up Service
How many times do you want to top up? 2
Please enter 50,100,300,500 or 1000: 7
Try Again!, Wrong Top-up
Please enter 50,100,300,500 or 1000: 50
Please enter 50,100,300,500 or 1000: 10
Try Again!, Wrong Top-up
Please enter 50,100,300,500 or 1000: 100
Top up(s) information :  [50, 100]
Total top up(s):  150
Do you want to start again?,Y or else: Y
Please enter Green, Blue or Red: Red
...
...
...
Do you want to start again?,Y or else: n
Thank you for using our service

Code Review

PEP-8 violations:

E231 - missing whitespace after ,

range(1,n+1) ⟶ range(1, n+1)
{50,100,300,500,1000} ⟶ {50, 100, 300, 500, 1000}

Declare constants for services and top-ups instead of writing {"Blue", ...} and {50, ...} everywhere.

{"Blue", ...} ⟶ AVAILABLE_SERVICES = {"Green", "Blue", "Red"} Now you can use AVAILABLE_SERVICES instead of writing {"Blue", ...}
{50, ...} ⟶ AVAILABLE_TOPUPS = {50, 100, 300, 500, 1000}

Use str.title when taking input for service, so "BLUE" would become "Blue".
Use _ here for i in range(1, n+1) when you are not using i in the loop.

for i in range(1, n+1) ⟶ for _ in range(n)
What's the purpose of _ in python

You can make AVAILABLE_SERVICES as frozenset to make immutable.

AVAILABLE_SERVICES = frozenset({"Green", "Blue", "Red"})
AVAILABLE_TOPUPS = frozenset({50, 100, 300, 500, 1000})

You can use pep8online* to check if your code is in accordance with PEP-8 standard.
You can use black* (code formatting tool)
black --line-length 79 your_file.py

* I'm not affiliated to pep8online and black.


Creating dialogs and modals with AngularJS

The disadvantage is the modal directive hanging around for no good reason in the templates, and a tight coupling between the controller and the modal directive.

Far better is using a service to inject this modal into the DOM as needed.
This is the approach that for example the AngularUI team uses in their approach.

This ensures lower coupling (more creative freedom and less technical debt), more easily testable code, and a more intuitive API. Simply inject and call a service, rather than having to make sure the directive is added, and the controller writes to the correct variable, and they share the same scope etc.

The reason you are encouraged to use directives for DOM manipulation is first and foremost convention and testability issues. Using a service in this use-case is an acceptable exception.


I'm not a smart man.

Just figured out that I was covering the buttons with the #orbit div...


An ASCII histogram of a die rolled n times

The roll function generates a random sequence of integers. The loop body shows me that you know how to seed a pseudo-RNG with a true source of randomness but you're doing it for every iteration. You should seed the pseudo-RNG once and then use it in the loop. You know how big your rand vector will be by the time you're done with it so you should reserve memory for it so that it the memory doesn't need to be reallocated as you push integers. So your roll function should probably look like this:

std::vector<int> roll(int times)
{
    std::vector<int> rand;
    rand.reserve(times);

    std::random_device seeder;
    std::mt19937 engine(seeder());
    std::uniform_int_distribution<int> dist(1, 6);

    while (times > 0)
    {
        rand.push_back(dist(engine));
        --times;
    }

    return rand;
}

The next function, histrogram_calculate creates a histogram. The histogram is stored in a std::map<int, int> which is not really the best choice. Think about what we're storing.

1 -> 7
2 -> 3
3 -> 10
4 -> 1
5 -> 0
6 -> 5

We want to know the frequency of six numbers. Since six is a compile-time constant, we could use a std::array<int, 6> instead. Initializing an array to zero is as simple as histogram.fill(0). With a std::map<int, int> you need to set keys to zero in a loop.

auto max_element = 6;

for (int i = 1; i <= max_element; ++i)
{
    cnt_hashmap[i] = 0;
}

Using auto here is not a good idea. In fact, int is shorter and provides more information. Also, max_element should be a constant since it doesn't actually change. The max_element variable is a good start but 6 should be available to the roll function as well. You should create a global constant for 6 or perhaps use a template parameter.

// The number of sides on a die
constexpr int num_sides = 6;

histrogram_calculate iterates the vector of random numbers and counts up the frequencies.

for (auto iter = random_numbers.begin(); iter != random_numbers.end(); ++iter)
{
    cnt_hashmap[*iter] += 1;
}

Here, you're using iterators when you could be using a range-for.

for (const int num : random_numbers) {
    cnt_hashmap[num]++;
}

Wait just a minute!

histogram_calculate makes a call to roll which returns a sequence of random integers but then, it's just thrown away! Do we really need the whole sequence in order to create a histogram?

No. We can create the histogram directly from the sequence of random numbers. There's no need to create an array and then just throw it away.

I'll let you try this yourself.

histogram_draw knows how to generate a histogram. histogram_draw should take a histogram and draw it. histogram_draw should have no idea where the histogram is coming from. histrogram_draw should just draw a histogram.

As @Calak pointed out in the comments, histrogram_draw doesn't actually behave as intended so this question is technically off-topic. Might I suggest that you write code to print a horizontal histogram? English text is typically written left-to-right so it is considerably easier to draw a horizontal histogram than a vertical one.

1 | ####### 7
2 | ### 3
3 | ########## 10
4 | # 1
5 | 0
6 | ##### 5

If you make improvements to your code, feel free to create a new question with your improved code. Just make sure that it functions as intended, otherwise, you risk getting flagged for being off-topic.


Finding the busiest time-frame in a parking lot

Naming Conventions

MSDN, General Naming Conventions

DO NOT use Hungarian notation:

[dt]Start in getPickTimeframe() --> DateTime currentFrameStartDate
[dt]End in getPickTimeframe() --> DateTime currentFrameEndDate

DO favor readability over brevity:

ParkedCar --> ParkingLog
getPickTimeframe(List<ParkedCar> [cars]) --> GetPeakTimeFrame(List<ParkingLog> parkingLogs)
public int [countCars]; --> public int TotalNumberOfParkedCars;
int [count] = 0; --> int currentFrameNumberOfParkedCars;

MSDN, Naming Guidelines / Capitalization Conventions
DO use PascalCasing for all public member, type, and namespace names consisting of multiple words:

[G]et[Pick]Time[F]rame() --> GetPeakTimeFrame()
class ParkTime[F]rame
ParkTime[F]rame.[S]tartTime
ParkTime[F]rame.[E]ndTime
ParkTime[F]rame.[C]ountCars --> Also see above for alternative name
ParkedCar.[A]rrivalTime
ParkedCar.[L]eavingTime

Implementation

Your current implementation, besides efficiency, is not working correctly.

For parkings as the following:

// Parking opens at 07:00
DateTime parkingOpenDate = DateTime.Now.Date.AddHours(7);

// t --xxxxxxxx--------------------------------07:02 - 07:10
// t ---xxxxxxxx-------------------------------07:03 - 07:11
// t --------------xxxxxxxx--------------------07:14 - 07:22
// t --------xxxxxxxxx-------------------------07:08 - 07:17
// t 001222223321112221111100000000000000000000

new ParkingLog[]
{
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(2), LeavingTime = parkingOpenDate.AddMinutes(10) },
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(3), LeavingTime = parkingOpenDate.AddMinutes(11) },
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(14), LeavingTime = parkingOpenDate.AddMinutes(22) },
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(8), LeavingTime = parkingOpenDate.AddMinutes(17) }
}

It should output

07:08.00 - 07:10:00 with 3 cars

However, it outputs:

07:02.00 - 07:10:00 with 2 cars

Here are my changes to the code, calculating the correct peak time frame, only assuming the LeavingDate of each ParkingLog (ParkedCar in your source) is greater than the ArrivalDate:

public class _113182
{
    private SortedList<DateTime, int> carParkCapacityTracker = new SortedList<DateTime, int>();

    public class ParkingTimeFrame
    {
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public int TotalNumberOfParkedCars { get; set; }

        public override string ToString()
        {
            return string.Format("{0:HH:mm.ss} - {1:HH:mm:ss} | #Cars: {2}", StartTime, EndTime, TotalNumberOfParkedCars);
        }
    }

    public class ParkingLog
    {
        public DateTime ArrivalTime { get; set; }
        public DateTime LeavingTime { get; set; }

        public override string ToString()
        {
            return string.Format("{0:HH:mm:ss} - {1:HH:mm:ss}", ArrivalTime, LeavingTime);
        }
    }

    private void TrackCarParkingAction(DateTime actionDate, int actionEffect)
    {
        if (!carParkCapacityTracker.ContainsKey(actionDate))
        {
            carParkCapacityTracker.Add(actionDate, actionEffect);
        }
        else
        {
            carParkCapacityTracker[actionDate] += actionEffect;
        }
    }

    private void TrackCarParkingAction(ParkingLog parkingLog)
    {
        TrackCarParkingAction(parkingLog.ArrivalTime, +1);
        TrackCarParkingAction(parkingLog.LeavingTime, -1);
    }

    public ParkingTimeFrame GetPeakTimeFrame(List<ParkingLog> parkingLogs)
    {
        carParkCapacityTracker.Clear();

        parkingLogs.ForEach(TrackCarParkingAction);

        int currentNumberOfParkedCars = 0;
        int maximumNumberOfParkedCars = 0;
        int maximumCapacityFrameOffset = 0;

        for (int currentFrameOffset =  0; currentFrameOffset < carParkCapacityTracker.Count; currentFrameOffset++)
        {
            currentNumberOfParkedCars += carParkCapacityTracker.Values[currentFrameOffset];
            if (maximumNumberOfParkedCars <= currentNumberOfParkedCars)
            {
                maximumNumberOfParkedCars = currentNumberOfParkedCars;
                maximumCapacityFrameOffset = currentFrameOffset;
            }
        }

        return new ParkingTimeFrame()
        {
            StartTime = carParkCapacityTracker.Keys[maximumCapacityFrameOffset],
            EndTime = carParkCapacityTracker.Keys[maximumCapacityFrameOffset + 1],
            TotalNumberOfParkedCars = maximumNumberOfParkedCars
        };
    }
}

And here is the code to test it:

public static void Main()
{
    Console.WriteLine("Enter to start..");
    Console.ReadLine();

    // Parking opens at 07:00
    DateTime parkingOpenDate = DateTime.Now.Date.AddHours(7);

    List<ParkingLog> parkingLogs = new List<ParkingLog>
    (
        // t --xxxxxxxx--------------------------------07:02 - 07:10
        // t ---xxxxxxxx-------------------------------07:03 - 07:11
        // t --------------xxxxxxxx--------------------07:14 - 07:22
        // t --------xxxxxxxxx-------------------------07:08 - 07:17
        // t 001222223321112221111100000000000000000000

        new ParkingLog[]
        {
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(2), LeavingTime = parkingOpenDate.AddMinutes(10) },
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(3), LeavingTime = parkingOpenDate.AddMinutes(11) },
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(14), LeavingTime = parkingOpenDate.AddMinutes(22) },
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(8), LeavingTime = parkingOpenDate.AddMinutes(17) }
        }
    );

    // Should output 07:08 - 07:10 with 3 cars
    Console.WriteLine("{0}", new _113182().GetPeakTimeFrame(parkingLogs));
}

Edit:

The OP told me that he tested the code and the code failed.

I tested it with the same input (as documented in the question by the OP) and it produced the correct result:

public static void Main()
{
    // According to the data provided by the OP
    // 10:10, 11:10
    // 10:30, 12:40
    // 10:25, 11:10
    // 11:10, 12:20

    //       10:00    10:10    10:25    10:30    11:10    12:20    12:40
    // CAR 1            xxxxxxxxxxxxxxxxxxxxxxxxxxx
    // CAR 2                              xxxxxxxxxxxxxxxxxxxxxxxxxxxx
    // CAR 3                     xxxxxxxxxxxxxxxxxx
    // CAR 4                                       xxxxxxxxxx

    // The peak time frame should be: 10:30 - 11:10 with 3 cars:

    List<ParkingLog> parkingLogs = getParkedCars();
    Console.WriteLine("{0}", new _113182().GetPeakTimeFrame(parkingLogs));
}

Output:

10:30.00 - 11:10:00 | #Cars: 3

Edit 2:

The OP provided new test data and asserted that the code fails with this data.

Here is my test, and it works as expected, or there is something wrong and we are not on the same page:

// According to the new data provided by the OP
//09:00, 15:00
//10:10, 11:10
//10:30, 12:40
//10:35, 11:20
//10:25, 11:10
//11:10, 12:20

//       09:00    10:10    10:25    10:30    10:35    11:10    11:20    12:20    12:40    15:00
// CAR 1   xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 2            xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 3                              xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 4                                       xxxxxxxxxxxxxxxxxxx
// CAR 5                     xxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 6                                                xxxxxxxxxxxxxxxxxxx

// The peak time frame should be: 10:35 - 11:10 with 5 cars:

List<ParkingLog> parkingLogs = getParkedCars();
Console.WriteLine("{0}", new _113182().GetPeakTimeFrame(parkingLogs));

And the output is:

10:35.00 - 11:10:00 | #Cars: 5


We probably want to be able to move-construct, so as well as this constructor:

SafeVector(const SafeVector& orig) : vec(orig.vec), mut(), cond() {}

We probably want also:

SafeVector(SafeVector&& orig)
  : vec{std::move(orig.vec)},
    mut{},
    cond{}
{}

I'd recommend being able to construct from a standard vector:

SafeVector(std::vector vec)
  : vec{std::move(vec)},
    mut{},
    cond{}
{}

Since we always default-initialize mut and cond, we could declare their initializers in the class definition, removing the need to have them in the constructors' initializer lists.

There's no need to specify an empty destructor - just let the compiler generate it.

I think we probably want one or more assignment operators.

Big question: how can we safely use iterators we get from begin() and end()?  There's no way for client code to lock the mutex until it's finished using the iterators.


Importing a report through the enabler4excel add-in

Readability & Maintainability

Use indentation to make control-structures easier to understand and read.
Some variables are all lower-case, some are camelCase, some are PascalCase. OCD is unhappy :( Use a consistent naming convention. I'd recommend camelCase. Either way, choose one and stick to it
ButtonClick1 is a rather non-descriptive name
these "random" spaces before the third argument look strange. I assume they're not there in your own code, right?

Compartmentalization
You should be able to make your code into neat little compartments. Those are also known as "methods", "functions", "procedures"  or a handful of other names. All these separate paragraphs that have been mentioned in a comment already can almost be methods. Consider:
Set automationObject = FindEnablerAddin()
' [...]
Private Function FindEnablerAddin() As Object
    For Each addin In Application.COMAddIns
        If addin.Description = "Enabler4Excel" Then
            Set FindEnablerAddin = addin.Object
            Exit Function
        End If
    Next addin
    'FindEnablerAddin should be Nothing
End Function

This can be applied in other places as well. Note that I have used Exit Function to break the loop over all COMAddIns early. This may or may not help with performance noticeably. It usually avoids work, so you should do it.
Performance & Nitpicks

You can usually significantly increase performance by turning of Events, Calculation and ScreenUpdating in Excel. Don't forget to turn them back on, even if your code falls into an error state.
Working on the Workbook directly is slow. Then again this looks like you don't have much of a choice here
Instead of If Result = False Then you can use If Not Result Then. This is cleaner and avoids the potential for confusion about assignment and boolean comparisons


Geocoder form with Google Maps autosuggest

From a once over:

When you wrote

var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());

you probably meant to write

var latLng = results[0].geometry.location;
$('#lat').val(latLng .lat());
$('#lng').val(latLng .lng());

I wonder why you capture new google.maps.places.Autocomplete(input, options); into autocomplete since you do nothing with autocomplete.
1 var block with comma separated variables is considered the standard, preferably on top.
You could capture document.getElementById('location') into a var to prevent repeated DOM lookups
Don't do console.log in production code
Creating GeoCoded as an object with 1 property is overkill, why not simply
var geoCodingDone = false;
lowerCamelCasting is not applied consistently : autosuggest -> autoSuggest, autocomplete -> autoComplete
There is an indentation problem after return true;

With all that, I would counter suggest something like

$(document).ready(function () {

  var geoCodingDone = false,
      locationInput = document.getElementById('location');

  createAutoSuggest();

  $('#myform').on('submit', function (e) {
    if (geoCodingDone)
      return true;

    var geocoder = new google.maps.Geocoder(),
        address  = locationInput.value;

    e.preventDefault();

    $('#myform input[type="submit"]').attr('disabled', true);

    geocoder.geocode( {'address': address }, function (results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            var latLng = results[0].geometry.location;
            $('#lat').val(latLng.lat());
            $('#lng').val(latLng.lng());
            geoCodingDone = true;
            $('#myform').submit();
        } else {
            $('#myform input[type="submit"]').attr('disabled', false);
        }
    });
  });
});

function createAutoSuggest(){
  var options = { types: [] };
  new google.maps.places.Autocomplete(locationInput, options);
}


JavaScript function for to create HTML-elements

Some thoughts below:

Consider passing attrs as an object or object literal representing key:value pairs.  This would eliminate need for more fragile string parsing approach you currently have.

You could replace all of this:

  attrs = attrs || '';
  innerHtml = innerHtml || '';

  ret = document.createElement(nodeName);

  attrs = attrs.split(/\s/g);

  if (attrs[0]) {
    attrs.forEach(function(attr) {
      attr = attr.split(/=/);

      if (attr[1]) {
        ret.setAttribute(attr[0], attr[1]);
      }
    });
  }

with this:

  attrs = attrs || {};
  innerHtml = innerHtml || '';

  ret = document.createElement(nodeName);

  for (attr in attrs) {
        ret.setAttribute(attr, attrs[attr]);
  }

Consider different name.  "get", in typical programming thought often refers to retrieval of an existing item. I would think createHtmlElement or similar would be more appropriate.
I would strongly consider adding some additional validation around the input node name, to at a minimum make sure you have a non-zero length string.
After element creation, you could determine whether ret contains HTMLUnknownElement object, which would indicate that the browser did not recognize the node name value.  This could be useful if you wanted to fail out at this point to not allow arbitrary tag creation.  Perhaps whether or not to allow arbitrary (custom) tag creation could even be a flag passed as optional parameter.
Consider throwing known Error object rather than vanilla object literal of your own creation. You get a lot more utility from this Error object than from generic object.  Check out the documentation at link below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

Example:

throw new Error('error message');


Dynamically call lambda based on stream input: Try 3

I was about to add more things to my answer on your previous post and noticed meanwhile that your already asked a following question (that's almost too fast! :o). I have done some additional reading about C++14 and integer sequences. And I have found some things in the standard that could help to improve your code again.

I realized at some point that you were using int as the value_type of std::integer_sequence. However, you initialize your static constexpr int size with the result of sizeof... and sizeof... returns a std::size_t, not an int.

Then I remembered that, along with std::integer_sequence, there is a typedef for std::integer_sequence<std::size_t, N> which is called std::index_sequence and which has been made to solve the kind of problem that your are trying to solve. Therefore, you should every occurrence of int by std::size_t and of std::integer_sequence<int, N> by std::index_sequence<N>.

Moreover, you don't need to create a typedef for Sequence in CallerTraits: you can deduce this class directly in callFunctor thanks to CallerTraits<>::size:

template<typename StreamValueGetter, typename Action, typename Stream>
void callFunctor(Stream& stream, Action action)
{
    using Sequence = std::make_index_sequence<CallerTraits<Action>::size>;
    expandArgsAndCallFunctor<StreamValueGetter>(stream, action, Sequence());
}

Note that I also replaced decltype(action) by Action since it is the same type.

Also, you can get rid of the public inheritance specifier for CallerTraits since you are using a struct. That does not change anything whatsoever.

Here is your code once refactored. I don't provide a link to an online compiler since none of the ones available has a good enough C++14 support (you just need to add some light library components though):

template <typename T>
struct CallerTraits
    : CallerTraits<decltype(&T::operator())>
{};

template<typename C, typename ...Args>
struct CallerTraits<void (C::*)(Args...) const>
{
    static constexpr std::size_t                size = sizeof...(Args);
    typedef std::tuple<std::decay_t<Args>...>   AllArgs;
};

template<typename StreamValueGetter, typename Action, typename Stream, std::size_t... S>
void expandArgsAndCallFunctor(Stream& stream, Action action, std::index_sequence<S...>)
{
    typedef CallerTraits<Action>        Trait;
    typedef typename Trait::AllArgs     ArgumentTuple;

    // ArgumentTuple  arguments(StreamValueGetter::template get<typename std::tuple_element<S, ArgumentTuple>::type>(stream)...);
    // action(std::get<S>(arguments)...);

    // The above two commented out lines
    // Represent the logic of the following line which retrieves
    // and calls the arguments in a single line thus avoiding temporaries.
    action(StreamValueGetter::template get<std::tuple_element_t<S, ArgumentTuple>>(stream)...);
}

template<typename StreamValueGetter, typename Action, typename Stream>
void callFunctor(Stream& stream, Action action)
{
    using Sequence = std::make_index_sequence<CallerTraits<Action>::size>;
    expandArgsAndCallFunctor<StreamValueGetter>(stream, action, Sequence());
}


Is there a better way than lambda to filter on attributes/methods of objects?

I would use a list comprehension:

contexts_to_display = ...
tasks = [t for t in Task.objects.all()
         if t.matches_contexts(contexts_to_display)
         if not t.is_future()]
tasks.sort(cmp=Task.compare_by_due_date)

Since you already have a list, I see no reason not to sort it directly, and that simplifies the code a bit.

The cmp keyword parameter is more of a reminder that this is 2.x code and will need to be changed to use a key in 3.x (but you can start using a key now, too):

import operator
tasks.sort(key=operator.attrgetter("due_date"))
# or
tasks.sort(key=lambda t: t.due_date)

You can combine the comprehension and sort, but this is probably less readable:

tasks = sorted((t for t in Task.objects.all()
                if t.matches_contexts(contexts_to_display)
                if not t.is_future()),
               cmp=Task.compare_by_due_date)