int[][] mat = new int[n + 1][m + 1];
        for(int i = 0 ; i < n + 1 ; i++)
            mat[i][0] = 0;
        for(int i = 0 ; i < m + 1 ; i++)
            mat[0][i] = 0;

Consider

        int[][] mat = new int[n + 1][m + 1];
        Arrays.fill(mat[0], 0);
        for (int i = 1; i < mat.length; i++) mat[i][0] = 0;

Now we no longer initialize mat[0][0] twice.  We initialize it only once because we exclude it from the for loop.

We use the built-in to initialize the first row.

We initialize the rest of the first column with a for loop, as the built-in doesn't work with columns.

Since we are using the single statement version of the for loop, we put the single statement on the same line as the for loop.  Now it's obvious that it's just a single statement.  Before it was less obvious.

I would actually prefer to always use the block form, but that's your choice.

I changed from n + 1 to mat.length because it is more robust in the face of future changes.  Consider what happens if you were to change the n + 1 in the first line to n + 2.  In the original code, you would have to change the second line as well.  In this version, you don't.

One might argue that you would never change the 1 to a 2 in this code.  But even if that is so here, that might not be true in other code.  It is a good habit to try to avoid having code parallel other code.  If possible, make the code follow the other as it does here.  The mat.length will always be the right value here while the n + 1 is dependent on the logic used now.

I'm not crazy about the name mat.  I'm guessing it's short for matrix, but matrix of what?  It seems like there could be a more descriptive name.

Note that given the way that Java defaults integer values, the initialization is actually unnecessary.  Java will initialize the whole thing to 0.  You don't have to do any explicit initialization.  Java will do what you want automatically.

        char capStart = 65;
        char capEnd = 90;
        char smallStart = 97;
        char smallEnd = 122;
        char diff = 32;

You only use two of these

        char smallStart = 'a';
        char diff = 'A' - 'a';

I find this more readable.  By substituting 'a' for the numeric value, it is clearer about what we seek.  Although I'd probably just change

                if(a[i - 1] >= smallStart)

to

                if (a[i - 1] >= 'a')

or

                if (Character.isLowerCase(a[i - 1]))

That last may be longer, but it is also more robust against other alphabets than the latin1 alphabet.  And it may be better optimized as well.

        for(int i = 1 ; i < n + 1 ; i++)
        {
            for(int j = 1 ; j < m + 1 ; j++)

Given the frequency with which you say i - 1 and j - 1, I'd consider saying

        for (int i = 0; i < a.length; i++)
        {
            for (int j = 0; j < b.length; j++)

I believe that this reads more naturally.  For each letter in a and for each letter in b, do...

Don't forget to change all the i - 1 to i and all the i to i + 1 if you do this.


Avoid using open when you can. with is a keyword for using a context manager, which will automatically ensure that files are always properly closed, which you don't ensure when you just call open in a list comprehension.

with open('bad_words.txt') as f:
    bad_words = [line.rstrip('\n') for line in f]

keep_running is always True, so why not just use while True.

To reduce nesting levels, I'd flip the condition from this:

rst_messages_list = []
if div.id not in parsed_messages:
    rst_messages_list.append(div.text)

to this

rst_messages_list = []
if div.id in parsed_messages:
    continue

rst_messages_list.append(div.text)

continue moves onto the next iteration, so it is effectively the same as before except that your code isn't as deeply nested.

When testing unique_message, you should really make it lowercase for ease of testing. That way you can match regardless of case. Also when you're testing if any word in bad_words is in unique_message, there's a Python function that does that, called any:

for unique_message in rst_messages_list:
    unique_message = unique_message.lower()
    if any(word in unique_message for word in bad_words):

This does the same as you had before, but now the if and for statements are combined in one line. The one main difference, is that your old code would message the user repeatedly if they used multiple bad words, which I assume was not the intention.

You repeatedly call these lines:

FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(message)
FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

Make this a function:

def send_message(message, xpaths):
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(message)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

That reduces your code drastically:

if any(word in unique_message for word in bad_words):
    send_message(message, xpaths)
elif '/message1' in unique_message:
    send_message("text to be sent", xpaths)
elif '/message2' in unique_message:
    send_message("2016 © me", xpaths)
elif '/message3' in unique_message:
    line = random.choice(open('jokes.txt').readlines())
    send_message(line, xpaths)

Worth noting that since these are all if commands, you might send every one of these messages, for a message like "/message1 /message2 /message3 smeg" (assuming that smeg is on your list of bad_words). You should all but the first one elifs, so that they're mutually exclusive and only one (or none) will run.

Last point, unless calling webdriver.Firefox() is a lot of work for the script, I'd put that at the top instead of in if __name__ == "__main__", as it's easier to spot when it's near the top of the page, after imports. That's the convention for where constants should go.

FIREFOX_DRIVER = webdriver.Firefox()


Takes a list and return a dict of distinct values pointing to a list of index locations of each value

The first try :
from itertools import groupby
sample_data = [1,2,3,3,1,0,5]
give_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in itertools.groupby(list(enumerate(dta)), lambda x:x[1])}
print(give_groups(sample_data))

Have to be corrected to:
from itertools import groupby # --> you don't have to call itertools.groupby just groupby
sample_data = [1,2,3,3,1,0,5]
give_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in groupby(list(enumerate(dta)), lambda x:x[1])}
print(give_groups(sample_data))

But seems to be replacing items and not appending them, don't see why.

In the alt_grouping function, defaultdict doesn't exists:
def alt_grouping(dta):
    retdict = defaultdict(list) # don't know what is defaultdict
    for position, item in enumerate(dta):
        retdict[item].append(position)
    return retdict

Then I found a solution that works, it's based on your function alt_grouping:
sample_data = [1,2,3,3,1,0,5]

retdict = {}
for position, item in enumerate(sample_data):
        if item in retdict.keys():
            retdict[item].append(position)
        else:
            retdict[item] = [position]

print(retdict)

I take some execution & times testing in the first try and my alternative with a bigger sample a list of two range(100).
Sample Data:
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

First Function:
{0: [100], 1: [101], 2: [102], 3: [103], 4: [104], 5: [105], 6: [106], 7: [107], 8: [108], 9: [109], 10: [110], 11: [111], 12: [112], 13: [113], 14: [114], 15: [115], 16: [116], 17: [117], 18: [118], 19: [119], 20: [120], 21: [121], 22: [122], 23: [123], 24: [124], 25: [125], 26: [126], 27: [127], 28: [128], 29: [129], 30: [130], 31: [131], 32: [132], 33: [133], 34: [134], 35: [135], 36: [136], 37: [137], 38: [138], 39: [139], 40: [140], 41: [141], 42: [142], 43: [143], 44: [144], 45: [145], 46: [146], 47: [147], 48: [148], 49: [149], 50: [150], 51: [151], 52: [152], 53: [153], 54: [154], 55: [155], 56: [156], 57: [157], 58: [158], 59: [159], 60: [160], 61: [161], 62: [162], 63: [163], 64: [164], 65: [165], 66: [166], 67: [167], 68: [168], 69: [169], 70: [170], 71: [171], 72: [172], 73: [173], 74: [174], 75: [175], 76: [176], 77: [177], 78: [178], 79: [179], 80: [180], 81: [181], 82: [182], 83: [183], 84: [184], 85: [185], 86: [186], 87: [187], 88: [188], 89: [189], 90: [190], 91: [191], 92: [192], 93: [193], 94: [194], 95: [195], 96: [196], 97: [197], 98: [198], 99: [199]}
--- 0.001995563507080078 seconds ---
My Function:
{0: [0, 100], 1: [1, 101], 2: [2, 102], 3: [3, 103], 4: [4, 104], 5: [5, 105], 6: [6, 106], 7: [7, 107], 8: [8, 108], 9: [9, 109], 10: [10, 110], 11: [11, 111], 12: [12, 112], 13: [13, 113], 14: [14, 114], 15: [15, 115], 16: [16,
116], 17: [17, 117], 18: [18, 118], 19: [19, 119], 20: [20, 120], 21: [21, 121], 22: [22, 122], 23: [23, 123], 24: [24, 124], 25: [25, 125], 26: [26, 126], 27: [27, 127], 28: [28, 128], 29: [29, 129], 30: [30, 130], 31: [31, 131], 32: [32, 132], 33: [33, 133], 34: [34, 134], 35: [35, 135], 36: [36, 136], 37: [37, 137], 38: [38, 138], 39: [39, 139], 40: [40, 140], 41: [41, 141], 42: [42, 142], 43: [43, 143], 44: [44, 144], 45: [45, 145], 46: [46, 146], 47:
[47, 147], 48: [48, 148], 49: [49, 149], 50: [50, 150], 51: [51, 151], 52: [52, 152], 53: [53, 153], 54: [54, 154], 55: [55, 155], 56: [56, 156], 57: [57, 157], 58: [58, 158], 59: [59, 159], 60: [60, 160], 61: [61, 161], 62: [62,
162], 63: [63, 163], 64: [64, 164], 65: [65, 165], 66: [66, 166], 67: [67, 167], 68: [68, 168], 69: [69, 169], 70: [70, 170], 71: [71, 171], 72: [72, 172], 73: [73, 173], 74: [74, 174], 75: [75, 175], 76: [76, 176], 77: [77, 177], 78: [78, 178], 79: [79, 179], 80: [80, 180], 81: [81, 181], 82: [82, 182], 83: [83, 183], 84: [84, 184], 85: [85, 185], 86: [86, 186], 87: [87, 187], 88: [88, 188], 89: [89, 189], 90: [90, 190], 91: [91, 191], 92: [92, 192], 93:
[93, 193], 94: [94, 194], 95: [95, 195], 96: [96, 196], 97: [97, 197], 98: [98, 198], 99: [99, 199]}
--- 0.0009963512420654297 seconds ---

Seems to be pretty similar then I try with list(range(10000)):
First Function:
--- 0.015984535217285156 seconds ---
My Function:
--- 0.005953311920166016 seconds ---

Here we see a difference.
There is the code for tests - EDITED :
import time
sample_data = list(range(1000000)) + list (range(1000000))
# print ("Sample Data:\n",sample_data, "\n")

print("First Function:")
start_time = time.time()

from itertools import groupby
give_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in groupby(list(enumerate(dta)), lambda x:x[1])}
# print(give_groups(sample_data))
give_groups(sample_data)

print("--- %s seconds ---" % (time.time() - start_time))

print("My Function:")
start_time = time.time()
retdict = {}
for position, item in enumerate(sample_data):
        if item in retdict.keys():
            retdict[item].append(position)
        else:
            retdict[item] = [position]

print("--- %s seconds ---" % (time.time() - start_time))

print("Other Function:")

from collections import defaultdict

start_time = time.time()
def dict_with_indices(dta):
    """ Returns a dictionary with a list of indices for each item in dta

    Args:
        dta (list): list of data to be indexed

    Returns:
        dict: dict with list of indices as values

    Examples:
        >>> dict_with_indices([1,2,3,3,1,0,5]]
        {1: [0, 4], 2: [1], 3: [2, 3], 0: [5], 5: [6]}
    """
    result = defaultdict(list)
    for idx, val in enumerate(dta):
        result[val].append(idx)
    return result

dict_with_indices(sample_data)

print("--- %s seconds ---" % (time.time() - start_time))

Times for this new tests:
First Function:
--- 1.9537413120269775 seconds ---
My Function:
--- 0.7061352729797363 seconds ---
Other Function:
--- 0.6053769588470459 seconds ---

New Solution seems to be the better one, thanks to @agtoever :
from collections import defaultdict

    def dict_with_indices(dta):
        """ Returns a dictionary with a list of indices for each item in dta

        Args:
            dta (list): list of data to be indexed

        Returns:
            dict: dict with list of indices as values

        Examples:
            >>> dict_with_indices([1,2,3,3,1,0,5]]
            {1: [0, 4], 2: [1], 3: [2, 3], 0: [5], 5: [6]}
        """
        result = defaultdict(list)
        for idx, val in enumerate(dta):
            result[val].append(idx)
        return result

    dict_with_indices(sample_data)


You could rewrite your key() method and use it to much greater effect, reducing repeated code.

def key(self, co, radius=0):
    return tuple((c + radius) // self.cell_size for c in co)

You can then call key() in both add_item() and check_sphere(). In add_item() it will replace k, while in check_sphere() you can use it to define your ranges.

After that I would look for a way to flatten those nested for loops which will likely be an algorithm change. Hopefully someone else has some ideas there.


Yes, you can. Given that foldr is right-associative, your implementation is incorrect. Intuitively, foldr will recurse down a structure until it bottoms out and then will it start accumulating the result by going back up. So, this version would be more appropriate:

foldr f acc (NonEmpty a as) = f a (foldr f acc as)

In fact your version is a correct foldl:

foldl f acc (NonEmpty a as) = foldl f (f acc a) as

I think your version of foldMap is fine given the associativity of the monoidal operation.


Code Repetition
In your program, you are using the following code three times:
System.out.print("a: ");
if (!in.hasNextInt() || (a = in.nextInt()) <= 0) {
 System.out.println("Input must be a positive integer!");
 return;
}

You should use a method for this:
public static int getUserInput() {
 Scanner in = new Scanner(System.in);
 int number;
 if (!in.hasNextInt() || (number = in.nextInt()) <= 0) {
  System.out.println("Input must be a positive integer!");
  return -1; //Returns -1 for illegal input
 }
 return number;
}

Input validation
It's good that you control, whether the user made a valid input, but this point can be improved further: Your program stops, when the user makes an invalid input. That's not what an user expects:
public static int getUserInput(String var) {
 Scanner sc = new Scanner(System.in);
 int number;
 while(true) {
  try {
   System.out.print(var + ": ");
   number = sc.nextInt();
   if(number <= 0) {
    throw new InputMismatchException();
   }
   break;
  }
  catch(InputMismatchException e) {
   System.out.println("Enter a number > 0.");
   sc.nextLine();
  }
 }
 return number;
}

By using this code, the user will be able to make inputs until making a valid input. If you don't know about try-catch yet, i suggest reading this explanation.

Logic
I would create a seperate method for the "triangle-validation":
public static boolean isTriangle(int a, int b, int c) {
 if (a + b > c && a + c > b && b + c > a) {
  return true;
 } else {
  return false;
 }
}

Style
Please consider using more than one space for indentation. My suggestion is two or even four spaces. This improves the legibility.

Final code
import java.util.Scanner;
import java.util.InputMismatchException;

public class Triangle {
    public static void main(String[] args) {
        int a, b, c;
        Scanner in = new Scanner(System.in);

        // Prompt for a
        a = getUserInput("a");

        // Prompt for b
        b = getUserInput("b");

        // Prompt for c
        c = getUserInput("c");

        if (isTriangle(a, b, c)) {
            System.out.println("It's a triangle.");
        } else {
            System.out.println("Invalid lengths for a triangle.");
        }
    }

    public static boolean isTriangle(int a, int b, int c) {
        if (a + b > c && a + c > b && b + c > a) {
            return true;
        } else {
            return false;
        }
    }

    public static int getUserInput(String var) {
        Scanner sc = new Scanner(System.in);
        int number;
        while(true) {
            try {
                System.out.print(var + ": ");
                number = sc.nextInt();
                if(number <= 0) {
                    throw new InputMismatchException();
                }
                break;
            }
            catch(InputMismatchException e) {
                System.out.println("Enter a number > 0.");
                sc.nextLine();
            }
        }
        return number;
    }
}


Random alphanumeric password generator with GOTOs

As a general rule of thumb, any time you feel the need to use goto, take a couple of aspirin and lay down until the feeling passes.  They probably should have been deprecated decades ago.

In this particular case, using a string of allowed characters and randomly picking an index in that string would do away with your goto's.

I think too a StringBuilder would do a lot better for storing the characters than a LinkedList.


Finding the second-largest value in an array

Trust the math. When the x > hi comparison fails, there is no need to test against x < hi. The streamlined code should look like

    if x > hi:
        ....
    elif x > mid:
        ....
    else
        ....

Follow the math. In the worst case - the array sorted in the descending order - (almost) every element has go through two comparisons, making total of \$2n - 2\$, which is larger than the goal of \$n + \log{n} - 2\$
A correct approach is to arrange an elimination tournament (\$n - 1\$ comparisons to determine a champion), while keeping track of those who lose only to the champion. This makes \$log{n}\$ candidates for the second place, and \$\log{n} - 1\$ comparisons to determine the second. For the details, watch Alex Stepanov lectures starting with lecture 8, or just see the final code.

I highly recommend to watch the entire course, even if you are not interested in C++.


Provide functional-programming style solution for 2D Array - DS challenge

There's no need to write a max() method. The Standard Library provides for that.

A for comprehension, with a yield clause, produces a result. So instead of using a mutable var to capture and collect the results of the yield you should capture them directly.

val res = for {...} yield {...}

Or, if you want to process the results more directly, i.e. without the intermediate variable, you can use the somewhat awkward parentheses construct.

def hourglassSum(arr: Array[Array[Int]]): Int = {
  (for {
    x <- 0 to 3
    y <- 0 to 3
  } yield {
    arr(y)(x)   + arr(y)(x+1)   + arr(y)(x+2) +
                  arr(y+1)(x+1) +
    arr(y+2)(x) + arr(y+2)(x+1) + arr(y+2)(x+2)
  }).max
}


Your code formatting deviates from the default Java code formatting, just saying.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

Wildcard imports are kinda bad. If you can avoid them, please do so.

public class Panel extends JPanel

I'm sure you can find a more descriptive name for this class, like PaintablePanel or MousePaintablePanel.

// PROPERTIES

Personally, I don't like such "structuring" comments, they do nothing and only clutter up the code and need to be manually moved when refactoring automatically.

private final int DEFAULT_WIDTH  = 800;
private final int DEFAULT_HEIGHT = 800;
private final Color BACK_COLOR   = Color.WHITE;

Personally I also don't like this column based alignment, it puts my brain into some sort of "column reading mode" which makes it hard for me to associate the value with the variable.

private int x1, y1, x2, y2;

You should not declare multiple variables on the same line, it makes it easy to miss the declaration of variables.

private MyMouseHandler handler;

MyMouseHandler is not a very good name.

public void paintComponent(Graphics g)
{
  super.paintComponent(g);
}

This method seems to override a super method, yet misses the @Override annotation. Also, if it does not do anything, why override it?

public void mousePressed( MouseEvent e )
{
...
     SetUpDrawingGraphics();

Why are you doing this on every mouse press?

public class RunPanel

This is another bad name. What does it run? And it is not a panel.

frame.setDefaultCloseOperation(3);

Any reason why you're not using the constants defined in JFrame?

The program works fine, I can draw normal curves at low mouse speed. But again, as I increase the mouse speed the lines/curves start the get jaggy and ugly.

That is how it is.

I have gathered the two classes into one class file and the program stoped the lag. What is causing this?

I see this behavior in both programs. Combining them in the same file has for sure nothing to do with it.


Convert a JS DataTable to an array of objects

There isn't really much you can do unless you know the objects property name. I refactored the properties into an array, so you just can iterate through them as they are reused so many times.

function processAggregateData(data) {
    var dataProperties = ['index', 'average', 'min',
                          'max', 'sum', 'target',
                          'LLL', 'LL', 'L',
                          'H', 'HH', 'HHH',
                          'status'];
    dataRows = data.data[0].rows;
    var returnArray = [];
    for (var i = 0; i < dataRows.length; ++i){
        var dataObject = {};
        for(var j=0;j<dataPoperties.length;j++){
          dataObject[dataProperties[j]] = dataRows[i].fld[j].v;
        }
        returnArray.push(dataObject);
    }
    return returnArray;
}

As you can see there are no longer any magic constants.

NOTE: EcmaScript 6 is possible, you just need to transpile it into EcmaScript 5


Delay and queue animation in a function - how can I optimise this by removing duplicate code?

You are repeating yourself a ton here, you should read up on DRY.

You could store the animations in an array and then execute those animations :

var PROPERTIES = 0 , OPTIONS = 1;
var animations =
[
  [ {top: '425px'}         , { duration: 1800, easing : 'linear', queue: true } ],
  [ {marginLeft: '-284px'} , { duration: 2500, easing : 'linear', queue: true } ],
  [ { top: '157px'}        , { duration: 1800, easing : 'linear', queue: true } ],
  [ {marginLeft: '264px'}  , { duration: 2500, easing : 'linear', queue: true } ]
]

function animateNode( $node )
{
  animations.forEach( function (animation)
  {
    $node.animate( animation[PROPERTIES] , animation[OPTIONS] );
  });
}

function animateNodes()
{
  animateNodes( $('.node') );
  animateNodes( $('.node2') );
  animateNodes( $('.node3') );
  animateNodes( $('.node4') );
}

Ideally of course, you would store the results of $(...) in a variable and use that variable instead of invoking $(...) every single time. Even more ideally, those variables would be in an array over which you can loop.

You can apply this technique to the rest of your code as well.


Render multiple SSRS reports in parallel

Here's pure async example without any workarounds.
private async Task ProcessReport(Report report, ConcurrentDictionary<int, string> reportDictionary)
{
    var (reportPath, bindingOrder, reportParameters) = report;

    var exportedImage = await _exporter.Export(_reportServerUrl, reportPath, export, reportParameters);

    if (exportedImage == null)
    {
        throw new InvalidOperationException($"Could not render report {reportIdentifier} with binding order {bindingOrder}.");
    }

    reportDictionary.GetOrAdd(bindingOrder, exportedImage);
}

var reportDictionary = new ConcurrentDictionary<int, string>();

List<Task> tasks = new List<Task>();
foreach (var report in request.Reports)
{
    tasks.Add(ProcessReport(report, reportDictionary));
}
await Task.WhenAll(tasks);


Two major points:

The parsing is very fragile and only works when the code is laid out in a certain way. You should look for a proper parser and leverage that.
It is rather inefficient to scan all the files every time you encounter a function declaration. You could use dictionaries to keep track of functions so one pass over the files would suffice.


Parsing a u8 separated vector of FromStr from a BufRead

I'm calling the code directly from my main function, so I'm more
concerned with returning a human readable error rather than something
that can be caught and recovered from programmatically, hence I'm
using String as the error type.
[...]

Is it considered bad practice to return String as an error type?

Yes, it is generally considered bad practice to return Result<_, String> when the error returned is formatted from other errors.  The recommended approach is to define an enum and implement From, Display, and Error: (using the thiserror crate for simplicity)
use thiserror::Error;

#[derive(Debug, Error)]
pub enum Error {
    #[error("cannot read entry {entry_no}")]
    Io { entry_no: usize, source: std::io::Error },
    #[error("cannot read entry {entry_no}")]
    Encoding { entry_no: usize, source: std::string::FromUtf8Error },
    // ...
}

The above code works as far as I can tell, but I'm wondering if
there's a nicer way to deal with the mess in the match expression. The
functions from_utf8 and split return different error types, but
both implement Display so maybe there's some elegant way to
eliminate some code duplication there that I don't know about (I'm new
to rust, coming from C++).

Your options include:

methods on Option and Result, like Result::and_then and Option::ok_or_else;

the ? operator; and

using .zip(1..) instead of .enumerate() to get rid of that + 1,

plus potentially other things that didn't immediately come to mind.


Converting Decimals to Fractions with JavaScript - Simplify & Improve

highestCommonFactor should take 2 integers as parameter instead of relying on the variable numerator and `denominator'. Also, you could find it using Euclid'a algorithm.
I am wrong is saying that this piece of code :

var rightDecimalPart = decimalArray[1];
// Save decimal part only for later use
var decimalOnly = "0." + rightDecimalPart;
// Find the decimal multiplier
var multiplier = "1";
for (var i = 0; i < rightDecimalPart.length; i++) {
    multiplier += "0";
}
// Create numerator by multiplying the multiplier and decimal part together
var numerator = Number(multiplier) * Number(decimalOnly);

is here to transform a number such as 78924 in 0.78924 and then check that have to multiply it by 100000 to get an integer which is ... 78924.

Edit
After a first cleanup, I get :

function highestCommonFactor(a,b) {
    if (b==0) return a;
    return highestCommonFactor(b,a%b);
}

var decimal = "1.75";
var decimalArray = decimal.split(".");
var leftDecimalPart = decimalArray[0];
var rightDecimalPart = decimalArray[1];

var denominator = "1";

for (var i = 0; i < rightDecimalPart.length; i++) {
    denominator += "0";
}
document.getElementById("debug").innerText = denominator;
var factor = highestCommonFactor(rightDecimalPart, denominator);

// Simplify the fraction by dividing the numerator and denominator by the factor
var denominator = Number(denominator) / Number(factor);
var numerator = (Number(rightDecimalPart) / Number(factor)) + (leftDecimalPart * denominator);

// Display solution as a proper fraction or improper fraction (depending on input)
document.getElementById("divSolution").innerText = numerator + "/" + denominator;

I'll try to go a step further.

Edit 2
After a rewriting of the calculation, here's what I got :

function highestCommonFactor(a,b) {
    if (b==0) return a;
    return highestCommonFactor(b,a%b);
}

var decimal = "1.75";
var decimalArray = decimal.split(".");
var leftDecimalPart = decimalArray[0]; // 1
var rightDecimalPart = decimalArray[1]; // 75

var numerator = leftDecimalPart + rightDecimalPart // 175
var denominator = Math.pow(10,rightDecimalPart.length); // 100
var factor = highestCommonFactor(numerator, denominator); // 25
denominator /= factor;
numerator /= factor;

document.getElementById("divSolution").innerText = numerator + "/" + denominator;


Resolving multiple "paths" in nested attributes

What do you think this will return for part = '[compact|fullsize|x|y]'

re.findall(r'\[(\w+)(?:\|(\w+))*\]', part)

It will give:

[('compact', 'y')]

Because, when a group matches multiple times, the last match overwrites previous matches, as per the docs.
If you want to support multiple patterns, I'm afraid you will have to do in two steps: matching and then splitting.

The part I don't like about this is that you split path to parts,
then when you need to recurse,
you re-join the parts again,
and in the recursion step it will be split again, and so on.
That's a lot of splitting and joining and iterations.
The recursive logic can be also tricky to understand.

Here's an alternative, without using recursion and unnecessary splitting, joining, iteration:

from collections import deque

def resolve_paths(path):
    parts = deque(path.split('.'))
    paths = [[]]

    while parts:
        part = parts.popleft()
        branches = re.findall(r'\[(\w+)(?:\|(\w+))*\]', part)
        if branches:
            orig_paths = paths[:]
            paths = []
            for branch in branches[0]:
                for path in orig_paths:
                    paths.append(path + [branch])
        else:
            for path in paths:
                path.append(part)

    return ['.'.join(path) for path in paths]


Basic Collatz program with input validation in Python

Most of your code deals with obtaining and validating user input. That's
tedious code to write and maintain. In addition, programs premised on
user-interactivity are difficult to execute during development, testing, and
debugging: every execution requires a manual dialogue between the user (you,
the programmer) and the computer. That get annoying very fast. Moreover, your
program provides no clean way to quit. A more powerful approach based on
command-line arguments and the built-in argparse library is shown below.
The second issue is that your collatz() function intermixes algorithmic
computation and reporting (i.e. printing). That's almost
always a bad idea. A more flexible approach is to restrict collatz() purely to
the algorithm and do the printing at a higher level in the program -- either in
main(), if the reporting remains extremely simple, or in a function called by it.
The essence of most of these suggestions is to organize your code more
carefully to keep different tasks more separated: user input collection; input
validation; computation; and reporting.
import argparse
import sys

def main(args):
    # Get user arguments.
    opts = parse_args(args)

    # Make computations.
    sequences = [list(collatz(val)) for val in opts.initial_values]

    # Report to user. Enhance as needed.
    for seq in sequences:
        print(seq)

def parse_args(args):
    # You want the user to provide one or more integers
    # on the command line. The argparse library will handle that
    # automatically for many use cases (e.g, any integer). In your situation,
    # you do need to write a type validation function, but that process
    # is a bit simpler and more focused than your previous validation
    # code, which was mixed with the rest of the program's logic.
    ap = argparse.ArgumentParser()
    ap.add_argument('initial_values', nargs = '+', type = positive_int)
    return ap.parse_args(args)

def positive_int(val):
    # You can make this more robust if needed (eg to prevent values like
    # '12.34' from being accepted), but here's the basic technique.
    try:
        n = int(val)
        1 / n
        return n
    except Exception:
        raise argparse.ArgumentTypeError(f'Invalid positive integer: {val}')

def collatz(n):
    # Relieved of printing, this function becomes simpler, more testable,
    # and more general purpose.
    while n > 1:
        yield n
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
    yield n

# Invoke main() if the program was executed rather than imported.
# This is important for testability, because testing tools need
# to import your code without executing the script in its entirety.
if __name__ == '__main__':
    main(sys.argv[1:])


Your question is not very clear... but, the way I understand it is:

Collect all the unique values in t1, and count how many of those unique values appear in t2.

Interesting problem.... instead of a straight join with all the or conditions, which may lead to an internal cross-product (thousands of joins and results to run comparisons on), I would state the logic as a couple of subselects ... which represent the two sets of data... the unique values in t1, and the unique values in t2.

Note, the 'union' operator does a distinct as part of the union....

select count(*)
from
  (
      select c1 as val from t1
    union
      select c2 as val from t1
    union
      select c3 as val from t1
  ) as t1vals,
  (
      select c1 as val from t2
    union
      select c2 as val from t2
    union
      select c3 as val from t2
  ) as t2vals
where t1vals.val = t2vals.val

The code looks nicer this way, but requires scanning each table three times (which I think will be better than the potentially thousands of times it may have to happen with your query......

I have put together an sqlfiddle for this


$device = Device::where($params)->first(); will either return an instance of eloquent or null.

You have if (!$device) {...}else{...}.

This translates to if the device is not found aka the else part then $device->is_banned which will results in a trying to get property of non-object fatal error.

if ($condition) {
    return false;
}else{
    return true;
}

The else is not necessary since return will immediately end the execution of the function and return the result.

if ($condition) {
    return false;
}
return true;

Works just the same and I personally find it more visually pleasant.

$this->isDeviceExistWithUser($user_id,$device_id)

Syntax heavy naming. You could simple call it deviceForUser or something like that. is usually suggests a boolean, as in isDevice, isSmall, isLarge etc etc.

$this->isDeviceBanned($device_id)

Nitpick but a simple isBanned will do here since you passing in $device_id, clearly a device is the scope here.

isLoginValid2Refactored

Again really heavy name here. It's not something inherently wrong with it, but the lighter the better. Fluent and easy to understand goes a long way.


Calculate the frequency of characters in a string

Separate logical elements

It's good to separate different logical parts of a program, for example:

Parse input: a function that takes an InputStream and returns a String
Compute frequencies: a function that takes a String and returns frequencies in some form. In your current program you used an int[], it could have been a Map<Character, Integer>.
Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.

Computing indexes of letters

If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:

int index = ch - 'A';

This eliminates the nested loop you had.
It also eliminates the need for the c array.

Initializing arrays

Instead of this:

int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

You could write simply int[] f = new int[26];

Instead of this:

char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

I would take a lazy approach and write char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

Use better variable names

Single-letter variable names should only be used for trivial, highly transient things.
The names f and c in the program are inappropriate, and make the program more difficult to read.


Storing variables to a map by splitting a text file

Range-based for loop

for (int i = 0; i < textList.size(); i++){
    String[] split = splitTxt(textList.get(i), "\\s+");

You can simplify this with a range-based for loop.

for (String text : textList) {
    String[] split = text.split("\\s+");

No need to manage i manually.

I also eliminated the call to splitTxt, which makes the code smaller and easier to read.

Bug

    List<String> friends = new ArrayList<>();
    List<String> interests = new ArrayList<>();
    if (split.length >= 2){
        String[] interestArray = splitTxt(split[2], ";");

This will cause an array index out of bounds when the split.length is 2.

    if (split.length < 3) {
        continue;
    }

    String[] interestArray = splitTxt(split[2], ";");
    List<String> friends = new ArrayList<>();
    List<String> interests = new ArrayList<>();

When split is of length 2, only 0 and 1 are valid indexes.  So split[2] would be out of bounds.  Making it a 3 instead of a 2 would fix that.

Switching to an early exit changes from >= to < and allows us to reduce the level of indent.  It works here because the entire code for an iteration after that point is inside the if.

There is no point to declaring and initializing friends and interests if we're not going to use them.  So do those tasks after the check, not prior.

asList

        String[] interestArray = splitTxt(split[2], ";");
        for(int j = 0; j < interestArray.length; j++){
            interests.add(interestArray[j]);
        }
        Accounts.put(split[0],split[1]);
        intrestDic.put(split[0],interests);

You don't need to manually copy one by one.

        Accounts.put(split[0],split[1]);
        intrestDic.put(split[0], new ArrayList<String>(Arrays.asList(split[2].split(";"))));

Using a copy constructor with Arrays.asList will allow the whole thing to be copied at once.

Summary

private static final int HEADER_SIZE = 3;

and later

for (String text : ReadFile(FileName)) {
    String[] split = text.split("\\s+");
    if (split.length < HEADER_SIZE) {
        continue;
    }

    Accounts.put(split[0], split[1]);
    intrestDic.put(split[0], new ArrayList<String>(Arrays.asList(split[2].split(";"))));
    List<String> friends = Arrays.asList(split).subList(HEADER_SIZE, split.length));
    FriendsDic.put(split[0], new ArrayList<String>(friends);
}

This isn't necessarily more efficient, although it could be (depending on how Java optimizes it).  The primary advantage of this version is that it leaves maintenance to the Java engine.

Hibernate

Hibernate (and Java Persistence Annotations in general) is for exactly this task.  It maps classes to storage and vice versa.  Now, that might be a heavyweight solution, but it is one that exactly addresses the problem.

You can write persistence code manually, without annotations.  But I would generally still use a database if you intend the code to scale at all.  You don't want to read all the records every time you want one record.  Rather than reinventing that wheel, just use the existing solution:  a database.

Hibernate makes it comparatively easy to switch from one database to another.


Querying all items that are in a many-to-many relationship with a child of an object

I also considered trying something like
return Images.objects.filter(articles__publication=self)

But I don't think that I can do this because then I have to define Images above
Publications, which won't work with Articles and Images.

Did you try this?  It seems like it would work and would be the best approach.  You could add a .distinct() clause at the end of the query to avoid converting to a set.
It is best practice to set the related_name and related_query_name variables on your model related fields.  This will make your queries less verbose; article_set and image_set become articles and images, respectively.  See example below
class Article(models.Model):
    filename = models.CharField(max_length=255)
    publication = models.ForeignKey(to=Publication,
                                    on_delete=models.CASCADE,
                                    related_name='articles',
                                    related_query_name='article')

class Image(models.Model):
    name = models.CharField(max_length=255)
    articles = models.ManyToManyField(to=Article,
                                      related_name='images',
                                      related_query_name='image')

Look at the prefetch_related documentation.  You are querying the db for every image set on each article.
@property
def images(self):
    images = []
    for article in self.article_set.all():
        images += list(article.images.all())
    return list(set(images))

Using prefetch_related:
@property
def images(self):
    images = []
    publication = self.objects.prefetch_related('articles__images')
    for article in publication.articles.all():
        for image in article.images.all():
            images.append(image)

    return set(images)


Finding all possible distinct palindromes of a string

/*
* Complete the function below.
*/

Do you still need it?

String[] strArray = str.split("");
List<String> list = Arrays.asList(strArray);
list = list.subList(1, list.size());

That's ugly. You could work with the original String or use str.toCharArray() if you really needed an array. But you don't.

//Set does'nt allow duplicates.

True, but rather well-known. And a typo.

//Sublist is required because split method gives an extra space.

True, but misplaced by a few lines. Full line comments belong before the block they describe.

String palindromeStr = null;
for(int i = 0;i<list.size();i++){
    palindromeStr = list.get(i);

This should be

for(int i = 0; i < list.size(); i++){
    String palindromeStr = list.get(i);

Note the spacing.

    for(int j = i+1;j<list.size();j++){
        palindromeStr = palindromeStr+list.get(j);

This is a pretty slow way of creating what

   String palindromeStr = str.substring(i, j);

could give you. By creating your string incrementally you gain nothing: Because of strings being immutable, their whole content gets copied on every step.

This way the complexity is O(n**3) and could be reduced(*) to O(n**2) by simply defining a method working on a substring like

 static boolean isPalindrome(String str, int start, int end) ...

You should improve both spacing (just press Ctrl-Shift-F in Eclipse) and naming, maybe as follows:

str -> input
strArray -> nothing, just inline it
palindromeSet -> palindromes as it's clearly a set
palindromeStr -> substring or candidate as it's not always a palindrome

Your naming is not really bad, but you concentrate on the type too much and I can imagine to get lost in a bunch of names like intListSetArray  and strDoubleMap without any clue what's the variable good for.

I'd bet there's a faster algorithm, but I haven't figured it out yet.

(*) I'm assuming that isPalindrome is O(1) on the average, which is true for normal strings, but not for e.g. "aaaa....a".


Multiple functions to establish a fallback value for a property until not null

This seems to be a textbook case for the null coalescing operator ??

Head = GetComponent<Camera>() ?? GetComponentInChildren<Camera>() ?? Camera.main;

You also (probably) don't need to prefix with this

Edit:

If the null coalescing operator doesn't work (which is a massive shame) why not create an extension method?

public static T IfNullThen<T>(this T obj, Func<T> factory) where T : class
{
    return obj != null ? obj : factory();
    // or
    // return obj == null ? factory() : obj;
}

then you can do:

Head = GetComponent<Camera>().IfNullThen(GetComponentInChildren<Camera>).IfNullThen(() => Camera.main);

Unfortunately I'm on my mac so I don't have a compiler but I think it should work :)


I see nothing wrong with the code itself, but you're in dire need of docstrings. Arcane functional one-liners like the one in intersperse are impenetrable unless they're well-documented. You'd also benefit from splitting that one into multiple lines.

For strings like this:

    return requests.get('https://api.github.com/repos/{}/{}/branches/master'.format(author, repo)).json()['commit']['commit']['tree']['sha']

consider rewriting your format call as an f-string; i.e.

f'https://api.github.com/repos/{author}/{repo}/branches/master'


Simplifying multiple mouseover and mouseout functions

Use an .each "loop":

var tooltips = $('.tooltip');

$('.remove').each(function(i) {
    var tooltip = tooltips.eq(i);

    $(this).on({
        mouseover: function() { tooltip.show(); },
        mouseout:  function() { tooltip.hide(); }
    });
});


Do not do using namespace std; This is a bad habbit that pollutes your namespace needlessly. You are only using std in exaclty 4 places. Its really easy to be better here.
Please use sensible names. Your t is the number of test runs, so name it numTests or something similar. In a month you will never know the meaning of a given variable.
Stay consistent in your code style. You have different styles of for loop. This is really confusing and quite frankly annoying to read.
The question is marked as c++ but you use plain old C here. Rather than a C-style array you should use a std::vector<int>
You are getting timeouts because you use a brute force approach. You should realize, that you can directly calulate the number of infomred people directly. At the first day it is a[0]. At the second day it is a[0] + a[0] + ... a[a[0]]. Consequently you can determine the number of newly informed people for every day just once and reuse that value.


Checking if a number is a perfect square by recursive sum of its digits

Your code works, as specified, but your specification is wrong.

Sometimes doing a code review involves fact-checking. In this case, your facts are wrong. What looked fishy to me, is the statement that:

  the recursive sum of digits of perfect squares is always 1,4,7 or 9

(well, I also checked that only perfect squares have an odd number of divisors - which is true).

What is the truth about the sum of digits? Well, it is true that all perfect squares have recursive digit sums that total 1, 4, 7, or 9, but the inverse is not true. This is obvious if you take the value 7, which is not a perfect square, but has the digit sum of 7.

When I looked around, I found this entertaining read: How to check if a number is a Perfect Square. It is quite clear that this is the second line of attack for checking whether a number is a perfect square. The first line is to check the last digit (which excludes 7, by the way).

Even once you have done (and passed) these two tests, all you can say is that the number is likely a perfect square. You still need to do the hard work to confirm it.

As an aside... why do you use recursion for the digit-sum. Something iterative would be great:

 long long iterativeSum(long long num){
     while(num >= 10){
        long long sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        num = sum;
     }
     return num;
  }


You can vectorize this at various points to apply arithmetic to the whole dataframe rather than row-by-row.
def min_euclidean(df, options):
    """ Returns the index of the series in iterable options for which df - row has minimum
    Euclidean distance """
    return pd.DataFrame(((df - series) ** 2).sum(axis=1, skipna=False) for series in options).idxmin()

def k_means(TE, k):
    iteration = 0
    epoch = 0
    tol = 1
    old_tol = 2
    tols = []
    start_time = time.time()
    mean_cl = [random.uniform(TE.min(), TE.max()) for _ in range(k)]
    o_a = min_euclidean(TE, mean_cl)
    while abs(old_tol - tol) > 0.005:
        old_tol = tol
        epoch += 1
        mean_cl = [TE[o_a == i].mean() for i in range(k)]
        n_a = min_euclidean(TE, mean_cl)
        iteration += len(TE)
        tol = (o_a != n_a).mean()
        tols.append(tol)
        o_a = n_a
    return time.time() - start_time, tols, n_a, iteration

Note that:

wherever possible we work with Pandas series or dataframes instead of lists
I calculate mean_cl as a list of Pandas series instead of a list of lists. This way we avoid iterating through the column or row indices of TE, which is slower. There might be some way to optimize this further by storing mean_cl as a dataframe, but I can't see an obvious way of working with it that way.
there is no need to take the square root for the Euclidean distance - the indices associated with minimal distance will be the same working with the squared values
o_a and n_a are also stored as series. We can then do (o_a!= n_a).mean() to calculate the disparity between them.
The biggest optimization here is probably the min_euclidean function which calculates the square difference for the entire dataframe in an optimized way, rather than iterating through it.

This may be a helpful explanation of vectorization. Working with Pandas series and dataframes in an optimal often involves a slightly different way of thinking than in regular Python.
EDIT: Here is a version using numpy instead of pandas. This fully vectorizes all the operations and is substantially faster again. It uses an optimization from this StackOverflow answer.
def k_means(TE, k):
    epoch = 0
    tol = 1
    old_tol = 2
    tols = []
    start_time = time.time()
    te = np.array(TE)
    rows, columns = te.shape
    te3 = te[:, np.newaxis]  # 3d version of te for calculating euclidean more easily
    k_range = np.arange(k)[:, np.newaxis]
    mean_cl = np.random.uniform(te.min(axis=0), te.max(axis=0), size=(k, columns))
    o_a = np.nanargmin(((te3 - mean_cl) ** 2).sum(axis=2), axis=1)
    while abs(old_tol - tol) > 0.005:
        old_tol = tol
        epoch += 1
        m = o_a == k_range     # masks for each value in range 0 to k-1
        mean_cl = m.dot(te) / m.sum(1, keepdims=True)
        n_a = np.nanargmin(((te3 - mean_cl) ** 2).sum(axis=2), axis=1)
        tol = (o_a != n_a).mean()
        tols.append(tol)
        o_a = n_a
    return time.time() - start_time, tols, n_a, epoch * rows


Benchmarking our LAMP servers with this php script

I'm not to good at optimizing, so I don't think I'm qualified to touch on that aspect.
So, formatting I guess,
One thing I can say though, is that your code is seriously lacking consistency. Some assignments ($mysqlserver = 'localhost';) you place spaces around operators and use single quotes, on some ($payload="";) it's the exact opposite! I suggest you choose a style, or a beautifier for that matter, and apply it to the whole script. It makes reading it, a lot easier. Also, please fix your indentation. Knowing which functions and clauses your closing brackets end is pretty important.
Now the code,
Why $_REQUEST? Are you expecting to receive input from the URL, other pages, and cookies? If so, you may skip this. If not, I suggest you choose between $_GET or $_POST to keep things specific.
How about this:
$n=rand(0,57)+65;
$payload = $payload.chr($n);

It really could be reduced to:
$c = rand(65, 122);
$payload .= chr($c);

I felt a "c" would be better than an "n", but really, variables should have some sort of context in them. So "$charCode" would be excellent. Hold off on fixing this though!
Now I don't feel qualified to critique the actual I/O code, so I'll leave that up to someone with more knowledge. From what I do know though, I can't see any glaring problems with your database queries that would cause it to be so slow. Hopefully some one with an eye keener than mine can help.

Now this:
$fname = chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).'.txt'

is very wet. What I mean by that is, we need to DRY it out a bit!
Head back up to the top, and let's make a nifty function:
function rand_char_str($length) {
    $returnString = "";
    for ($i = 0; $i < $length; $i++) {
        $returnString .= chr(rand(65, 122));
    }
    return $returnString;
}

Great! Now we can replace
for($i=0;$i<108000;$i++) //generate a big string
{
    $n=rand(0,57)+65;
    $payload = $payload.chr($n);
}

with
$payload = rand_char_str(108000);

We can also replace that $fname assignment with
$fname = rand_char_str(4) . ".txt";

Towards the end there, you have
$stmt = $mysqli->prepare('select t from temp limit 1');

and then a conditions checking the value of $stmt. You can just place the method call inside the conditional. This one's just nit-picking though!


Improving or replacing a long if statement


In this case I would clearly go with the more concise version 2.

In general it can improve readability to assign complex expressions to variables with meaningful names and I would always prefer this to adding a comment. However, in this case there is neither the necessity to add a comment nor is the variable name array very meaningful. Just the opposite: You have to decode the second line by looking up array one line above if you want to understand what's going on.

Personally I would shorten the code some more:

function count(string) {
    return string.split("").filter(e => e === "a").length
}

In my opinion, the name element doesn't add much information here, so you might as well write e or x. When variable scope is very short, these short names are fine. When you read this code, you will never wonder where the hell this variable e is coming from and what it means. It literally refers to something defined on the same line.


I know this question/post is old, but...

Use isinstance rather than directly storing and then checking the type() output.

We can get rid of t and two of your if statements to check type by using isinstance instead, and check against all three acceptable types:

if not (isinstance(n, (float, str, int))):
    raise ValueError('Parameter must be an int, str or float')

Just a thought on this, though: If something provided is not an int, str, or float, then it's an invalid type, and should raise a TypeError, rather than a ValueError, because TypeError is more generally used when you're passing an invalid object type into a function that can't handle it.  Therefore, your raise ValueError("...") for cases where the parameter is not an int, str, or float should probably be a TypeError with the same error message.

As was mentioned, isinstance will not behave right if you are using inherited classes which are subclasses of other primary classes.  However, consider that subclasses building upon other immutable classes are rare and as long as you aren't testing for instances of a bare object, this should suit your purposes.

The final code is this:

from typing import Union

def int_exact_cast(n: Union[int, float, str]) -> int:
    """
    Tries to cast parameter to int without losing decimal part or raise an exception
    :param Union[int, float] n: The value to be converted
    :type n: Union[int, float]
    :return: The converted int value
    :rtype: int
    :raises ValueError: raises ValueError exception if the parameter can't be casted exactly to int
    """

    if not (isinstance(n, (float, str, int))):
        raise ValueError('Parameter must be an int, str or float')

    f = float(n)

    if not f.is_integer():
        raise ValueError('Parameter contains a decimal part')

    return int(f)

Just keep in mind that if the string can't be converted to a number (such as if the string is 'I Am A Teapot'), then you get a different ValueError from the conversion system, because it's Not a Number.  (Which is why you don't need the NaN check with this method, but you have to be careful with what you're working with)


Extend number of arguments in std::hypot

First of all, let me just say that qsum is a really bad name for a generic hypot function. I would have called it... hypot! In fact, I'm going to do that in this answer, because it'll make the code a lot easier to read.

Well, I'll call it my_hypot, because we'll be including <cmath>, and I don't want any confusion over whether we're accidentally referring to the standard library's 2-argument hypot.

You have an anti-pattern in your code: you're writing things like T sum2(const T v) instead of T sum2(T v). The former is exactly equivalent to the latter as far as the caller of the function is concerned; but for the implementor of the function, the latter is strictly better:

It's less typing, and more importantly, less reading for the maintainer/reviewer.
It doesn't inhibit move semantics.
For these reasons, it's idiomatic C++; and therefore you should follow the idiom because breaking idioms for no reason is distracting to the maintainer/reviewer.

I think you could simplify your code by "thinking in C++17" and then working backwards to lower the resulting code back down to C++11.

In C++17, with fold-expressions, your function would be just

template<typename... Ts> constexpr auto my_hypot(Ts... vs) {
    return sqrt(( (vs * vs) + ... ));
}

In C++14, though, we don't have fold-expressions, so we're going to have to replace the construct (pattern + ...) with some kind of function call; say, sum(pattern...). So our C++14 code should look like

template<typename... Ts>
constexpr auto my_hypot(Ts... vs) {
    return sqrt(sum( (vs * vs)... ));
}

In C++11, we need to use the "trailing decltype" trick to get the compiler to accept that code, since C++11 can't deduce return types (except in lambdas).

template<typename... Ts>
constexpr auto my_hypot(Ts... vs) -> decltype(sqrt(sum( (vs * vs)... ))) {
    return sqrt(sum( (vs * vs)... ));
}

And there we go! Other than writing the sum function, this is a very straightforward translation of the code you want to write, into code that should be acceptable to a C++11 compiler.

However, I think your code as it stands is a bit sketchy, because of the overflow issue. my_hypot(65536, 65536, 1.0) should yield 92681.9, not undefined behavior! To mitigate that issue, I agree with you that casting all of the parameters to common_type would be a good idea. Let's implement that.

#include <cmath>
#include <iostream>
#include <type_traits>

template<typename CT> constexpr CT sum() { return {}; }

template<typename CT, typename T, typename... Ts>
constexpr CT sum(T v, Ts... vs)
{
    return v + sum<CT>(vs...);
}

template <typename... Ts>
constexpr auto my_hypot(Ts... vs) -> typename std::common_type<Ts...>::type
{
    using CT = typename std::common_type<Ts...>::type;
    return sqrt(sum<CT>( (CT(vs) * CT(vs))... ));
}

int main()
{
  std::cout << my_hypot(10., 10) << std::endl;
  std::cout << my_hypot(10, 10, 10.) << std::endl;
  std::cout << my_hypot(10, 10) << std::endl;
}

This is all the same straightforward code as before, with the possible exception of sum<CT>(). Here we're making an overload set of sum<CT>() (with no arguments) and sum<CT>(T, Ts...) (with at least one argument). By construction, both T and all the elements of Ts... will always be CT; we could static_assert that, if we wanted to. sum<CT>() returns a value-initialized CT (i.e., the "zero" of whatever type CT happens to be); I used {} instead of 0 just in case CT is some wacky bignum type that doesn't have an implicit conversion from int. Depending on your assumptions, 0 might be the safer choice.

The really nice thing about this code is that because we constructed it by starting with C++17 and moving backward, it's easy to take this code and migrate it forward to C++14 (by removing the trailing return types) and then to C++17 (by replacing the implementation of sum with a one-liner, or inlining it altogether) as your compiler catches up. Looking at your original code, I think it would be a little bit harder to disentangle the C++11isms from the "business logic" of how to compute hypot. For example, you've got the subexpression v * v repeated in two different places, for no good reason that I can see. You could have factored that out... or rather, not factored it in in the first place! :) Don't repeat yourself.


Docstring: You should include a docstring at the beginning of every method/class/module you write. This will help documentation identify what your code is supposed to do.
Simplify boolean comparison: Instead of evaluating if found == False, you should evaluate the variable itself, if not found:, since it contains a boolean value.
Simplify variable addition: Instead of doing x = x + 1, you should do x += 1, since it's more compact and easier to read. You switch between these two in your program, but it good to stay consistent with one practice.
Variable Naming: You did a good job of naming the variables snake_case, but the method names are lacking. This is a link to PEP-8 Naming Conventions, which can provide more insight.

Updated Code

"""
Module Docstring:
A description about your program goes here
"""

import random
import numpy as np

class Seats():
    """
    A class for containing an array of seats, finding seats,
    and counting good seats
    """
    def __init__(self, cs, ns):
        """
        Seats Class Init Method

        :param cs: The size of the grid of seats
        :param ns: The number of agents

        """
        self.cs = cs
        self.ns = ns
        self.seats = np.zeros([self.cs, self.cs], dtype=int)

    def found_seat(self):
        """
        Attempts to find an open seat in the array `self.seats`
        """
        found = False
        tries = 0
        while not found and tries <= 3:
            x = random.randint(0, self.cs)
            y = random.randint(0, self.cs)
            if self.seats[x][y] < 1:
                self.seats[x][y] = 1
                found = True
            else:
                tries += 1

    def good_seat(self, x, y):
        """
        Determines the amount of empty neighbors around the seat

        :param x: The X coordinate of the seat
        :param y: The Y coordinate of the seat

        """
        empty_neighbors = 0
        for neighbor_x in range(x - 1, x + 1):
            for neighbor_y in range(y - 1, y + 1):
                if self.seats[neighbor_x][neighbor_y] == 0:
                    empty_neighbors += 1


TapeEquilibrium Codility implementation not achieving 100%

Algorithm

Your algorithm works for input with only positive integers.
But it may not work with some input that contains negative numbers,
for example it gives incorrect result for:

[-1, 1, 1, -1, -2]

Why does it work for all positive numbers?

At any point in your loop, you basically have:

leftsum: the sum of elements on the left so far
leftnext: the next element on the left
rightsum: the sum of elements on the right so far
rightnext: the next element on the right

When you know that all remaining elements in the middle are non-negative,
then you can safely decide whether to take the left or the right,
by minimizing the difference between leftsum + leftnext and rightsum + rightnext.
This is safe, because all the remaining elements are non-negative,
therefore the difference can only shrink, or otherwise be minimal.

But when there can be negative numbers in the middle,
you don't have such knowledge,
and it can be impossible to decide which side to advance.

Consider this alternative that's simple and intuitively easy to understand,
and it's guaranteed to give correct result:

Set left to the first element
Set right to the total sum - left
Initialize mindiff to the absolute difference of left and right
Iterate from the 2nd element until the -1th: add to left and subtract from right and update mindiff (A quick tip for writing the loop: for value in A[1:-1]: ...)
return mindiff

Technique

It's strange you did from math import fabs when you don't need floating point math to solve this problem. You can use abs instead of fabs.

Instead of A.__len__() it's more natural to use len(A).


Regarding the problem of the error case where either the table or key is null in hash_code, you might pass in ht->size instead of ht, thus halving the problem.  If you redefine the 'contract' so that a NULL key is treated the same as an empty string "", then you no longer have an error case.

Some comments on the code:

I'd expect a short description of the nature of the hashtable and how it is used at the start.
INITIAL_VALUE and M should be const
function parameters should be const where possible
return values not stated in headers
I would omit things like 'Function which'... from comments.  If it is a function then this can be assumed.
hash_code uses -1 as an error code while set/rm_val use 0.  Inconsistent.
Generally, unsigned should be used for values that are not numeric, such as bitmaps, not for numbers that you don't intend to go negative (although size_t contradicts that).

create_table()

don't cast malloc return value
check malloc return
ht->buckets not initialised to 0; use calloc instead?
you could avoid the first malloc by passing in a pointer to a statically allocated HashTable or by defining the buckets array as a flexible member and then allocate the necessary total size

typedef struct HashTable {

 size_t size;
 char *buckets[];

} HashTable;

hash_code():

parameter ht: I'd pass in the size (ht->size) instead of ht.  In general, it is easier to test a function that takes simple scalar inputs than one that receives structures.
use of strlen in loop control is inefficient; key size does not change but will be evaluated each loop.  Perhaps for (; *key; ++key) {...}
prefer spaces after ';' in for-loop conditions
return hash % ht->size; loses precision (compiler warning due to type conversion).  Just use int throughout unless your hash is ever going to be big enough for the extra bit to matter.  If you thought it might get big enough (eg if using a processor where int is small) then you would have to check for overflow of an unsigned int too (I'm not suggesting you do that here).

get_val()

ignores -ve return from hash_code on error
last 4 lines reduce to return ht->buckets[hash];

set_val()

Better to return int, not unsigned int
hash is signed. Other uses are unsigned.
should val be duplicated (allocated)?  If not you have to tell the  caller that the string must be persistent (ie. the caller must not free it or pass a stack value).
else { return 0; } at the end of function can be reduced to return 0;
comment could be said to be excessive - describing what is obvious from the code; its first ',' should be '.'  I would say just: "Set hashtable value unless already set.  Returns 1 on success, 0 on failure (value already set)."

rm_val()

Better to return int, not unsigned int
ignores -ve return from hash_code on error
else { return 0; } at the end of function can be reduced to return 0;

main()

use EXIT_SUCCESS and EXIT_FAILURE


Iterating more smartly can simplify your loops.

To start with, run this standalone example and see that the izip(…) expression produces useful pairs of coordinates:

from itertools import product, izip
nRows, nColumns = 3, 5
for dest, src in izip(product(range(nRows - 1), range(nColumns)),
                      product(range(1, nRows), range(nColumns))):
    print(dest, src)

Then, you can reuse the loop just by changing which ranges you pass in.

from itertools import product, izip

def merge(direction):
    def merge(dest_iterator, src_iterator):
        for (dr, dc), (sr, sc) in izip(dest_iterator, src_iterator):
            if grid[dr][dc] == grid[sr][sc]:
                 grid[dr][dc] == 2 * grid[sr][sc]
                 grid[sr][sc] = 0
                 move(direction)

    if direction == "up":
        merge(product(range(nRows - 1), range(nColumns)),
              product(range(1, nRows), range(nColumns)))
    elif direction == "down":
        merge(product(range(1, nRows), range(nColumns)),
              product(range(nRows - 1), range(nColumns)))
    elif direction == "left":
        merge(product(range(nRows), range(nColumns - 1)),
              product(range(nRows), range(1, nColumns)))
    elif direction == "down":
        merge(product(range(nRows), range(1, nColumns)),
              product(range(nRows), range(nColumns - 1)))


To send the email on some given date and time

Use PDO, not mysql_* as they are deprecated and dangerous.
Break up your code into functions, this makes it easier to call and test.
Throw and catch exceptions.
You can omit the ending ?>

NOTE: This is untested code as I don't have the isdk.php file.

    <?php

    require('iSDK/src/isdk.php');

    $iSDK = new iSDK();

    try{
        checkConnection($iSDK);
        performQuery($iSDK, getDBConnection("", "", "", ""));
    } catch(RuntimeException $e){
        die($e->getMessage());
    }

    function checkConnection(&$iSDK){
        # Throw an exception if we don't have a connection, otherwise return true
        if (!$iSDK->cfgCon("connectionName")) {
            throw new RuntimeException('Could not obtain connection.');
        }
    }

    function performQuery(&$iSDK, $PDO){
        $sth = $PDO->prepare("SELECT * FROM `emails` WHERE `senddate` <= NOW()");
        $sth->setFetchMode(PDO::FETCH_ASSOC); # setting the fetch mode
        $sth->execute();

        while($row = $sth->fetch()) {
            $conDat = array('Email' => $row['email']);
            $conID = $iSDK->addCon($conDat);
            $clist = array($conID);
            $email = $iSDK->sendEmail($clist, 'kamranasadi431@gmail.com', '~Contact.Email~', 'ccAddresses', 'bccAddresses', 'contentType', 'JK', 'htmlBody', 'txtBody');
        }
    }

    function getDBConnection($host, $dbname, $user, $pass){
        try {
            return new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
        } catch(PDOException $e) {
            die($e->getMessage());
        }
    }


So here is my take on how I'd change it.
It might be over the top if the application is very simple and light, however, its how I'd rewrite it.

ExampleController

The actual implementation here would need to be updated, however this is to demonstrate how to use a new Service layer and passing in the repository.

public class ExampleController
{
    public JsonResult GetStops()
    {

        var loggingRepository = new LoggingRepository();
        var stops = new HeatMapService(loggingRepository);

        var heatMapViewModel = stops.GetMyHeatmap();

        return Json(stops.ToArray(), JsonRequestBehavior.AllowGet);

    }
}

HeatMapService

Firstly it's useful to have something to orchastrate the work, and so I'd add a HeatMapService.

public class HeatMapService
{

    private LoggingRepository LoggingRepository { get; set; }

    // Pass in the loggingRepository
    public HeatMapService(LoggingRepository loggingRepository)
    {
        LoggingRepository = loggingRepository;
    }

    // Have a service method, whos job it is to return the HeatmapViewModel for your use case
    public HeatmapViewModel GetMyHeatmap()
    {

        // We individually call the Repository for the first and last logs
        var firstLog = LoggingRepository.GetFirstLog();
        var lastLog = LoggingRepository.GetLasttLog();

        // We ask the entity to get the answer to the difference before and after midnight
        var firstDifference = firstLog.GetDifferenceAfterMidnight();
        var lastDifference = lastLog.GetDifferenceBeforeMidnight();

        // Finally we create a new HeatmapViewModel - using a factory method
        return HeatmapViewModel.CreateHeatMapFromTwoDifference(firstDifference, lastDifference);
    }

}

The Logging Model

Ask the model questions about the model

public class Logging
{
    // Id moved to the top, as this is assumed to be the unique id for this entity
    public int Id { get; set; }
    public string Imei { get; set; }
    public DateTime CurDateTime { get; set; }
    // Nullable<DateTime> replaced with more modern version DateTime?
    public DateTime? GPSDateTime2 { get; set; }
    public decimal? Latitude2 { get; set; }
    public decimal? Longitude2 { get; set; }
    public int Speed { get; set; }
    public int? Datatype { get; set; }

    // Get the difference after midnight, on the actual Model itself
    public int GetDifferenceAfterMidnight()
    {
        return (int)(this.CurDateTime - this.CurDateTime.Date).TotalMinutes;
    }

    // Get the difference before midnight, on the actual Model itself
    public int GetDifferenceBeforeMidnight()
    {
        return (int) (this.CurDateTime.Date.AddHours(23).AddMinutes(59) - this.CurDateTime).TotalMinutes;
    }

}

HeatmapViewModel

Create a new instance of HeatmapViewModel using a factory method, restricting how the model can be created.

Also note that the Properties are private set - so can only be set via the factory method (or via additional non-static methods).

public class HeatmapViewModel
{
    public int FirstStartDifference { get; private set; }
    public int LastStartDifference { get; private set; }
    public int Coeff => 2;
    public int Difference { get; private set; }

    // Just pass in your two ints to create a new HeatMapModel
    public static HeatmapViewModel CreateHeatMapFromTwoDifference(int firstStartDifference, int lastStartDifference)
    {
        return new HeatmapViewModel
        {
            FirstStartDifference = firstStartDifference,
            LastStartDifference = lastStartDifference
        };
    }
}

LoggingRepository

Simpify the repository methods, to just get the entries you need. Single Responsibilty - return individual log entries from the ctx

public class LoggingRepository {

    // Get the First Log
    public Logging GetFirstLog()
    {
        using (var ctx = new GoogleMapTutorialEntities())
        {

            var firstitem = ctx.Loggings.FirstOrDefault(x => x.Datatype == 2);
            return firstitem;
        }
    }

    // Get the Last Log
    public Logging GetLasttLog()
    {
        using (var ctx = new GoogleMapTutorialEntities())
        {

            var firstitem = ctx.Loggings.LastOrDefault(x => x.Datatype == 2);
            return firstitem;
        }
    }

}


Finding the second highest version using bash array script and clean up files

I think your approach is too complicated and esoteric with the use of BASH_REMATCH. Here goes my solution:

versions_to_keep=(
    $(find -maxdepth 1 ! -path . -type d -printf "%f\n"\
        | sort -n -t '_' -k 2 | sort -n -m -t '.' -k 2,3 | tail -n 2)
)
highest_version=${versions_to_keep[-1]}
second_highest_version=${versions_to_keep[-2]}
echo "The highest version is: ${highest_version:?}"
echo "The second highest version is: ${second_highest_version:?}"
find -maxdepth 1 ! -path . -type d ! -name "${highest_version}"\
    ! -name "${second_highest_version}" -exec rm -rf {} +

Explanation:

find -maxdepth 1 ! -path . -type d -printf "%f\n": find and print the basename of directories at most one level below and excluding the current directory .
sort -n -t '_' -k 2: sort in numerical order by field 2, fields delimited by _
sort -n -m -t '.' -k 2,3: sort in numerical order by fields 2 to 3, fields delimited by ., but take care to merge already sorted results
tail -n 2: output the last 2 lines
${highest_version:?} and ${second_highest_version:?}: if either of those variables is null or unset, print an error message and abort the script
find -maxdepth 1 ! -path . -type d ! -name "${highest_version}" ! -name "${second_highest_version}" -exec rm -rf {} +: find directories at most one level below the current directory whose basename patterns match neither ${highest_version} nor ${second_highest_version} and delete them

Actually, if you can guarantee the directory names are of the format XXX_a.b.c.d.TEST, you can combine the two sort into one:
sort -n -t '.' -k 1.5,3, which starts the sort at character position 5 in field 1 and ends the sort at field 3. If you only want to delete empty directories, you can replace -exec rm -rf {} + with -delete.


If you write uniq as a right fold, you don't need to pass an accumulator through, and the list comes out in the right order:

uniq :: Eq a => [a] -> [a]
uniq [] = []
uniq (x:xs) = (if x `elem` xs then id else (x:)) $ uniq xs

filt :: Show a => Num a => Read a => Eq a => Integral b => [a] -> b -> [a]
filt k is = uniq [i | i <- is, count i is >= k]

(Edit: Actually that one throws out the first of each two equal elements, not the last. Here`s one without that problem:

uniq :: Eq a => [a] -> [a]
uniq [] = []
uniq (x:xs) = x : uniq (filter (/=x) xs)

)

You've commendably already brought count into a form that allows it to be written in terms of library combinators:

count :: Eq a => Integral b => a -> [a] -> b
count e = sum . map (\a -> if a == e then 1 else 0)

That's a bit ugly due to lambdas though, here's a nicer version:

count e = length . filter (== e)

For separation of monadic and pure code (and generally for factoring out common code from across cases), here's a showList to replace printList:

showList :: Show a => [a] -> String
showList [] = "-1"
showList a = unwords [show i | i <- a]

Calling a monadic action a given number of times doesn't need manual recursion, and thus also doesn't need to give the repeated action a name:

main :: IO ()
main = do
  a <- readLn
  replicateM_ a $ do
    [_n, k] <- map read . words <$> getLine
    numbers <- map read . words <$> getLine
    putStrLn $ showList $ filt k numbers

(I think readNumbers doesn't deserve a name.)

In case the order in which the output is given isn't important, here's a version that doesn't require quadratic time because each element is compared to every other:

filt k = map head . filter ((>=k) . length) . group . sort

which relies on Data.Lists sort being faster than quadratic time.


Interface
Passing an array and then two indexes is a very C style of interface. In C++ it is much more common to pass two iterators. An iterator is a generalized form of pointer.
So rather than:
bool binary_search(int ar[], int low, int high, int key);

I would use:
template<typename I>
bool binary_search(I low, I high, int key);

Also rather than pointing at the first and last elements iterator ranges use a first and one past the last. This makes calculating sizes easier.
Code Review
Don't use >> 1 to represent a divide by 2. The point of high level code is to write it so that it is easy for humans to read. That is not obvious. Also the compiler can do these micro optimizations much better than you. So don't try and confuse it. Just write code in the most readable way possible.
Don't use sizeof(ar) / sizeof(ar[0]) it is so easy to break as array collapse into pointers at the drop of a hat. Use std::size() which works for arrays/containers but will fail to compile for pointers (which is what you want).
But if you switch to using Iterator based interface then you should use std::begin() and std::end().
Style
Your bracing style is uncommon. But not so egregious that I would complain about. Normally brace style is defined by a local style guide. So if you are in a compnany or project just check that.
 // Most common C++ styles
 if ()
 {
     Statement;
 }

 // or
 if () {
     Statement;
 }


Generate n appointments in the next m months

The essential part of your code is:

static LocalDate random(LocalDate start, int months, Random rnd) {
    LocalDate end = start.plusMonths(months);
    int days = (int) ChronoUnit.DAYS.between(start, end);
    return start.plusDays(rnd.nextInt(days + 1));
}

I have no idea why you need more code than this to express the idea.

I don't see any practical reason to use either the old and ugly java.util.Date or the even uglier java.util.Calendar or the inappropriate java.sql.Date (since this code has nothing to do with databases, let alone SQL). All you need are the classes from java.time, and java.time.temporal.


Using Array.join is unrelated to usage of async and await. Also note that the time it takes to call Array.join is insignificant in comparison to the time it takes to make the two API calls.

You can consider call1().then(data => call2(data)) roughly equivalent to const data = await call1(); call2(data). There's no (obvious) performance gain to be made here by using async/await over then. You would have a slight readability gain though. Note that your second call is dependent on your first call. When this is not the case you can get a performance improvement by making both calls simultaneously like so Promise.All([call1(), call2()]). That is not applicable here, but maybe this was what you had in mind?

The vast majority of the time here is spent waiting for the API calls. If you have ownership of the back end and want to improve performance, then I would suggest you consider creating a new endpoint that better fits your need so you only need to make one API call.

Also I prefer this._source !== undefined over typeof this._source !== 'undefined', but that's only if you're sure that this._source is declared.

In general I think this code looks fine.


Let's notice that
\$ n + x = n \oplus x \$  is true
when and only when
\$ n + x = n \vee x \$  is true

This is because
\$ n + x \geq  n \vee x = n \oplus x + n \wedge x \$.

Where:

\$ \vee \$ - bitwise OR
\$ \wedge \$ - bitwise AND

So we just need to calculate the number of zero bits in the \$n\$.
Let's calculate the nonzero bits:

private static int NumberOfSetBits(ulong i)
{
    i = i - ((i >> 1) & 0x5555555555555555UL);
    i = (i & 0x3333333333333333UL) + ((i >> 2) & 0x3333333333333333UL);
    return (int)(unchecked(((i + (i >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56);
}

The method above was copy-pasted from this answer: stackoverflow.com

Then rewrite the SumVsXoR method:

private static int SumVsXoR(ulong number)
{
    int numberOfBits = (int)Math.Log(number, 2) + 1;
    return 1 << (numberOfBits - NumberOfSetBits(number));
}


is there a more functionally idiomatic way of generating valid dates in f#?

One way to work around invalid dates is not to generate them in the first place: find the number of days between the boundary dates, generate a random integer from this range and then add that number of days to the start date:

let generateDate (min : Date) max =
    let totalDays = int (max - min).TotalDays
    let generatedDays = rnd.Next(0, totalDays)
    let generatedDate = min.AddDays(float generatedDays)
    generatedDate

let generateDateByYear minYear maxYear =
    generateDate (Date(minYear, 1, 1)) (Date(maxYear, 1, 1))

let generateBirthDate() = generateDateByYear 1904 1954

let sampleDobs = [for i in 1 .. 1000 -> generateBirthDate()]


Bash script to rename subfolder to include name of parent folder

You should always double-quote variables that are used as filesystem paths.
This is the same script but with variables correctly double-quoted:

# Parse through all show folders.
for show in /Users/sanjeetsuhag/Desktop/*; do
    # Check if it is a folder.
    if [ -d "$show" ]; then
        # Parse through all season folders.
        for season in "$show"/*; do
            # Check if it is a folder.
            if [ -d "$season" ]; then
                mv "$season" "$show/$(basename "$show") - $(basename "$season")"
            fi
        done
    fi
done

If you change the globs to end with /,
they will match only directories,
and so you can skip the directory checks:

for show in /Users/sanjeetsuhag/Desktop/*/; do
    for season in "$show"/*/; do
        mv "$season" "$show/$(basename "$show") - $(basename "$season")"
    done
done

You could further optimize this by using pattern substitution instead of basename:

for show in /Users/sanjeetsuhag/Desktop/*/; do
    for season in "$show"/*/; do
        show=${show%/}
        season=${season%/}
        mv "$season" "$show/${show##*/} - ${season##*/}"
    done
done

The ${show%/} is to shave off the trailing /,
and the ${show##*/} is to delete everything until the last /.

Finally, instead of hardcoding the base path /Users/sanjeetsuhag/Desktop,
the script would be more reusable if you make that a command line parameter of the script.


General advice:

Use enums instead of strings for board squares. This will protect you against mistakes like board[i] = "x".
A dictionary is overkill for a 3x3 board, you can just use an array. One benefit is that a bad index will throw an IndexOutOfRangeException, while a dictionary will not complain.
Board logic should be encapsulated in a class, so that you can make changes to your implementation (like switching from a dictionary to an array) without the rest of your code having to change. It will also allow you to guard against errors such as overwriting a non-empty board square.

To make the function easier to test:

Pass the board to the function, or make this a method of your Board class, instead of referring to GameBoard.Content.
Return an object representing the game state, instead of modifying private fields.

Together, it might look like this:

public static GameState GetGameState(Board board)
{
    foreach (var winningLine in WinningLines)
    {
        var line = new BoardState[]
        {
            board[winningLine[0]],
            board[winningLine[1]],
            board[winningLine[2]]
        };

        if (line.All(state => state == BoardState.Human))
        {
            return GameState.HumanWon(winningLine);
        }

        if (line.All(state => state == BoardState.Computer))
        {
            return GameState.ComputerWon(winningLine);
        }
    }

    return board.Any(state => state == BoardState.Empty)
        ? GameState.Unfinished
        : GameState.Tie;
}


Ruby function to capitalize all words in a string

You could make it a one liner. If you want to get fancy checkout Rail's implementation https://apidock.com/rails/v5.2.3/ActiveSupport/Inflector/titleize

str.split.map(&:capitalize).join(' ')


This is repeated for each column's width:

Columns("A:A").ColumnWidth

It could just be:

Columns("A").ColumnWidth

The code repeats this block of code almost verbatim twice in a row, with no change in the Selection:

With Selection
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlCenter
    .WrapText = False
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
End With

With the only difference being .VerticalAlignment = xlBottom (1st one) and .VerticalAlignment = xlCenter (2nd one).

You should be able to remove one of the two altogether and get identical results, as the 2nd one should overwrite changes made by the 1st one.

This repeats the same command with varying zoom levels:

ActiveWindow.Zoom = 90
ActiveWindow.Zoom = 80
ActiveWindow.Zoom = 70

I would say unless you need to see that is actually zooms progressively, just do ActiveWindow.Zoom = 70 by itself.


Your primes_sum function seems to be inspired by the sieve of Erathostenes, but there are a number of things in your implementation that don't work out too well:

Do not remove items from you num_list. That's an expensive operation which basically requires rewriting the whole list. Plus, it makes the following point impossible.
If you have a list of consecutive integers, and you know the position i of a number n, you do not need to do modulo operations to figure out its multiples. Instead, repeatedly add n to i. Addition is much cheaper than modulo.
You don't actually need to have a list of numbers: instead keep a list of boolean values, with their position in the list indicating the number they represent. Ideally this would be a bit array, for maximal memory saving. But a list of Python booleans will save you 4 or 8 bytes per entry already.

A very straightforward implementation of a sieve would look like:

def sum_primes(n):
    sieve = [False, False] + [True] * (n - 1)  # 0 and 1 not prime
    for number, is_prime in enumerate(sieve):
        if not is_prime:
            continue
        if number * number > n:
            break
        for not_a_prime in range(number * number, n+1, number): #If you use range(__, n, __), the function leaves the last Boolean in the sieve list as True, whether or not it is a prime. If you change it to range(__, n+1, __), this problem is taken care of.
            sieve[not_a_prime] = False
    return sum(num for num, is_prime in enumerate(sieve) if is_prime)

On my system this spits the answer for 2 * 10^6 in under a second, manages to get 2 * 10^7 in a few, and can even produce 2 * 10^8 in well under a minute.


Two implementations of website internationalization

Creating the translations table with an indefinite number of weirdly named columns is a bad idea. Subsequently adding a language will be awkward: it involves ALTERing the table, then a series of UPDATEs.

I suggest a table with normalization…

CREATE TABLE translations (
    id INTEGER NOT NULL,
    lang_id INTEGER NOT NULL,
    string VARCHAR(???),
    PRIMARY KEY (id, lang_id),
    FOREIGN KEY (lang_id) REFERENCES languages (id)
);

Then, for your programming convenience, create a view for each language that you support.

CREATE OR REPLACE VIEW en AS
    SELECT string
    FROM translations AS t
        JOIN languages AS l
            ON t.lang_id = l.id
    WHERE l.name = 'English';

Alternatively, define a stored procedure to satisfy your laziness.

That way, your schema stays normalized.  Adding a view is less risky than altering a table. Even your queries read better:

SELECT string FROM en WHERE id = ?;

However, for performance, I think you would be better off querying and caching all of the strings (probably a few hundred — no big deal) in PHP than issuing a separate query per string.


How to Improve This Program, Add Comments, etc.?

import dbm
import subprocess
import time
subprocess.call("clear")

This isn't cross-platform. Sadly, there isn't really a cross-platform alternative

try:
    # Tries to import cPickle, a faster implementation of pickle.
    import cPickle as pickle
except ImportError:
    import pickle

class PickleDB:
    def open_db(self):
        """Gets and opens the database"""
        self.db_name = input("Enter a database name\n")

You really shouldn't call input inside of a work class. The code responsible for User I/O should be separate from that doing any actual work.

        # Makes sure the database name is compatible
        db_parts = self.db_name.split(".")
        self.db_name = db_parts[0]

Ok, why are you ignoring part of the name if its not good? Shouldn't you complain to the user and ask for a new name? Also, I'd avoid assigning to self.db_name only the replace it again a bit later. Since you don't use it outside this function, I'd probably just have a local variable

        self.db = dbm.open(self.db_name, "n")

    def get_data(self):
        """Gets data to write into the database"""
        subprocess.call("clear")
        self.raw_data = input("Enter your raw data\n")
        # Pickles data

This comment is a little obvious, I'd delete it

        self.pickled_data = pickle.dumps(self.raw_data)

I'd expect a function that gets data to return it to the caller. Generally, functions that drop state onto the class is a sign of poor design. Methods should usually communicate by parameters and return values not object storage.

    def write_to_db(self):
        """Writes data into database"""
        # Logs time
        self.start = time.time()

Collecting timing information isn't something that's usually part of the actual class doing the work. Usually you'd time the class from the outside.

        # Creates keys
        self.db["raw"] = self.raw_data
        self.db["pickled"] = self.pickled_data

    def close_db(self):
        """Closes database"""
        self.db.close()
        # Logs end time
        self.end = time.time()

    def info(self):
        """Prints out info about the database"""
        subprocess.call("clear")
        print("Load data from database using dbm")
        print("Keys: raw\tpickled")
        # Prints total time
        print("Speed:", self.end - self.start, "seconds")

As noted, output and timing is usually something you want to do outside of the work class itself.

# Function calls
pickled_db = PickleDB()
pickled_db.open_db()
pickled_db.get_data()
pickled_db.write_to_db()
pickled_db.close_db()
pickled_db.info()

Here's the overall thing about your code. You are using a class as a group of functions and treating the object storage like a place to put global variables. You aren't making effective use of the class. In this case, you'd be better off to use a collection of functions than a class.


Calculate the percentage of sum of hash values

Ruby Hash

Rather than using a verbose case statement:

 case index
      when 0
        0.2
      when 1
        0.25
      when 2
        0.3

You could use a Hash:

rates = {0 => 0.2, 1 => 0.25, 2 => 0.3}

And the case can be replaced with:

rates[index]

Rubocop Report

Use symbols as procs when possible.

covers = covers.map { |x| x.to_sym }

This is a compact alternative:

covers = covers.map(&:to_sym)

Identify unused block arguments.

@quotes.select { |k,v| covers.include?(k) }

Use an underscore to identify unused block arguments:

@quotes.select { |k, _v| covers.include?(k) }

Numeric predicates should use predicate methods instead of comparison operators if possible

premium == 0 ? nil : premium

Use the predicate method zero instead:

premium.zero? ? nil : premium


Major

All 3 of your functions are linear (they do O(n) multiplications) while, in fact, only O(log(n)) is necessary:

(defun pow (x n)
  (if (minusp n)
      (/ (pow x (- n)))
      (multiple-value-bind (d r) (floor n 2)
        (let ((p (if (zerop d) 1 (pow x d))))
          (* p p (if (zerop r) 1 x))))))

In addition to much fewer multiplications, I am returning ratios for rational x.

Minor

Use minusp instead of comparison with 0.0 and (/ a) instead of (/ 1 a).


To see if an array has a specific index you should use array_key_exists rather than isset.

In case you want default values, how about just assigning all the defaults at the same time:

$foo = function_call();
$result = array('error' => (array_key_exists('error', $description) ? $description['error'] : ''), ...);


Flexibility

Your plugin relies on very specific markup; an element with an ID of fruitZoom having a first and last child element meant to be used as zoom in and zoom out buttons, respectively.

This is not flexible enough to be generally useful. What if you want multiple zoom controls on the page at once? What if you want to use a slider instead of buttons, or keyboard controls?

Naming and style

The identifier ele is not appropriate for a user-facing option name. The name elements would be an improvement. Better yet, use something more descriptive of what the value should to be, such as selector. After all, the user does not assign elements to this property, they assign a selector to it.

Your use of semicolons is inconsistent. Don't rely on automatic semicolon insertion in some places and not in others. Either terminate every statement with a semicolon, or only use them as separators in places where they are necessary. Pick a style and stick to it.

Behavior

This line here...

fontSize = $(defaults.ele).css("font-size")

...only gets the size of the first element matched by the ele selector. That means as soon as you zoom in or out, all elements matching your selector are resized to the size of the first element. You can see this in your own example code on JSFiddle; as soon as you zoom, the heading changes its size to match the first paragraph. This is probably not desirable behavior.

Redundancy

This block of code...

$("#fruitZoom :first-child").click(function () {
    fontSize = $(defaults.ele).css("font-size")
    $(defaults.ele).css("font-size", parseInt(fontSize) + 2);
    console.log(fontSize)
});

...is nearly identical to the next:

$("#fruitZoom :last-child").click(function () {
    fontSize = $(defaults.ele).css("font-size")
    $(defaults.ele).css("font-size", parseInt(fontSize) - 2);
    console.log(fontSize)
});

This is a sure sign that you should refactor your code to eliminate redundancy. Consider writing a named function, replacing the + 2 / - 2 part with + amount, where amount is a variable you pass in, having a value of 2 or negative 2.


Using a webservice with blocks and returning data via callback

Here is a way how I do it:

Create a class and name it like ClientApi. This class should be a singleton link and be absolutely independent. Also, create a class APIRouter which will return a path for a request. I'm using the AFNetworking framework for communication with different API etc. and JSONModel framework for mapping. Here you can find the full answer about network architecture in iOS apps.

@interface SFAPIClient ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation SFAPIClient

+ (instancetype)sharedInstance
{
    static id _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[[self class] alloc] init];
    });

    return _sharedInstance;
}

If a request should return some data, pass block as a parameter to the method:

- (void)getAllChildsWithCompletion:(void(^)(NSArray *arr, NSError *error))completion
{
    NSString *url = [SFAPIRouter childRoute];
    [self setupRequestSerializer];

    [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error = nil;
        NSArray *arr = //map respons

        if (!error)//if everything good call block with data
            completion(arr, nil);
        else
            completion(nil, error);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
        if (completion)
            completion(nil, error);
    }];
}

APIRouter:

static NSString * const kSFServerURL = @"http://0.0.0.0/api/v1";

@implementation SFAPIRouter

+ (NSString *)saveMediaToListRoute
{
    return [kSFServerURL stringByAppendingString:@"/childs"];
}

And then in controller call function from your ClientApi class:

//show activity indicator
[[SFAPIClient sharedInstance] getAllChildsWithCompletion:^(NSArray *arr, NSError *error){
//stop showing activity indicator

if (error)
{
//show alert
return;
}
//do what you need
}];