Getting NTFS permissions of all shared folders on the local machine

The only way to improve the speed of the script is to drop the usage of Excel as a COM-object altogether. It is considered bad practice. And it is not possible on servers where Excel is not installed.

It's better to use a library like NPOI (.NET port from Apache POI (java)).

I used this (old) example as a base and adapted it to roughly match your code.

[Reflection.Assembly]::LoadFrom("C:\Users\IEUser\Desktop\Release\Net40\NPOI.dll")
[Reflection.Assembly]::LoadFrom("C:\Users\IEUser\Desktop\Release\Net40\NPOI.OOXML.dll")
[Reflection.Assembly]::LoadFrom("C:\Users\IEUser\Desktop\Release\Net40\NPOI.OpenXml4Net.dll")
[Reflection.Assembly]::LoadFrom("C:\Users\IEUser\Desktop\Release\Net40\NPOI.OpenXml4Net.dll")
[Reflection.Assembly]::LoadFrom("C:\Users\IEUser\Desktop\Release\Net40\NPOI.OpenXmlFormats.dll")
[Reflection.Assembly]::LoadFrom("C:\Users\IEUser\Desktop\Release\Net40\ICSharpCode.SharpZipLib.dll")

$wb = New-Object NPOI.XSSF.UserModel.XSSFWorkbook;
$ws = $wb.CreateSheet("output");
$ws.CreateRow(0)| out-null;

$dirToAudit = Get-ChildItem -Path "C:\Users\IEUser" -recurse | Where { $_.psIsContainer -eq $true }

$intRow = 1

foreach ($dir in $dirToAudit)
{
    $colACL = Get-Acl -Path $dir.FullName

    foreach ($acl in $colACL)
    {
        $fileNameRow = $ws.CreateRow($intRow)
        $fileNameRow.CreateCell(1).SetCellValue($dir.FullName)
        $intRow++

        foreach ($accessRight in $acl.Access)
        {
            $values = $ws.CreateRow($intRow)
            $values.CreateCell(2).SetCellValue($($AccessRight.IdentityReference).ToString())
            $values.CreateCell(3).SetCellValue($($AccessRight.FileSystemRights).ToString())
            $values.CreateCell(4).SetCellValue($($acl.AreAccessRulesProtected).ToString())
            $intRow++
        }
    }

}
$fs = new-object System.IO.FileStream("C:\Users\IEUser\Desktop\test.xlsx",[System.IO.FileMode]'Create',[System.IO.FileAccess]'Write')
$wb.Write($fs);
$fs.Close()

There is also another library for this kind of stuff: EPPLus

And someone else made some nice powershell functions for it.


Basic Implementation of Hash Table in Python

Your code looks generally quite good. I just have a few suggestions:

Don't forget to define __str__() and __repr__() for each class
I dislike the use of the "magic number" constants in the __init__() of the Hash_Map. They really ought to be either passed as parameters, read from a config somewhere, or clearly marked in a parameter section as pseudo-constants.
The line for i in range(len(self.table)): appears multiple times. This style of loop is considered non-Pythonic. Python has the enumerate() built-in that returns a succession of tuples consisting of both the item and its index. I'd prefer for (i,item) in enumerate(self.table):
If there's a clash, hash(key) will unnecessarily be called multiple times. Note that index = self.__get_hash_code(key, i) is called each time through the i loop, but the first thing it does is call hash(key) even though it may have already been computed. Better to compute hash(key) once outside the loop since it won't change.
Multiple references to self.table[index]. The interpreter might be able to optimize them away, but the code will be shorter (and less error-prone) if it performs the lookup once and stores in a temp. (Or just use enumerate() like my previous suggestion)
In def __get_hash_code(self, key, value): the third parameter is poorly named. It's not the value of the element, it's the linear probing parameter.
There's a bug related to the interaction of __get_hash_code() and __resize_table() which can lead to \$O(n)\$ performance, defeating the purpose of using a hashtable.


Bug

Your code does not work when either the left or right array is empty.

left_item = items1[left_pointer]
right_item = items2[right_pointer]

When item1 or item2 is an empty array this will break with an IndexError.

if right_pointer >= len(items2):
    sorted_list.extend(items1[left_pointer:])
    break
if left_pointer >= len(items1):
    sorted_list.extend(items2[right_pointer:])
    break

You should move this piece of code up to avoid the issue. Now it will break when either is empty.

Tests

I think you can improve your tests quite some bit using the builtin unittest framework.

import unittest

class TestMergeSort(unittest.TestCase):
    def test_normal_merge(self):
        left = [1, 4, 7]
        right = [2, 3, 6, 9]
        out = [1, 2, 3, 4, 6, 7, 9]
        self.assertEqual(merge(left, right), out)

    def test_right_empty(self):
        left = [1, 4, 7]
        right = []
        out = [1, 4, 7]
        self.assertEqual(merge(left, right), out)

    def test_left_empty(self):
        left = []
        right = [2, 3, 6, 9]
        out = [2, 3, 6, 9]
        self.assertEqual(merge(left, right), out)

if __name__ == "__main__":
    unittest.main()

Merge function

An easier way would be to pop the left sides (index=0) of the list and append to the result until either one is empty, after that you can add the remaining to the result.
Naming: I believe you should rename your item1 and item2 to left and right for clarity.
This will no longer have the bug, that it will raise an IndexError when either of the list's are empty.

def merge_sorted_lists(left, right):
    result = []
    while left and right:
        if left[0] < right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    return result + left + right


Function to skip assignments and apply multiple functions

I like it, though it looks a lot like array_map(). I would get rid of the § symbol. Instead, 'use' a very short custom function alias that is ASCII. Something like map().

Also, you could make this more powerful if you use variadics.


Note: you're cloning a DOM element not an actual image..

About .querySelector

The great thing about .querySelector is that you can use any DOMString (CSS string selectors) to select the elements. However in your case you're using the action attribute on the button. So essentially you're already naming your buttons (here there's only one). You can actually get away with not naming them at all. If you have multiple buttons you could simply select them with .querySelectorAll which returns a NodeList that you can either:

directly iterate over with the built-in forEach

document.querySelectorAll('button').forEach(button => {
  // do something with `button`
});

or first convert the NodeList into an Array. You can use the ES6 spread syntax to destructure the iterable NodeList object into an actual object of type Array. This way you can then apply methods from the Array class, for example: .forEach, .map, .reduce, .filter, etc... Here's an example:

[...document.querySelectorAll('button').forEach(button => {
  // do something with `button`
}

I personally never go with .getElementById or .getElementbyClassName and always use .querySelector and .querySelectorAll.

About .nodeNode

If you're going to duplicate a DOM element on the page then I would say nodeList is the way to go. There are alternatives but they are slower.

copy the OuterHTML of the image (the actual image tag) and add it directly to the innerHTML of #image-section with .innerHTML +=. This is by far the worst idea as it forces the browser to re render the DOM when the property is changed. You can read more on this other Stack Overflow post.
copy the OuterHTML of the image, create a new element we will use as a wrapper for our duplicate then add the image element as the wrapper's child and append the wrapper's first child (the image) to #image-section.

Here is how it can be implemented:

const duplicate = () => {
  const image = document.querySelector('img[alt="Dog"]');
  const copy = document.createElement('div');
  copy.innerHTML = image.outerHTML;
  document.querySelector('#image-section').appendChild(copy.firstChild);
}

I have tested both version with a timer to make sure, here is the code. Results are below.

const timeit = fn => {
    const start= new Date();
    let i = 1000;

    while(i--) fn();
    return new Date()-start;
}

console.log('clone: ', timeit(clone), 'ms')
console.log('duplicate: ', timeit(duplicate), 'ms')

       <button action="button">Yeah, I want more dogs!</button>

Results are here, time to render 1000 dogs (in ms):

-----------------Chrome:----------------
clone:  50 | 30 | 44 | 38 | 50 | 37 | 42
copy:   86 | 50 | 55 | 50 | 57 | 45 | 56

-----------------Firefox:---------------
clone:  42 | 46 | 44 | 66 | 34 | 53 | 50
copy:   59 | 49 | 50 | 97 | 55 | 55 | 58

You should stick with nodeClone(true).

For further reference on this read: Deep cloning vs setting of innerHTML: what's faster?


When calling the function malloc():

The returned type is void*, so it can be assigned to any pointer, making the 'cast' totally unneeded. It just clutters the code, making it more difficult to understand, debug, maintain.
The expression sizeof(char) is defined in the standard at 1. Multiplying anything by 1 has no effect, so the expression just clutters the code.
When calling any of the memory allocation functions (malloc, calloc, realloc), always check (!=NULL) the returned value to assure the operation was successful.

When invoking the main() function and the code does not use the parameters, use the signature int main(void).

When compiling, always enable all the warnings, then fix those warnings. (For gcc, at a minimum use: -Wall -Wextra -pedantic I also use: -Wconversion -std=gnu99.)

For ease of understanding and readability by the reader of the code:

Separate code blocks (for, if, else, while, do...while, switch, case, default) via a blank line.
Use meaningful variable names. A variable name should indicate usage or content (or better, both).

The code is using 'named' semaphores. 'named' semaphores are persistent, so calling sem_open() with the O_CREAT parameter will fail if the file has ever been run before.  I suggest first calling sem_unlink().

The calls to error() are not correct. The passed parameter is errno, a negative number, not a char and will not tell the user anything useful, especially if what is displayed is the contents of memory those address corresponds to the errno value. I suggest calling syserror() to get the error message that the OS thinks caused the error.

The call to pthread_create() returns 0 on success and -1 on failure. Passing that -1 to the function error() is meaningless.

I suggest passing a char* similar to error("pthread_create for producer failed") then modifying the error() function to expect a pointer to a char array.

The call to sem_open() returns a value SEM_FAILED which might be equal to -1 but that is an implementation detail, so do not use -1, use SEM_FAILED.

The second call to sem_open() returns busy, so the error check following that call should be checking busy, not free.

There are several other problems with the code, but the above comments should get you moving in the right direction.


optimizing conversion between string and date

Here's a one-liner for you:

    private DateTime convertToDateFromString(string dateString)
    {
        DateTime bufferDate;

        return DateTime.TryParseExact(
            dateString,
            new[] { "MMddyy", "MMd yy", "M d yy" },
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out bufferDate)
            ? bufferDate
            : new DateTime(1, 1, 1);
    }

With more than one line:

    private DateTime convertToDateFromString(string dateString)
    {
        var allowedFormats = new[] { "MMddyy", "MMd yy", "M d yy" };
        DateTime parsedDate;
        var couldParse = DateTime.TryParseExact(
            dateString,
            allowedFormats,
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out parsedDate);

        if (couldParse)
        {
            return parsedDate;
        }

        return new DateTime(1, 1, 1); // or throw an exception
    }


Similarly to a feature in most UNIX shells, Python has a globbing module, called glob.

It even supports the extended globbing (using ** to recursively descend into sub-folders) since Python 3.5, which you can use like this:

import os
from glob import glob

if __name__ == "__main__":
    dir = os.path.expanduser('~/Documents/MyLibrary/')
    books = glob(os.path.join(dir, "**/*.pdf"), recursive=True)
    print(books)

Here I also used the os.path module to correctly join the paths and expand the ~ symbol to the users home directory.

Alternatively, you could use the pathlib.Path object (introduced in Python 3.4), which also supports globbing:

from pathlib import Path

if __name__ == "__main__":
    dir = Path('~/Documents/MyLibrary/').expanduser()
    books = list(dir.glob('**/*.pdf'))
    print(books)

Note the list call, which is necessary, because the Path.glob method returns a generator (in contrast to glob.glob, which returns a list).


logic/presentation

You are mixing presentation and business logic. Both when signalling the AI won, as with the board.
Do you want to look through your whole code if you decide that "_" s a better representation for clear sea than "O", or you want it in another colour than white?

Tile

As far as I remember correctly, a tile on a battleships board has a few states: (clear sea, vessel, shot but no hit, hit vessel), where clear sea and vessel have the same representation to the opponent. So instead of using a string to represent this state, better would be to use an enum

from enum import Enum

class Tile(Enum):
    CLEAR = "CLEAR"
    VESSEL = "VESSEL"
    SHOT = "SHOT"
    HIT = "HIT"

Board

I assume your board at this moment is just a list of lists of strings. It is worth it to make a slightly smarter board

class Board:
    def __init__(self, width=10, height=10):
        self.width = width
        self.height = height
        self._board = [[Tile.CLEAR] * width for _ in range(height)]

is used to create an empty board

By overloading __getitem__ and __setitem__, you can make accessing the board a lot more intuitive:

def _exists(self, x, y):
    return 0 < x <= self.height and 0 < y <= self.width

def __getitem__(self, coord):
    x, y = coord
    if not self._exists(x, y):
        raise IndexError
    return self._board[x-1][y-1]

def __setitem__(self, coord, state):
    x, y = coord
    if not self._exists(x, y):
        raise IndexError
    self._board[x-1][y-1] = state

now you can do stuff like

b = Board()
b[2, 3]

Tile.Clear

b[2, 3] = Tile.Vessel
b[2, 3]

Tile.Vessel

This way, you don't bother the user directly with the 0-indexed list of lists in a 1-indexed environment. You can even work with row names A to J if you want with only a slight adaptation to those 2 methods.

Then you can add a ship like this:

def add_ship(self, length, x, y, orientation='horizontal'):
    directions = {
        'horizontal': (1, 0),
        'vertical': (0, 1),
    }
    dx, dy = directions[orientation]
    coordinates = [
        (x + i * dx, y + i *dy)
        for i in range(length)
    ]
    try:
        if any(self[x, y] != Tile.CLEAR for x, y in coordinates):
            raise ValueError("No room for this ship")
    except IndexError: # over the edge
        raise ValueError("No room for this ship")
    for x, y in coordinates:
        self._board[x, y] = Tile.VESSEL

In your implementation of the AI, after a hit, you have the AI check all the neighbours. This can be simplified by implementing a neighbours function on the Board

def already_shot(self, x, y):
    return self[x, y] in {Tile.SHOT, Tile.HIT}

def neighbours(self, x, y):
    coordinates = ((x-1, y), (x+1, y), (x, y-1), (x, y+1))
    for x, y in coordinates:
        try:
            yield (x, y), self.already_shot(x, y)
        except IndexError:
            pass

Same goes for the actual shooting itself:

def shoot(self, x, y):
    if self.already_shot(x, y):
        raise ValueError("Already targeted this square")

    if self[x, y] == Tile.VESSEL:
        self[x, y] = Tile.HIT
        return True
    self[x, y] = Tile.SHOT
    return False

You will need to implement a method to check whether all ships are sunk to determine whether someone has won. This method belongs to the Board, instead of on the AI method

Testing

using a class like this to keep track of the state of the board allows you to test parts of your program piece-meal. You can write a test suite so test the placing of the ships, the shooting, etc.

Turns

Where do turns show up in this? As far as I understand this, the AI keeps shooting as long as it can hit. I would expect the AI to be implemented as a class, which remembers what it has already shot etcetera, and which gets queried for a coordinate to aim at by the Game

Random shooting

If the minimum length of a ship is 2, you only need to target half of the field in while randomly looking for a ship, so only those where (x + y) % 2 is either 1 or 0, depending on where you start

AI class

This is a first shot at it. The _last_hit can use some improvement, and using a collections.deque or even a set here seems more logical than using a single value. But it shows how different methods can be used for defined beahviour

class AI:
    def __init__(self, opponent_board):
        self._board = opponent_board
        self._last_hit = None

    def random_shot(self):
        while True:
            x = random.randint(1, self._board.height)
            y = random.randint(1, self._board.width)
            if (x + y) % 2 == 0:
                continue
            try:
                hit = self._board.shoot(x, y)
                self.mark_hit(x, y, hit)
                return hit
            except ValueError:
                continue

    def mark_hit(self, x, y, hit):
        if hit:
            self._last_hit = x, y
        else:
            self._last_hit = None

    def next_turn(self):
        if self._last_hit is None:
            return self.random_shot()
        x, y = self._last_hit
        if self._board[x, y] == Tile.HIT:
            for x_, y_ in self._board.neighbours(x, y):
                try:
                    hit = self._board.shoot(x, y)
                    self.mark_hit(x, y, hit)
                    return hit
                except ValueError:
                    pass
            self._last_hit = None

        # No adjacent tiles to aim at if this got through here
        return self.random_shot()


The original index is never used and can currently be removed from both url and filter.

Your use of temporary variables is actually making the code less easy to read.

Replace the length indexes which are just a temporary values to check for validity.  I call this pathCount in the code below.
Replace parameters and the merging that you do with just continually adding to the array.  Adding to the array should overwrite any existing values equivalently to the array_merge operation.

I would also change the name of $key to something else as it confuses me with it being an array key. (I would call it $component or something similar).  I didn't make this change in the code below.

Edit:

In fact further to this $url and $filter are also temporary variables hurting your readability.  They could be replaced at the appropriate points with:

 $urlPath = explode('/', parse_url($url, PHP_URL_PATH);
 $filterPath = explode('/', $filter);

The code then becomes (not tested):

function ay_dispatcher($url, $routes)
{
   $urlPath = explode('/', parse_url($url, PHP_URL_PATH));

   foreach($routes as $filter => $data)
   {
      $filterPath = explode('/', $filter);

      if (count($filterPath) !== $count($urlPath))
      {
          continue;
      }

      if(!array_key_exists('parameters', $data))
      {
          $data['parameters'] = array();
      }

      foreach($filterPath as $i => $key)
      {
          if(strpos($key, ':') === 0)
          {
              $data['parameters'][substr($key, 1)] = $urlPath[$i];
          }
          // this filter is irrelevent
          else if($key !== $urlPath[$i])
          {
              continue 2;
          }
      }

      return $data;
   }

   return FALSE;
}

I am not sure that your logic for counting the filter path should just be a count?  Perhaps you need a function for that as parameters used in the filter would effect the count?


Readability:

you should have 2 newlines after each function definition
you should use augumented assignments where possible
you should define each method in a logical order (e.g: if you're calling a function inside another function, the later should be defined first). That's rather a personal preference because you can't do this everytime.
you should have a space around operators and delimiters
you should make your print() statements more compact
variable names should be snake_cased. The same goes for method names.
at the beginning of each function you should define a docstring

Now, let's dig into each function:

in def statistics() you should use format() and join those two prints into a single one:

def statistics(wins, times_to_run):
    """Print the statistics"""
    print("The computer won {} times"
          "This means the computer won {} % of the time".format(wins, (wins / times_to_run) * 100))

as mentioned above:

def setup_doors(always_change_choice):
    """Set up the winning door"""
    winning_door = random.randint(1, 3)
    computer_guess = random.randint(1, 3)

    print("The winning door is {}.\n"
          "The computer guessed door number {}".format(winning_door, computer_guess))

    return play_game(winning_door, computer_guess, always_change_choice)

in def run(change_choice, times_to_run) you should avoid that multiple condition by using the lower function. You can also use the enumerate() to get rid off that variable definition, and replace i by _ as you don't use it:

def run(change_choice, times_to_run):
    """Some description here"""
    for wins, _ in enumerate(range(times_to_run)):
        if change_choice.lower() == 'y':
            wins += setup_doors(True)
        else:
            wins += setup_doors(False)

    # Display amount of times won/percentage of games won
    statistics(wins, times_to_run)

in def setup() I'd just join the print statements:

def setup():
    """Basic greeting/explaining what to do."""
    print("\n\n"
          "There are 3 doors. One is a winner. The computer \n"
          "will try guess the right one. After the first \n"
          "guess, one door is shown to be a loser. The computer \n"
          "can then change it's choice to the remaining door.\n")

    # Display choices and get input
    change_choice = input("Should the computer always change it's choice? y/n\n:> ")
    runs = int(input("How many times should this run?\n:> "))
    run(change_choice, runs)

// To be continued. I have to leave the office.


The solution looks good, my suggestions:

Generators: the function itertools.accumulate returns a generator which doesn't create the whole list in memory, but calling list on it does create the actual list in memory. This is probably why you get the runtime error. Changing Operations from:
def Operations(size, Array):

    values = [0] * (size+2)
    for a,b,k in Array:
        values[a] += k
        values[b+1] -= k

    values = list(accumulate(values))

    Result = max(values)
    return Result

To:
def Operations(size, Array):
    values = [0] * (size + 2)
    for a, b, k in Array:
        values[a] += k
        values[b + 1] -= k
    return max(accumulate(values))

solves the problem and all tests pass.
PEP 8: function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names. More info. The function name is probably given by HackerRank, but the variable names Array and Result should be lowercase.

FYI, this is my old review on the same problem.


Split string at index field length or just before that if there is white space

Your indentation is a bit off here, with the true case of the if being indented one extra level. The else case is missing its brackets, which is probably the cause of confusion.

    var firstRight = firstLine.substring(13);
    if(firstRight.indexOf(' ')>-1)
        {
            //If There is white space, break the line at it
           instr = firstLeft+firstRight.substr(0,firstRight.indexOf(' '))+" \n"+firstRight.substr(firstRight.indexOf(' ')+1);
        }
    else
        //else just split the string, according to the field size
        instr = instr.substring(0,fieldSize)+"\n "+instr.substring(fieldSize);
    }

Aside from that, you call firstRight.indexOf(' ') three times, and you'd be better off placing this in a separate variable.


Faster algorithm to tailor given mathematical expression

To start, let's fix the PEP8 style errors using any PEP8 checker:

counts = 0
ans = 0
while(ans == 0):
    s = 0
    for i in range(counts, len(arr)):
        s += int(arr[i]/(i+1-counts))
        if(s > M):
            break
    if((i+1) == len(arr) and s <= M):
        print(counts)
        ans = 1
    counts += 1

The parentheses around the conditions are also not usual Python style:

counts = 0
ans = 0
while ans == 0:
    s = 0
    for i in range(counts, len(arr)):
        s += int(arr[i]/(i+1-counts))
        if s > M:
            break
    if (i+1) == len(arr) and s <= M:
        print(counts)
        ans = 1
    counts += 1

The inner loop uses break; there's no reason that the outer loop can't also, and that would simplify things slightly:

counts = 0
while True:
    s = 0
    for i in range(counts, len(arr)):
        s += int(arr[i]/(i+1-counts))
        if s > M:
            break
    if (i+1) == len(arr) and s <= M:
        print(counts)
        break
    counts += 1

When we get to the line

    if (i+1) == len(arr) and s <= M:

the first part of the condition can only fail because we called break in the inner loop, and in that case the second part of the condition also fails, so we can simplify that line to

    if s <= M:

Python has integer division: it's just that you need to use // instead of /. So

        s += int(arr[i]/(i+1-counts))

can be changed to

        s += arr[i] // (i+1-counts)

for readability.

It would be more Pythonic to operate on a slice rather than a range of indices. I.e. instead of

    for i in range(counts, len(arr)):
        s += arr[i] // (i+1-counts)

we would have

    for i, z_i in enumerate(arr[counts:]):
        s += z_i // (i+1)

The outer loop, on the other hand, could perfectly well be a range: it starts at 0 and is incremented once each time round the loop.

for counts in range(len(arr)+1):

Finally, there's the question of names. arr isn't great, but in context it passes. M comes from the problem statement. counts is, in my opinion, not at all helpful. I would call it offset, start, or something similar. And s is really partial_sum or weighted_sum.

This gives us tidied code:

for offset in range(len(arr)+1):
    partial_sum = 0
    for i, z_i in enumerate(arr[offset:]):
        partial_sum += z_i // (i+1)
        if partial_sum > M:
            break
    if partial_sum <= M:
        print(offset)
        break

As for speed: flooring discards information, so it's not easy to calculate the partial sum for a given offset any faster by using information from other offsets. Moreover, you can't use binary chop or some similar search because the partial sum is not monotonic in the offset: consider input array

[1000, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1000]

So I don't think there's much you can do to speed this up.


First of all you are not verifying the input of your program. You also don't need the strings stringFirstNumber  stringSecondNumber you can just put this all into a method that will check if the input is in correct format and also return the value something like this :

    private static double SetNumber(string outputText)
    {
        double parse;
        Console.Write(outputText);
        string tempInput = Console.ReadLine();
        while (!double.TryParse(tempInput, out parse))
        {
            Console.WriteLine("Incorrect input !");
            Console.Write(outputText);
            tempInput = Console.ReadLine();
        }
        return double.Parse(tempInput);
    }

and use it like this :

        double firstNumber = SetNumber("Type you first number : ");
        double secondNumber = SetNumber("Type you second number: ");

Now, about the operations.. I'm not sure if you wanted the sign % to work as percentage because if that's the case it wont. This is called modulus you can read more about it here https://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx if you want to have percentages you must implement this yourself. Anyway I would recommend creating an array of strings that holds all your currently available operations and store them there something like this :

private static readonly string[] operations = { "+", "-", "*", "/", "^", "%" };

Note that we are creating this variable outside of the static void Main(). Here we are seeing a few modifiers which might be new to you so let me quickly go over them.

private means we are keeping this variable only in our current class (Program)
static means we are having just 1 instance of this variable.
readonly means we wont modify those variables it's similar to const but it gives us a little bit more flexibility of where we can declare the value of the variable.

If the modifiers confuse you just remove them :

static string[] operations = { "+", "-", "*", "/", "^", "%" };

You need the static one since we are using this variable in static methods.

Let's move on. Once we have our operations declared in a string array we can easily check if the user is entering a correct input by creating the following function :

    private static bool IsValidOperation(string input)
    {
        return operations.Contains(input);
    }

Well we have the checker method which uses LINQ.Contains() this extension checks if a specific collection contains a specific value. Now we just need a method that will return a string value to our stringOperation

    private static string SetOperation(string outputText)
    {
        Console.Write(outputText);
        string tempInput = Console.ReadLine();
        while (!IsValidOperation(tempInput))
        {
            Console.WriteLine("Incorrect input !");
            Console.Write(outputText);
            tempInput = Console.ReadLine();
        }
        return tempInput;
    }

and use like this

string stringOperation =
          SetOperation(
               "Enter the operation + (addition), - (soustraction), * (multiplication), / (division), ^ (exposant) or % (reste) :");

Now notice that we are using only string's. I removed the integer idea that you had initially. You can still implement it pretty easily working around with the indexes of the string array, but I don't this is necessary. Also one thing to mention is that we are again taking a parameter in our method SetOperation well we could've avoided that since we have just 1 operation to be entered so we could've just do

Console.Write("Enter the operation + (addition), - (soustraction), * (multiplication), / (division), ^ (exposant) or % (reste) :");

Instead of Console.Write(outputText);. But I used the same parameters in the previous method too so it's good to keep some consistency if you are still learning. We are almost done now all that's left is the big mess with if/else if statements and a switch case too .. So as I said earlier using integer and string is useless so I went just for a string. Combining both the switch case and the if/else if statements into this :

        switch (stringOperation)
        {
            case "+":
            case "addition":
                result = firstNumber + secondNumber;
                break;
            case "-":
            case "soustraction":
                result = firstNumber - secondNumber;
                break;
            case "*":
            case "multiplication":
                result = firstNumber*secondNumber;
                break;
            case "/":
            case "division":
                result = firstNumber/secondNumber;
                break;
            case "^":
            case "exposant":
                result = Math.Pow(firstNumber, secondNumber);
                break;
            case "%":
            case "reste":
                result = firstNumber%secondNumber;
                break;
        }

I prefer the switch case version here because it's more readable but you can go with if statements too

        if (stringOperation == "+" || stringOperation == "addition")
        {
            result = firstNumber + secondNumber;
        }
        else if (stringOperation == "-" || stringOperation == "soustraction")
        {
            result = firstNumber - secondNumber;
        }
        else if (stringOperation == "*" || stringOperation == "multiplication")
        {
            result = firstNumber*secondNumber;
        }
        else if (stringOperation == "/" || stringOperation == "division")
        {
            result = firstNumber/secondNumber;
        }
        else if (stringOperation == "^" || stringOperation == "exposant")
        {
            result = Math.Pow(firstNumber, secondNumber);
        }
        else if (stringOperation == "%" || stringOperation == "reste")
        {
            result = firstNumber%secondNumber;
        }

Notice that we don't have else/default at the end in case of wrong input, because we already made sure the nasty user wont be able to proceed unless he sticks to our rules.

And lastly I edited this line

Console.WriteLine("\nResult of " + firstNumber + " " + stringOperation + " " + secondNumber + " = " + result + ".");

into a formated string which also looks a lot more readable :

Console.WriteLine("Result of {0} {1} {2} = {3}", firstNumber, stringOperation, secondNumber, result);

Here's the full code if you got confused where to put something :

    private static readonly string[] operations = { "+", "-", "*", "/", "^", "%" };
    static void Main(string[] args)
    {
        double result = 0;
        double firstNumber = SetNumber("Type you first number : ");
        double secondNumber = SetNumber("Type you second number: ");

        string stringOperation =
            SetOperation(
                "Enter the operation + (addition), - (soustraction), * (multiplication), / (division), ^ (exposant) or % (reste) :");

        switch (stringOperation)
        {
            case "+":
            case "addition":
                result = firstNumber + secondNumber;
                break;
            case "-":
            case "soustraction":
                result = firstNumber - secondNumber;
                break;
            case "*":
            case "multiplication":
                result = firstNumber*secondNumber;
                break;
            case "/":
            case "division":
                result = firstNumber/secondNumber;
                break;
            case "^":
            case "exposant":
                result = Math.Pow(firstNumber, secondNumber);
                break;
            case "%":
            case "reste":
                result = firstNumber%secondNumber;
                break;
        }
        Console.WriteLine("Result of {0} {1} {2} = {3}", firstNumber, stringOperation, secondNumber, result);
        Console.ReadKey();
    }

    private static double SetNumber(string outputText)
    {
        double parse;
        Console.Write(outputText);
        string tempInput = Console.ReadLine();
        while (!double.TryParse(tempInput, out parse))
        {
            Console.WriteLine("Incorrect input !");
            Console.Write(outputText);
            tempInput = Console.ReadLine();
        }
        return double.Parse(tempInput);
    }

    private static bool IsValidOperation(string input)
    {
        return operations.Contains(input);
    }

    private static string SetOperation(string outputText)
    {
        Console.Write(outputText);
        string tempInput = Console.ReadLine();
        while (!IsValidOperation(tempInput))
        {
            Console.WriteLine("Incorrect input !");
            Console.Write(outputText);
            tempInput = Console.ReadLine();
        }
        return tempInput;
    }


REST Web Api unit test endpoint validity with NUnit and Moq

I think you are confused about what a mock is actually supposed to be used for.  A mock is to create a fake object to pass into a parameter, and is very useful when testing systems that use dependency injection exclusively.

Take this for example:

public interface IFoo
{
     string SomeMethod(IBar bar);
}

public interfact IBar
{
    int CalculateSomething();
}

public class Foo : IFoo
{
     public string SomeMethod(IBar bar)
     {
         if (bar.CalculateSomething() > 10)
         {
              // insert more code

              return "Completed";
         }

         return string.Empty;
     }
 }

One of your tests is to ensure the // insert more code section works.  To get into that code you need the IBar.CalculateSomething() to return a value > 10.  You also don't want to create an instance of the Bar class, because then you are not testing one unit of code. This is where mocking comes into play.  The way to make sure you hit the code is to pass a mock into the method, that is set up to pass the if statement

[Test]
public void EnsureThatInserMoreCodeWorks()
{
    var bar = Mock.Create<IBar>();
    bar.SetUp(b => b.CalculateSomething()).Returns(15);

    var sut = new Foo();

    var result = sut.SomeMethod(bar.Object);

    Assert.That(result, Is.EqualTo("Completed");
}

This is really simple, and I hope there is more to the // insert more code section to test, but this gives an easy to follow example of using mocks.

To make your test pass, you would simply have to pass in an invalid uri string.  No Mock needed.


Dodging your question for a quick comment:

Why don't you combine these

                      if(intLoop ==0){
                          mp1=MediaPlayer.create(MainClass.this, R.raw.item1);
                          mp1.start();
                          v.setPressed(true);
                          return true;
                      }
                      if(intLoop == 1){
                          mp1=MediaPlayer.create(MainClass.this, R.raw.item1);
                          mp1.start();
                          mp1.setLooping(true);
                          v.setPressed(true);
                          return true;
                      }

into this?

                      mp1=MediaPlayer.create(MainClass.this, R.raw.item1);
                      mp1.start();
                      if(intLoop == 1){
                          mp1.setLooping(true);
                      }
                      v.setPressed(true);
                      return true;

And, as Vogel612 mentions, is there any reason intLoop is not a boolean?

I think that if the rest of your code looks like that, simply combining the functionality like this might fix the idea that the listener is doing a lot.


Generating a table of differences between two dictionaries

You should separate the logic from your representation and first collect those differences in a separate list. Also, what are the types of your dictionaries? All those ToString()s make it really noisy and are likely not necessary. Furthermore, use a foreach loop to iterate through your key list, this will also automatically get rid of all those keyList[i] accesses. And finally, instead of appending to a string directly, use a StringBuilder to make it more efficient:

// Use a separate type to collect your diffs
class DiffEntry
{
    public string ColumnName { get; set; }
    public string OldValue { get; set; }
    public string NewValue { get; set; }
}

// collect all diffs
List<DiffEntry> diffs = new List<DiffEntry>();
foreach (string key in keyList)
{
    if (oldDic.ContainsKey(key))
    {
        if (newDic[key] != oldDic[key])
        {
            diffs.Add(new DiffEntry()
            {
                ColumnName = colNames[key],
                OldValue = oldDic[key],
                newValue = newDic[key]
            });
        }
    }
    else
    {
        diffs.Add(new DiffEntry()
        {
            ColumnName = newDic,
            NewValue = newDic[key]
        });
    }
}

// generate the actual table output
StringBuilder tableContent = new StringBuilder();
foreach (DiffEntry diff in diffs)
{
    tableContent.Append("
");
    tableContent.Append("");
    tableContent.Append(diff.ColumnName);
    tableContent.Append("	");
    tableContent.Append(diff.OldValue);
    tableContent.Append("	");
    tableContent.Append(diff.NewValue);
    tableContent.Append("
");
}
table += tableContent.ToString();


Misspellings
There are several misspelled words you should correct (see line comments):
  -- current weak -- should be 'week'
  declare @CurrentWeakStart date = dateadd(day, 1-datepart(dw, @Today), CONVERT(date, @Today)) -- should be '@CurrentWeekStart'
  declare @CurrentWeakEnd date = dateadd(day, 7-datepart(dw,  @Today), CONVERT(date,  @Today)) --should be '@CurrentWeekEnd'
  -- last week
  declare @LastWeakStart date = DATEADD(dd, DATEPART(DW,@Today)*-1-6, @Today) -- should be '@LastWeekStart'
  declare @LastWeakEnd date =DATEADD(dd, DATEPART(DW,@Today)*-1, @Today) -- should be '@LastWeekEnd'

Magic numbers
You use ints 1,2,3,4 as codes but no indication of what they mean. I'd suggest to take a moment to declare them and give them meaningful name:
declare @StartAndEndOfCurrentWeek  int = 1;
declare @StartAndEndOfLastWeek     int = 2;
declare @StartAndEndOfCurrentMonth int = 3;
declare @StartAndEndOfLastMonth    int = 4;

Then this becomes more clear:
  insert into @Result
  select CASE @Type
           WHEN @StartAndEndOfCurrentWeek  THEN @CurrentWeekStart
           WHEN @StartAndEndOfLastWeek     THEN @LastWeekStart
           WHEN @StartAndEndOfCurrentMonth THEN @CurrentMonthStart
           WHEN @StartAndEndOfLastMonth    THEN @LastMonthStart
           ELSE NULL
         END
  ,      CASE @Type
           WHEN @StartAndEndOfCurrentWeek  THEN @CurrentWeekEnd
           WHEN @StartAndEndOfLastWeek     THEN @LastWeekEnd
           WHEN @StartAndEndOfCurrentMonth THEN @CurrentMonthEnd
           WHEN @StartAndEndOfLastMonth    THEN @LastMonthEnd
           ELSE NULL
         END
  RETURN

Capitalization
You should try to stick to one style of capitalization throughout for keywords. It makes it easier to read and less distracting. This is especially true of something that could have some other code mixed it, for example this one could look like there is some VBA:

DateAdd( day, 1 - Day( @Today ), @Today )

What's the difference between day and Day? Well of course there isn't in SQL, but just the fact that it's capitalized differently may throw someone off that is less used to SQL and more to programming where capitalization makes a difference.

Overall
I think in general this is a good idea and seems like a useful function to have around. Especially if you work with finance stuff a lot. I think it could reasonably be broken into two functions though, one for week and one for month. Picture something like:

udf_getRangeOfDatesInWeek
udf_getRangeOfDatesInMonth

Then you only need to supply them an int parameter and put that in your datediff() operation. 0 for current, -1 for last, 1 for next, etc. I think that would be much more flexible and useful!


Core Location - Practices for Supporting Common iOS Devices

Apple's LocateMe sample has been kept up to date and shows how to properly handle getting a fix with accuracy evalutation and timeout. It's quite an excellent sample so why not start there?

Devices without cellular won't have the benefit of cell triangulation but that's all abstracted anyway.


A background service that will wait for items to process without busy-waiting

I suggest SemaphoreSlim instead of AutoResetEvent here because it has asynchronous API and will not block the current thread, and it accepts CancellationToken. Task.Yield is good hack but it can be useless because await in case of not null SynchronizationContext will restore the context and WaitOne() can anyway block the current thread.
public class ExecutionBackgroundService : BackgroundService
{
    private readonly IJob _job;
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); // 1 is concurrency degree

    public ExecutionBackgroundService(IJob job)
    {
        _job = job;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            while (true)
            {
                await _semaphore.WaitAsync(stoppingToken);
                await _job.Process();
            }
        }
        catch (OperationCanceledException ex)
        { } // occurs when WaitAsync receives canceling callback from the Token, you may log it if needed.
    }

    /// <summary>
    /// Notifies the background service to resume processing.
    /// </summary>
    public void Resume()
    {
        lock (_semaphore)
        {
            if (_semaphore.CurrentCount == 0) // is it waiting now?
                _semaphore.Release();
        }
    }
}

This way is better because now you may cancel the Token without calling the Resume().
Btw it's a programming pattern - Producer/Consumer. The best way for moving forward is using the specially designed for this purpose almost brand-new classes - System.Threading.Channels. Refer to this link.


Welcome to Code Review. Your code looks to be following some good practices from python's style guide (PEP-8). However, as a programmer, you can perhaps improve the structure/performance.

No need to have separate variables for dataframes for each club. Group all the links together, and use a map for fetch everything.
The reverse function defines an unused variables to_reverse.
Split functionality to separate function, just like you have one to reverse names.
You do not need to iterate over range(len(some_iterable)) if the index is not needed at all.
Add type hinting, and some comments to functions to help understand what kind of values it might expect (and return), as well as, what it is doing.
Put everything inside an if __name__ == "__main__" clause.

Rewritten code:
from typing import Tuple
import requests
import pandas as pd
import xlsxwriter
from bs4 import BeautifulSoup

def reverse(name: str) -> str:
    """Reverse name from 'Last First' to 'First Last'."""
    return " ".join(reversed(name.split(" ")))

def fetch_page(url: str) -> str:
    """Send request to given url, and return the contents on success."""
    response = requests.get(url)
    if response.ok:
        return response.content

def get_club_information(club_page) -> Tuple:
    """Read all `tr` elements on page, and extract player information.

    Each row (`tr`) consists of 6 cells. We are skipping over 1st and last cell data."""
    soup = BeautifulSoup(club_page, features="lxml")
    rows = soup.findAll("tr")
    header, *content = [[cell.getText().strip() for cell in row][1:5] for row in rows]
    for row in content:
        row[0] = reverse(row[0])
    return header, content

def conversion_df(url):
    page = fetch_page(url)
    header, content = get_club_information(page)
    print(header, content)
    table = pd.DataFrame(data=content, columns=header)
    return table

LINKS = (
    "https://www.lnb.fr/fr/espa/equipe/espoirs-nanterre-61344.html",
    "https://www.lnb.fr/fr/espa/equipe/espoirs-monaco-61343.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulazac-61331.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulogne-levallois-61332.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-bourg-en-bresse-61333.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalon-saone-61334.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-cholet-61336.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalons-reims-61335.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-dijon-61337.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-gravelines-dunkerque-61338.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-mans-61339.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-portel-61340.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-orleans-61345.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-pau-lacq-orthez-61346.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-roanne-61347.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-strasbourg-61348.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-limoges-61341.html",
    "https://www.lnb.fr/fr/espoirs/equipe/espoirs-lyon-villeurbanne-61342.html",
)

def main():
    # Creating Excel Writer Object from Pandas
    writer = pd.ExcelWriter("liste_espoir.xlsx", engine="xlsxwriter")
    workbook = writer.book
    writer.sheets["Espoirs"] = workbook.add_worksheet("Espoirs")
    row_count = 0
    for club in map(conversion_df, LINKS):
        club.to_excel(writer, sheet_name="Espoirs", startrow=row_count, startcol=0)
        row_count += 20
    writer.save()

if __name__ == "__main__":
    main()

Additionally, you can use asyncio to fetch those pages in parallel, to reduce the runtime for your program.


Is it normal to have a base type for Entities and Value Objects?

Review

The following methods are candidates for properties. A property is expected to return fast, without too much calculations and internal flow. I'm assuming NHibernateUtil.GetClass provides a fast lookup.

public virtual bool IsTransient()
{
    return Id == 0;
}

public virtual Type GetRealType()
{
    return NHibernateUtil.GetClass(this);
}

public virtual bool IsTransient => Id == 0;
public virtual Type RealType => NHibernateUtil.GetClass(this);

When to use a base class

Since C# allows for single class inheritance, pick a base class that adds sufficient state / operations to the class. Providing base classes like EqualityBase, ComparableBase, DisposableBase, HashCodeBase are bad choices, since they don't provide meaningful context except for a very specific mitigation of boiler-plate code. Which class should Entity implement of the above? You would like to implement all of them, but you can't!
Is Entity provided by the OP a good choice for a base class? If the IsTransient() and GetRealType() methods weren't provided, I would argue against using a base class. You would end up with a class like above (EqualityBase, HashCodeBase mix). Both added methods allow for sufficient context to justify a base class.
Use the power of interface inheritance, because you can implement as many interfaces as you want, and composition, because you can contain and delegate operations to as many contained objects you desire.

Dilemma

Using a base class allows for DRY code. The repetitive boiler-plate code sits in the base class, while the entities are very clean POCO's. However, you force the entities to derive from this base class, limiting the inheritance options for such classes drastically.

Solution

To allow for flexibility in inheritance options for your entities, and mitigating most boiler-plate code, you could provide an interface, a base class and let your entities implement both. The special entities that require to inherit from a different base class, should do so, and implement the interface.

public interface IEntity
{
    long Id { get; }
    bool IsTransient { get; }
    Type RealType { get; }
}

public abstract class EntityBase : IEntity
{
    public virtual long Id { get; protected set; }
    public virtual bool IsTransient => Id == 0;
    public virtual Type RealType => NHibernateUtil.GetClass(this);

    // .. other code (equals, operator overloads, ..)
}

Most entities would implement both the base class and interface:

public class Employee : EntityBase
{
    public string Name { get; set; }
    public string FirstName { get; set; }
    public string BadgeId { get; set; }
}

Allowing for special cases:

public class DocumentElement : TreeNode<DocumentElement>, IEntity
{
    // .. DocumentElement  members
    // .. IEntity members
}

Other layers using the entities don't care about the base class, only the interface.

public interface IRepository<T> where T : IEntity
{
    T Get(int id);
    void Save(T entity);
}


Printing the power set of a given set of elements

The integer to string to integer representation of string to string conversion is very wasteful. You can just do bit shifts.

private static String getSubset(String inputSet, int mask) {
    StringBuffer subset = new StringBuffer();

    for (int i = 0; i < inputSet.length(); i++) {
        // Check if ith bit is set
        if ((mask & (1 << i)) != 0) {
            subset.append(inputSet.charAt(i));
        }
    }

    return subset.toString();
}

public static List<String> permuteSet(String inputSet) {
    List<String> powerSet = new ArrayList<String>();
    int n = inputSet.length(); // size for binary
    int powerSetLength = 1 << n; // you should check that n is small enough

    for (int i = 0; i < powerSetLength; i++) {
        powerSet.add(getSubset(inputSet, i));
    }

    return powerSet;
}

Demo


Rearrange an array in place such that the first and last halves are interleaved

The recursion results in \$O(n)\$ space complexity (each recursive invocation consumes some stack), so technically you did not fulfill the requirement of _not using extra space. Since it is a tail recursion, it can easy to eliminate. Unfortunately, Java doesn't do it, so you have to eliminate it manually. Fortunately, it is just a mechanical rewrite.
The time complexity is \$O(n^2)\$. There is not much to do with the current approach. There is however a linear solution: an element at index k goes to either 2k, if k < n/2, or 2k - n + 1 otherwise. Convince yourself that this permutation has no loops, and just follow a chain of indices.
The loop

for (int i = swapInd2 ; i > swapInd1; i--) {
    arr[i] = arr[i - 1];
}

shifts a range, and deserves to be a function on its own (shift_rangeperhaps).


Python 3: Finding common patterns in pairs of strings

You can simplify the two functions quite a bit. For find_raw_patterns you can use partition instead of manually splitting the strings up, and simplify the formation of the list.

def find_raw_patterns(s1, s2): # used recursively
    if s1 == '' or s2 == '':
        return [], []
    com = longest_common_substring(s1, s2)
    if len(com) < 2:
        return ([0, s1], [0, s2])
    s1_bef, _, s1_aft = s1.partition(com)
    s2_bef, _, s2_aft = s2.partition(com)
    before = find_raw_patterns(s1_bef, s2_bef)
    after = find_raw_patterns(s1_aft, s2_aft)
    return (before[0] + [1, com] + after[0],
            before[1] + [1, com] + after[1])

For find_common_patterns, you can use list indices to get the even and odd values rather than checking the type of each value, and use zip to get a list of pair tuples.

def find_common_patterns(s1, s2):
    (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern
    return (zip(ptr1[::2], ptr1[1::2]),
            zip(ptr2[::2], ptr2[1::2]))

But I think you can also combine the two functions with a minor adjustment to put the found values into paired tuples.

def find_common_patterns(s1, s2): # used recursively
    if s1 == '' or s2 == '':
        return [], []
    com = longest_common_substring(s1, s2)
    if len(com) < 2:
        return ([(0, s1)], [(0, s2)])
    s1_bef, _, s1_aft = s1.partition(com)
    s2_bef, _, s2_aft = s2.partition(com)
    before = find_common_patterns(s1_bef, s2_bef)
    after = find_common_patterns(s1_aft, s2_aft)
    return (before[0] + [(1, com)] + after[0],
            before[1] + [(1, com)] + after[1])


Partial page refresh Ajax call on button click

I would suggest to:

I would recommend to use camelCase naming style, so instead of ApprovalTable you could use approvalTable
you are using a function to define a handler for an event, the name is not very consistent with what this function does, you could rename it to enableRequestValidationHandler
It's often a good idea to cache selectors, if you plan to use them more than once, so instead of using directly $('#largeModal') you could use somewhere:

var largeModal = $('#largeModal');

then use it in the ajax response handler via variable success: function (result) {...

The reason to do that, is because jQuery dive in html everytime you ask him to find something in html

you already defined var selectedButton = $(this); but still use $(this) in your code, you could use instead the selectedButton variable. I usually call it: self

These lessons will help you to understand fast and easy how jquery works


Use of nested namespaces in 3D graphics engine library

I don't think there is anything inherently wrong with nested namespaces.

I also disagree that it is rare. It is just not exposed directly.

std::tr1
CompanyName::ProductName
CompanyName::ProductName::Details

But like all features they can be abused so use judiciously. But saying that I see nothing wrong with your namespace hierarchy. BUT the way you are implementing it is a very bad idea.

If I include the file "File.h" I expect everything included to be declared in the correct namespace. But the way you define it, it is now possible to include it in a way that puts the classes in the wrong namespace.

Each header file should be designed so that it can not be used incorrectly.


Preface

A lot of C++ programmers hate Java being translated to C++. The reason is not that either C++ or Java is bad, the reason is that they are very opposite in nature. Java doesn't make the programmer to worry about performance, safety and memory allocations. It does checks to ensure safety. C++ almost always offers more degree of control, thus providing opportunities to write more optimized code. Despite that, C++ has encapsulation as well, but it keeps it to the minimum required. It provides encapsulation only when it's free (e.g. compile time, or no overhead). It always tries to hold following:

  don't pay for what you don't use

Your code

There are several problems in your code.

You got very close to strong exception safety. Unfortunately, you've missed one step of the copy and swap idiom. Namely the swap, so even if the deletion throws nothing bad will happen to the data in the container. I recommend this answer to enrich knowledge about C++ exception safety.

Your container new[]s everything. So there is a problem: if T is not default constructible, it is not possible to use your container. Some people use term lazy construction, but I prefer the following wording: you should not construct on memory allocation, you should retrieve uninitialized buffer, and then construct when needed. To do so you will need to call operator new. Use only non array version, since array version has very limited use.

Container copies every element on adding. C++11 introduced template parameter packs. With the feature you can write following code:

template <typename T>
template <typename ... Args>
void ArrayList<T>::emplace(Args... args)
{
    if (allocatedSize == actualSize)
    {
        //handle buffer resizing
    }

    new (copy + actualSize) T(args...);
    std::swap(copy, arr);
    ++actualSize;
    delete[] copy;
}

It will handle any constructor that T might have. It will also issue compile time error if there is no matching constructor to input arguments. The new expression used is called placement new. It constructs an element in the pointed to location specified.

Your container grows linearly. Often this is not enough. It will resize buffer too many times which will incur great overhead. Usual implementations increase the size exponentially. VC++ uses growth factor of 2 (probably as many others). Despite that, the article mentions how to get optimal growth factor.

You don't overload operator[]. I know that the code is meant to be ArrayList, but honestly it is not C++ without operator overloading. On top of that, usually container manipulations are not checked in C++. Your remove operation just does nothing on getting out of bounds. Surprising. std::vector uses special at function to perform checks and throw.

C++ programmers use std::size_t defined in <cstddef> when referring to the size of the objects in memory. The type has specific semantic: it is big enough to index all the elements in the memory. It is unsigned, which will suggest that users shouldn't pass negative values to the add and remove.

What is missing

Aside from iterators, here is the list:

std::initalizer_list constructor
resize
reserve
range add (based on iterators)
range erase (based on iterators)
Non resizing add on position (add should be amortized constant)
Move constructor
Move assignment operator (with point 7 and your already written code, you will fully implement rule of 5).
Placement add (using placement new)
Moving add
iterator based remove, add, constructor.
Move elements on buffer resizing if move is noexcept or no copy constructor is provided.

The way it should be

C++ has standard std::vector templated container. It mirrors the concepts of the ArrayList (contigious buffer, resizing, index based access). On top of that, it uses everything C++ has to offer. I recommend you to think about this: "When in Rome, do what Romans do".


XSS Protection from Query Strings in Java

In addition to RotoRa's answer:

Instead of

    String[] pair = param.split("=");

you should call

    String[] pair = param.split("=", 2);

Otherwise you will trim base64-encoded data, which may happen in some applications, especially if the client forgets to properly encode the = characters.

Instead of a HashMap, use a LinkedHashMap, since that will keep the parameters in the same order as they appeared in the original URL. This makes the code easier to test (you do have unit tests, I hope) and more predictable in general.


Be consistent with stdlib.h declaration of atoi()

The standard declaration is int atoi(const char *str);. Your declaration should match (i.e., take a const char * instead of char *).

What happens if a NULL pointer is passed?

As written, you dereference ato without checking if it is NULL (0). That is a big no-no in C. At the very top of the function, you should check if it's 0 and return 0 if it is:

if (!ato) { return 0; }

Edit: Martin R points out that silently returning 0 when a NULL pointer is passed to your function, as I have suggested, is bad programming practice, because it hides the error. If there's a possibility of calling myatoi() with a NULL pointer, there's no way for the function to notify the caller of the error. Therefore, it's incumbent upon the caller to check before calling.

No need for separate variable definition and initialization

Do:

int res = 0;
int sign = 0;

Don't:

int res;
int sign;
res = 0;
sign = 1;

Don't reinvent the wheel

Your first loop that skips over whitespace could use the standard library function isspace():

Edit: spot the bug in my original code... :/

Buggy (oops): while (isspace(*ato++));
Correct:      while (isspace(*ato)) ato++;

The condition check in the second loop can use the stdlib function isdigit():

while (isdigit(*ato)) {
    ...
    ato++;
}

If your instructor or assignment instructions prevent you from using isspace() and isdigit(), why not go ahead and define them yourself? You already have the logic!*

* Except you have a minor bug in your check for space characters. You also need to check for vertical tab (\v).

Edit: Chux points out that calling isspace(*ato) and isdigit(*ato) when *ato < 0 invokes undefined behavior (UB). Specifically, the C11 standard, section 7.4, Character Handling, states,

  The header <ctype.h> declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.

The correct usage, then, of the isspace() and isdigit() functions in this code would be:

while (isspace(*(unsigned char *)ato)) { atoi++; }
//...
while (isdigit(*(unsigned char *)ato)) {
    //...
    ato++;
}

Chux also pointed out that your original code as written did not have this problem; you weren't invoking undefined behavior. Moral of the story: be careful of the advice you receive from strangers on the Internet...? =)

Other than the issues mentioned, you have a decent implementation!


Multiple indexes over an in memory collection for faster search

Using ToString() to compare expressions for equality might work in simple cases, but:

It requires you to always use the same parameter name, for example, it would consider x => x.Id and product => product.Id to be different expressions.
Expressions with different meaning can produce the same string, for example (int i) => (float)i and (int i) => (double)i both produce i => Convert(i). Because of this, it might make sense to ensure that the used expressions contain only property accesses and nothing else.

Instead you should compare Expressions properly.

It seems wasteful to me to rebuild all indexes after each change. If you change the collection often, consider changing only the relevant part of each index.

Fields that are set in the constructor and then never modified should be readonly.

IList<T> data

If you're on .Net 4.5, you could use IReadOnlyList<T> here.

if (_lookups.Count > 0)

This check is pretty much useless. It saves you from unnecessarily creating an empty dictionary, but doing that is very cheap, so I think shorter code should take the priority here.

You could replace the whole RebuildIndexes() method with a single ToDictionary():

_indexes = _lookups.ToDictionary(
    lookup => lookup.ToString(), lookup => _items.ToLookup(lookup.Compile()));

c(x).Equals(value)

This won't work correctly when c(x) returns null. You should probably use object.Equals(c(x), value) instead.


Django Model field naming convention for lookup tables

You could have an abstract base model to lock in how the lookup tables all should work:

class LookupModel(models.Model):
    name = models.CharField(max_length=64)
    sort = models.IntegerField()

    class Meta:
        abstract = True
        ordering = ['sort']

    def __unicode__(self):
        return self.name

.. ditto for a DRF serializer, you just swap out which model is being connected. When you do this you cannot go the "gender__gender=gender" route though. It's a matter of how lazy you are, really (as in laziness, impatience, hubris). One advantage is that you can have a single class in the admin if you use that:

class LookupAdmin(admin.ModelAdmin):
    list_display = ('name', sort')
    ...

admin.site.register(Gender, LookupAdmin)
admin.site.register(Location, LookupAdmin)
admin.site.register(Status, LookupAdmin)

As for naming conventions, if sort is chosen/changeable and an integer I would call it position. If a string, sortkey or something like that. If automatic: Django, when sorting on foreign key with order_with_respect_to, adds the invisible column "_order", so you could do that, and find a way to set the column automatically. Or, you could sort on the automatically added auto-incrementing primary keyid-field (which I admit I've never done). I don't like implicitness though so would have a manually added column and manually set "ordering". Fewer surprises that way, laziness again.

But, and here's why I write this in 2020, long after you are hopefully done with the project you needed input on: Django 3.0 can use enums in Field.choices. So, in your case, with just a single name-field and a sort you won't change, you could forego the lookup table and instead:

LifeStatus =  models.IntegerChoices(
    'LifeStatus',
    'ALIVE MISSING DEAD UNDEAD'
)

class Human(models.Model):
    status = models.IntegerField(choices=LifeStatus.choices)
    ..

You can then do things like:

# zombieapocalypse.py

if human_looking.status == LifeStatus.UNDEAD:
    run_away()

Which IMO is very readable. Typos would also be a syntax error, bonus!

(Unfortunately this doesn't fix my problem though, I'd like a lookup table that also works like an enum...)


The execution time will be dominated by I/O, since you are writing so many files.  The only suggestion I have that might change the I/O performance is to try the NIO API, namely Files.write().

There is another possible inefficiency if sampleSize is much smaller than the size of the collections.  In that case, shuffling the entire list would be overkill, and you might be better off writing your own function to perform sampling without replacement.  (That would basically be a Fisher-Yates Shuffle that terminates early.)

There are four similar copies of the code, which you might want to consolidate, especially if it is not important to preserve the behaviour of your System.out.println(i) progress indicator.

My first observation is that the pos and neg lists can be treated independently.  My second observation is that you could simplify the loop if you interleave the output of the test and train cases.

I think that this code would make it more obvious that the number of files created is sampleSize, for each of the lists neg and pos.

private static void writeSampleFiles(List<String> list, String name, int sampleSize) throws IOException {
    Collections.shuffle(list);
    for (int i = 0; i < sampleSize; i++) {
        Path path = Paths.get(i & 1 == 0 ? "train" : "test",
                              name,
                              (i >> 1) + ".txt");
        Files.write(path, list.get(i).getBytes());
    }
}

// elsewhere...
writeSampleFiles(neg, "neg", sampleSize);
writeSampleFiles(pos, "pos", sampleSize);

Note that this isn't exactly identical to your original code.  The shuffled entries are extracted in a different order, which could be an issue if you are concerned about "dealing from the top of the deck".  If the execution aborts prematurely due to an IOException, then the difference in the processing order would be visible to the user.


Simple as that:

/<script>[^<]*?googletagmanager\.com.*?<\/script>/s

What's killing performance for you, is most likely the backtracking followed by a look-ahead on the first padding. Using a character class instead of a look-ahead, and making it non-greedy should solve that issue.

The /s modifier allows you to use . instead of explicit [\s\S].


Correct way to implement a Singleton field

IMHO, it's ok to use static methods if the object (HTTPHelper in your case) doesn't store data and can't have multiple states.

A little suggestion:

    private static final OkHttpClient client;
    static {
        client = new OkHttpClient();
        client.setConnectTimeout(TIMEOUT, TimeUnit.SECONDS);
    }

if you initailize your client in this way, you won't need getClient method at all!

Actually, what concerns me in your code is whether it must be used by multiple threads or not. What will happen of one thread call getHTML while client is used in another thread pending from answer?

Addition:
what does

private HttpHelper() { }

serve for? Do you want to forbid to create an instance of your class? If so, your class may be extended and instantiated, or your constructor may be accessed via reflection. Try this:

private HttpHelper() {
    throw new NonInstantiableException()
}


Mapping a CSV with UTF-8 encoding to JSON in Python

What you have done follows a coding anti-pattern (a coding pattern that is to be avoided). It's ok, you are learning. This anti-pattern is called loop-switch sequence. The essence of this antipattern is that a clear set of steps is done with a loop and a switch statement (or a series of if and else).

In your case, the steps are not even that different to require a distinct statement each. What you essentially want is for the first value in a row to be assigned to the first key, the second value to the second key etc.

You do not need the function mappingThoseValues, nor the variable a. Here's how you can do your job in Python. First, have the names of your dictionary keys in a list.

key_names = ['Ticket', 'Dominio', 'Tipo', 'Ruta', 'Version', 'Componente', 'Comentario']

Then you can read your csv row values and fill in the dictionary in one simple loop.

extracted_info = []
with open(runbookname) as csvfile:
    spamreader = csv.reader(csvfile, delimiter='\t')
    for row in spamreader:
        d =  {}
        for key, value in zip(key_names, row):
            d[key] = value.decode('iso-8859-1').encode('utf8')
        extracted_info.append(d)

The important thing here is to understand the function zip and how we can use it in loops. There is plenty of educational material you can find online (example). A few other things to notice in the new code:

No need for the global variable mydic (in general, you should
avoid using global variables to exchange data between methods).
No need to create copies of your dictionary to append them in the
list, because each time in the loop we create a new dictionary (in
your code you did need to copy mydic because it was a global variable)
No need for the call to close(), because you are using the with clause (close
will be automatically called)

Update based on comments: You can make the code even more succinct and pythonic by employing a dictionary comprehension. This might seem strange/difficult at your experience stage. Don't worry, you can come back to it later. The important bit is to understand the previous points I raised, but I'll include the dictionary comprehension here for reference.

List and dictionary comprehensions is a pythonic way to replace (some) loops by making the loop expression more succinct and also faster. Here's how it would work for your code:

extracted_info = []
with open(runbookname) as csvfile:
    spamreader = csv.reader(csvfile, delimiter='\t')
    for row in spamreader:
        d =  {key: value.decode('iso-8859-1').encode('utf8') for (key, value) in zip(key_names, row) }
        extracted_info.append(d)

Worth mentioning that there is also a csv.DictReader class that can directly read a csv file into a directory. You can provide the names of the keys in one of the argument called fieldnames, or if you do not define any fieldnames it will use the first row of the file as names for the fields/keys. However, my preference is to use this in very common csv format (like excel), as I have found it somewhat cumbersome to define delimiters. You will still need to loop through every row of this reader to get the dictionaries, and you would still need to do any manipulations you want (like your decoding and encoding) as everything is stored in strings. So the regular reader works equally well, and produces equally succinct code.

Finally, let me comment on decoding and encoding Unicode characters. You need of course to decode the bytes you read from your file. When you decode them they become Unicode strings (in Python 2.x they are called "Unicode strings", in Python 3.x they are called "strings", they are the same thing). Instead of immediately encoding these unicode strings to another byte format (as you do) you could simply store these unicode strings to your dictionary. You encode to another byte format only when you need to write it to another file or make it a stream of bytes in any way. In fact, this is the recommended thing to do. Quoting from the linked page:

  The most important tip is: Software should only work with Unicode
  strings internally, decoding the input data as soon as possible and
  encoding the output only at the end.

I hope this helps.


C-Style unsigned char parsing and manipulation

Your problem is here:
buf->str[ buflen ] = '\0';

You allocate a buffer (str) of buflen bytes.
This means you can index it (str) from 0 -> (buflen-1).
Thus the accesses above is writing one past the end of the buffer and corrupting memory.
You probably meant:
buf->str[ len ] = '\0';

Since you are using C++ compiler. You should use std::vector<viByte> or std::basic_string<viByte>.
This kind of bug is easy to introduce and unless you have good unit test hard to find. So why not use a class that already is unit test and has had 10 years of millions of people lookign at it to make sure it works correctly.
Other comments:
Broken and illegal.
    buf->str = ( viByte* ) 0x1;

Wrong. buf->str is a pointer and it was expecting a unsigned integer (they are not the same). Use %p to print a pointer value.
    printf(" Before viByteBuf_Prepend => %uc ", buf->str);

Broken and illegal (0x2 is not yours)
    viByteBuf_Prepend( buf, 3, ( viByte* ) 0x2 );

No check for NULL. (calloc can return NULL when it fails).
    viByteBuf* buf = ( viByteBuf* ) calloc( sizeof( viByteBuf ), 1 );

Again no check for NULL.
    buf->str = ( viByte* ) calloc( sizeof( viByte ), buflen );

Is this really what you want? Buflen includes the portion with the '\0' character. You need to be consistent and decide if len does or does not include the null.
    buf->len = buflen;

As pointed out above (write past the end of the buffer).
    buf->str[ buflen ] = '\0';

How do you handle failure?
As pointed out above calloc can fail. How do you propagate that failure to the caller.
    viByteBuf* tmp = viByteBuf_New( totallen );

Why are you nulling the whole array. You are just about to write over it.
Seems like a complete waste of time.
    memset( tmp->str, 0, tmp->len );

Looks like this loop is trying to reverse the string in place.
Which will fail as by the time you overwrite the first half the second half is a copy of the back half. Luckily it completely fails because you don't actually use the index variable.
    for( i = 0; i < buf->len; ++i )
    {

       index = ( buf->len - i ) - 1;

       *strpos = buf->str[ 0 ];
       ++strpos;
    }

Now that you have failed to reverse it. You then overwrite it again with 0 (presumably to cover up the failure to reverse it).
    memset( buf->str, 0, buf->len );

Illegal parameter to printf() again.
    printf( "%uc\n", buf->str );

More copying for unknow reason.
    memcpy( buf->str, tmp->str, tmp->len );

This code is so full of bugs. It has no write to work.


They're not being too nit-picky. DataTask's completion handler will return nil for data when it couldn't get the data, like when the network is offline.  Force unwrapping 'data' means you deliberately crash the application when that happens.  That would be bad.
"separate the business logic from the view controller": They expect you to make a data type to parse the JSON into, perhaps like this:
struct Item: Decodable {
    let id: Int
    let listId: Int
    let name: String?
}


Export running data from Garmin API to CSV

Interesting script! Here are a few comments to make it better :)

Documentation

Documenting how to find the required values is a very nice touch, exactly the kind of things that helps a new user or maybe yourself in a few months. However, other parts of the documentation can be improved. Indeed, there is a Convention for Python docstrings. It is definitly worth a read. Among other things, your script documentation should be in """triple-quoted string""". Also, you should try to document your functions : purpose and when relevant parameters and return value (I'll come back to this).

Style

Not much to say about the style, your code looks good and seems to follow PEP 8. A few lines seem "too" long, maybe having the URLs as global constant would make things easier to read, maybe splitting the long literal strings on multiple lines could help as well.

Return value

What your functions return seems a bit unclear which probably makes them hard to use properly.

get_previous_activity_id return an activity_id... or KeyError.
export_activity_laps return True... or an exception.

Maybe, get_previous_activity_id should return None when it fails (or throw an exception depending on how expected this can be).

Maybe, export_activity_laps should not return anything at all and just throw in case of error.

Avoidable recursion

export relies on a recursion to iterate over the different activities.
Python does not handle deep recursions very well because it does not perform Tail Recursion Optimisation. If needed, you can rewrite the function:

def export(activity_id):
    while True:
        previous_id = get_previous_activity_id(activity_id)
        export_activity_laps(activity_id)
        if not previous_id or previous_id = END_ID :
            break
    print("Finished exporting")

This version, just like yours, does not check the validity of the initial activity_id. This may be a desirable check. Then, you'd write something like:

def export(activity_id):
    while activity_id and activity_id != END_ID:
        export_activity_laps(activity_id)
        activity_id = get_previous_activity_id(activity_id)
    print("Finished exporting")

If you want to be a bit fancier and think you might use the logic retrieving the activity identifiers one after the other for a different usage, you could extract it in a generator:

def get_activity_identifiers(activity_id):
    while activity_id and activity_id != END_ID:
        yield activity_id
        activity_id = get_previous_activity_id(activity_id)

def export(activity_id):
    for activity_id in get_activity_identifiers(activity_id):
        export_activity_laps(activity_id)
    print("Finished exporting")

Parameters

It could make sense for export_activity_laps not to be responsible for chosing the file path. This could be provided as a parameter.

Disclaimer: I have run (pun intended) none of the code above.


Dependency injection/dependency injection containers in MVC web app

You are not even doing Dependency Injection here. In your controller constructor for example

public function __construct($db)
{
    $this->db = $db;
    $this->article = new Article($this->db);
    $this->nav = new Nav($this->db);
}

sure you are injecting the $db but that is not a dependency for as long as it does not enforce the type of object required. In this case I can inject anything, say, a string, a number, an object of some other class, array or pretty much everything else. How is constructor going to control the behaviour of this object ?

Furthermore, you are 'newing' up the objects in constructor. Don't you think the objects you are initialising inside the constructor should instead be injected into it ? That is what IoC does.

The solution to first problem is Type Hinting. What you do here is you define the type of argument and only defined type can be passed to the constructor as argument. For more flexibility (which you'd more likely want in case of database connection) you can define an interface and inject an implementation of it into the constructor. So for example you define an interface DatabaseConnection like this:

interface DatabaseConnection {
    public function prepareQuery($queryString);
    public function addQueryBindings(array $queryBindings);
    public function run();
}

Now you can create multiple implementations of this interface and have IoC inject them into constructor. So now you can have MySQLDatabaseConnection, PostgreDatabaseConnection, MSSQLDatabaseConnection, SQLiteDatabaseConnection each one implementing DatabaseConnection and then you type hint the constructor of controller to accept DatabaseConnection

public function __construct(DatabaseConnection $db)
{
    $this->db = $db;
    $this->article = new Article($this->db);
    $this->nav = new Nav($this->db);
}

This constructor will allow any object which implements the DatabaseConnection interface and throw error if you try to inject anything else that is not a descendent of this interface.

Now that type hinting and interface is out of the way, I hope you can already see this but let me point it out.
The objects you are initialising inside controller constructor can be injected by IoC, this will also eliminate the need to have DatabaseConnection injected into a controller (which looks a terrible idea to me). So here is the controller constructor freshen up

public function __construct(Article $article, Nav $nav)
{
    $this->article = $article;
    $this->nav = $nav;
}

and you'll also need to change the constructor of both Article and Nav class to type hint the DatabaseConnection so that IoC can do its things

class Article
{
    public function __construct(DatabaseConnection $db)
    {
        //...
    }
}

and

class Nav
{
    public function __construct(DatabaseConnection $db)
    {
        //...
    }
}

The container, as you call it, is also not an IoC container (Inversion Of Control), It is not doing dependency injection just holding pre-initialised objects into itself. If you want Dependency Injection you need an IoC Container for that.
I dont think I can explain the architecture of an IoC container in a post here but with IoC in place you'll be able to initialise objects auto-magically with proper dependency already injected into it. So for example when you initialise our new controller from IoC container you will have an object of Controller with Article and Nav injected into it and both of them will have DatabaseConnection injected into them.

There are many IoC containers available on Github, some standalone and some as a part of a framework.


DDD modeling for a User Voice-like system

The design looks solid, a few thoughts though:

I would split IUserVoiceStore into more granular UserRepository and SuggestionRepository. Also, UpdateSuggestionAsync() seems to indicate you can only update a suggestion and nothing else at a time, which can be limiting. It also IMO goes out of a repository's jurisdiction to flush a specific object to persistent storage. Using some kind of separate unit of work class where you can put multiple objects to be updated as part of a business transaction might be a better idea.
Not always feasible, but maybe change the type of link between Suggestion and User from a full reference to just an ID to avoid the temptation of manipulating 2 aggregate roots at the same time. (I don't agree with the article you linked to in that regard)
Keep an eye on suggestions with a large number of comments - depending on concurrent access, they can clog up your system and cause locking problems, especially if comments become more sophisticated, with images and so on.


Having an a element inside a button element is not valid. You can’t nest "interactive" elements.

As these are links (navigating to resources) and not buttons (changing state), you should use the a element instead of the button element.

When using a, you could use the next and prev link types.

Using the br element in this context is possibly not appropriate. It must only be used for meaniningful line breaks. But if you can’t use a colon to separate the label from the title (e.g., for text browser users), using br might make sense.

You could use the cite element for the titles of the linked posts.

So the plain HTML could look like this:

Previous: The title of the previous post
Next: The title of the next post. It might be long. Very very long

If you need additional elements for your font-based icons, you should use the span element instead of the i element. The meaning of i doesn’t cover decorative icons.


String Operation to Split on Punctuation

Billy Mays here for the regex library!

It's API-compatible with the standard Python re module. It's powered by open source, and it's safe for colored fabrics and carpets!

The regex library offers things like \p{Punctuation}, which is actually a shorthand form of p{Punctuation=Yes} which is really a shortening of p{General_category=Punctuation}.

If you can make a Unicode query, regex supports it. Identifiers, Categories, Blocks, Diacritical Marks - it even does Coptic!

It cleans! It brightens! It eliminates odors! All at the same time!

test_data = "This, this a sentence. with lotsa' puncts!?@ hahaha looo world"
print(f"Test data: '{test_data}'")

import regex

PUNCT_RE = regex.compile(r'(\p{Punctuation})')

print(PUNCT_RE.split(test_data))

The output looks like:

Test data: 'This, this a sentence. with lotsa' puncts!?@ hahaha looo world'
['This', ',', ' this a sentence', '.', ' with lotsa', "'", ' puncts', '!', '', '?', '', '@', ' hahaha looo world']

regex converts your code from a whopping 21 lines to a 1-line method call-- a 2000% reduction! But you gotta call now!

Here's how to order:

pip install regex


Let us focusing first on the code in question.

Naming

Based on the naming guidelines methods should be named using PascalCase casing and method parameters should be named using camelCase casing.

If you have your own coding/naming guidelines you should stick to them. Right now I don't believe so because you are mixing the casing styles for the input parameter names.

Based on the same guidelines one shouldn't use abbreviations for names. A variable named CS doesn't make it obvious at first glance what it is about, but connectionString would do.

Catching Exception isn't really a good way to do error handling. You should catch only the type of exception which can be handled by your code. What I mean with this can be read here

  Always deal with known exceptions as low-down as you can. However, if you're expecting an exception it's usually better practice to test
  for it first. For instance parse, formatting and arithmetic exceptions
  are nearly always better handled by logic checks first, rather than a
  specific try-catch.
  If you need to do something on an exception (for instance logging or roll back a transaction) then re-throw the exception.
  Always deal with unknown exceptions as high-up as you can - the only code that should consume an exception and not re-throw it should
  be the UI or public API.

If you want to make this reusable for other update methods, you should pass a Dictionary<TKey,TValue> to the method, where as TKey will be the parameters "name" like @LastName and the TValue will be the values the parameter will/should have like so

Public Sub UpdateRecord(ByRef procedure As String, Dictionary<String, Object> parameters)

You can then add the keys as the parameters name and the values as the value.


Best way to get nearest non-zero value from list

I really like your idea of splitting the list -- it's very functional! Let's look at optimizing that approach, though.

def nearest_non_zero(lst, idx):
    # note that I parameterized the list. Should make it easier to test.
    # though I'll use [4,2,6,7,3,0,0,9,4,2,5,8,1,7] as in your code for
    # all examples throughout

    if lst[idx] > 0:
        return lst[idx]
        # I find it easier to track early-exit routes through code than
        # to rule everything out. Let's short-circuit if possible!

    before, after = reversed(lst[:idx]), lst[idx+1:]
    # using `reversed` here lets us avoid creating a new list, which
    # is otherwise necessary if we did `(lst[:idx])[::-1]`. Imagine
    # using that on a list with length of ten million. Yikes!

So far I've really only cleaned up a little bit of code, nothing big, but here is where I'll make a decent departure from your original code. Your code does this:

if len(before) >= len(after):
    loop_length = len(before)
else:
    loop_length = len(after)

This is unnecessary, and it forces you to write in the guards inside your for loop to make sure you're not indexing a value outside of the list length. That's too much work. There's a couple better ways, the primary one being itertools.zip_longest.

The builtin zip pulls together two (or more!) lists into one list of tuples. For instance

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> zip(a, b)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip(b, a)
[('a', 1), ('b', 2), ('c', 3)]

However if you have lists of uneven size, it will only go so far as the shortest list

>>> a = [1, 2]
>>> b = ['a', 'b', 'c']
>>> zip(a, b)
[(1, 'a'), (2, 'b')]  # where's 'c'?!?!

That's not what we want here. We want to zip together every value from both the before and after lists and compare them. That's what itertools.zip_longest does. But of course it needs another value: what should I use to pair with a value that doesn't exist? That's the parameter fillvalue, which by default is None

>>> a = [1, 2]
>>> b = ['a', 'b', 'c']
>>> itertools.zip_longest(a, b)
[(1, 'a'), (2, 'b'), (None, 'c')]  # there's 'c', phew!

>>> a = [1, 2]
>>> b = ['a', 'b', 'c']
>>> itertools.zip_longest(b, a, fillvalue="foobar")
[('a', 1), ('b', 2), ('c', 'foobar')]

That's exactly what we want! In this case we want our fillvalue to explicitly be a failing case (since if the number doesn't really exist we obviously don't want to use it), and our failing case is zero.

After that we compare to zero our "before" value, then our "after" value (to implement that preference for before rather than after), and return either if it's appropriate to do so.

import itertools

for b_val, a_val in itertools.zip_longest(before, after, fillvalue=0):
    if b_val > 0:
        return b_val
    elif a_val > 0:
        return a_val
else:
    # what do you do if you have a list that's all zeroes?

This keeps us from having to deal with any indexing at all, which is common idiomatically in Python. If you have to do for i in range(...): some_list[i], then you're probably doing something wrong!

Our final code, then is:

from itertools import zip_longest

def nearest_non_zero(lst, idx):
    if lst[idx] > 0:
        return lst[idx]
    before, after = lst[:idx], lst[idx+1:]
    for b_val, a_val in zip_longest(reversed(before), after, fillvalue=0):
        # N.B. I applied `reversed` inside `zip_longest` here. This
        # ensures that `before` and `after` are the same type, and that
        # `before + [lst[idx]] + after == lst`.
        if b_val > 0:
            return b_val
        if a_val > 0:
            return a_val
    else:
        return 0  # all zeroes in this list


Singleton class to contain a DocumentClient instance, that can be overridden for testing

This answer only has one tiny section (IDisposable) that I feel is an appropriate kind of answer for Code Review. The rest is more suitable as a StackOverflow answer (since it dives into the specifics of the DocumentClient class). I apologize in advance, and if I should move my answer or edit it in anyway, please feel free to advise me in the comments section.

The DocumentClientclass is already thread-safe.

From what I can gather reading the latest documentation on the DocumentClient class, is that it is already inherently thread-safe. Provided that this remains true, your class wrapper is obsolete.

It seems that this confusion was also asked as a question over at StackOverflow

Microsoft's recommendation of using DocumentClient as a singleton

  If you can draw a parallel to how Microsoft recommends usage of the HttpClient then you might have a better idea of what I mean from this point onwards.

Microsoft recommends that you use a single instance* per application. (again, think of HttpClient)

In the case of a web application using ASP.NET this usually comes in the form of dependency injection via declaring the lifetime of the class to Singleton.

// dependency injection for ASP.NET
services.AddSingleton(myDocumentClientInstance);

This might be the root cause of your misunderstanding. The use of the word "singleton" from the article you probably read, is actually an ASP.NET convention for specifying a lifetime of the instance and also ensuring that only a single (shared) instance is used across your entire web application.

This doesn't mean that implementing the DocumentClient as a singleton class is wrong.

In such a case, a static instance (like you have done) could be the answer. But you're going to get a group of developers that will throw fists in the air at you for making the code difficult-to-impossible to unit test if you do so... You have been warned!

The DocumentClient class implements IDisposable.

Based on your code it will become quite a complex task of making sure that the instance is properly disposed.

The recommended way to handle an object that implements the IDisposable interface is by using the the using block.

using (IDocumentClient client = new DocumentClient(new Uri("endpoint"), "authKey"))
{
    ...
}

Special cases

To summarize with a special case, which could hopefully shine some additional light why your implementation will be troublesome as a true singleton.

There are some special cases for using more than one instance. In particular, if you have multiple CosmosDb accounts, then you should actually use one instance for each account. You can read about that here.

  Note: The parallel to HttpClient does not work here, since we are creating multiple instances on purpose.

Your particular implementation will fall short when you have a scenario with multiple CosmosDb accounts. So please keep that in mind.


Java Apache Commons Net SMTP Wrapper Attachment

SRP - single responsibility principle

The code is violating the SRP, as it does to many things.

It is

adding/composing headers for the attachments
reading files from disc

I would extract the composition of the headers to a separate method.

private String getHeaders() {
    StringBuilder sb = new StringBuilder();

    sb.append("\r\n").append("--").append(bound).append("\r\n");
    sb.append("Content-Type: application/octet-stream\r\n");
    sb.append("Content-Transfer-Encoding: base64\r\n");
    sb.append("Content-Disposition: attachment; filename=\"");

    return sb.toString();
}

and would assign the result before the for loop to a String variable.

Next we extract the file reading to a separate method. I don't know if Android supports Try with resources so I don't use it here. We also rename the int nRead to bytesRead.

private byte[] readFile(File file) throws FileNotFoundException, IOException {
    FileInputStream fileInputStream = new FileInputStream(file);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int bytesRead;
    byte[] data = new byte[1024];

    while ((bytesRead= fileInputStream.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, bytesRead);
    }

    buffer.flush();
    fileInputStream.close();

    return buffer.toByteArray();
}

next, we add a method which takes a file and returns the content as base64 encoded string

private String getContentAsBase64(File file) throws FileNotFoundException, IOException {

    byte[] fileContent = readFile(file);

    return Base64.encodeBase64String(fileContent);
}

After using the fluent append() method instead of the string adding using +, this leads to the former code beeing refactored to

Writer w = client.sendMessageData();
String attachmentHeader = getAttachmentHeader();
for (File file : myAttachments) {
    w.append(attachmentHeader);
    w.append(Tools.getNameForAttach(file.getName()));
    w.append("\"\r\n\r\n");
    w.append(getContentAsBase64(file));
    w.append("\r\n");
}
w.close();