UI experience

Your menue text is hard to read and not intuitively clear. I'd prefer to see something like that:

     Console.WriteLine(
@"Choose to convert temperature values, enter a key please:\n
1 - Fahrenheit to Celsius
2 - Fahrenheit to Kelvin
3 - Celsius to Fahrenheit
4 - Celsius to Kelvin
5 - Kelvin to Fahrenheit
6 - Kelvin to Celsius, Press 6
> ");

Also outputting the text that way would make the code more readable.

Taking input from console

Your statements

 var YInput = Console.ReadLine();
 int iInput = Convert.ToInt32(YInput);

can be simplified to

 int iInput = Convert.ToInt32(Console.ReadLine());

consider to catch exceptions or use a String and TryParse() to check for invalid input.1

Rather use switch than if else cascades

You should replace

 if (iInput == 1)
          {
              var aAnswer = FtoCelsius(dInput);

              Console.WriteLine("The value of {0} degrees Fahrenheit is equall to {1} degrees Celsius", dInput, aAnswer);
          }
 else if (iInput == 2)
          {
              var bAnswer = FtoKelvin(dInput);

              Console.WriteLine("The value of {0} degrees Fahrenheit is equall to {1} degrees Kelvin", dInput, bAnswer);
          }

with

switch(iInput) {
case 1:
    var aAnswer = FtoCelsius(dInput);
    Console.WriteLine("The value of {0} degrees Fahrenheit is equall to {1} degrees Celsius", dInput, aAnswer);
    break;
case 2:
    var bAnswer = FtoKelvin(dInput);
    Console.WriteLine("The value of {0} degrees Fahrenheit is equall to {1} degrees Kelvin", dInput, bAnswer);
    break;
}

That makes your code more readable and concise.

Write generic code, if it's prone to be extended

At least I'd try to make all of that more generic, using a

public delegate double ConversionDelegate(double x);
Dictionary<Tuple<string,string>,ConversionDelegate) = {
    { {"Fahrenheit","Celsius"}, FtoCelsius } ,
    { {"Fahrenheit","Kelvin"}, FtoKelvin} ,
    // ...
    { {"Kelvin", "Celsius" }, KtoCelsius ,
};

dictionary pair. Where the tuple key serves the possible combinations of Fahrenheit to Celsius, Kelvin to Fahrenheit, etc. You can use the functions from Dictionary to match the key, and call the delegate and render the output accordingly.

The command line input should look like this then

> Enter temperature and <unit> <conversion unit>
> 39.5 celsius kelvin
> The value of 39.5 degrees celsius is equal to 312,65 degrees Kelvin

1)BTW you rather want to deal with double values IMO.


Finding the length of the number of paths in a matrix

Don't do using namespace std;.

void printPath() {

}

This empty function does not do anything, so better remove it to make the code cleaner.

// Print matrix to see contents
//  for(int i = 0; i < m; i++) {
//      for(int j = 0; j < n; j++) {
//          cout << matrix[i][j] << " ";
//      }
//      cout << endl;
//  }
//  cout << endl;

Commented code clutters the code and can confuse the reader. "Is it still needed? Then why is it commented out? If not, why is it still there?". Apparently it is not used anymore, and it also tells the reader nothing about the code, so better delete it.

// Specify the number of rows and columns of the matrix
int n = MATRIX_SIZE;
int m = MATRIX_SIZE;

The comment here should not be needed, because the code explains itself. Maybe it would be even more explicit if you named the variables rows and columns. If n and m do not change, and you have MATRIX_SIZE defined anyways, you could just use MATRIX_SIZE instead of the variables.

// Declare random number generator
mt19937 gen(10);
uniform_int_distribution<> dis(1, 1000000);

A more explicit variable name would make this comment obsolete. Less comments means less to read and makes the code easier to understand. Comments should tell the reader why the code does something, but the code should explain what it does itself. rng would be short and is a well known acronym for random number generator.


A few things here:

Comments:

Your comments are all compeletely useless.. nothing personal and no offense. That is a beginner-mistake. You don't need to comment everything.

Comments should explain the why and not the how or the what. Exceptions:

License comments
Documentation (python's docstring, java's javadoc, c#'s summary, ...)

Naming:

$con = //...
$query1 = //...
$assoc1 = //...

As opposed to what many people seem to think, source code characters are not costly. Spell it out:

$connection = //...
$userQuery = //...
$userRecord = //...

Formatting:

The convention is, to place subordinate blocks in a visually different place than surrounding code. This is usually done by indenting the block and putting it on a separate starting line

while($assoc1=mysqli_fetch_assoc($query1)){echo $assoc1['user'].'
';}

then becomes:

while ($userRecord = mysqli_fetch_assoc($userQuery)) {
    echo $userRecord['user'].'
';
}

This would definitely improve the readability of your code, as one line is not a whole loop! Putting too much on one line makes it extremely difficult to follow the thoughts behind your code and makes reading a pain.


type Node

I agree with you that this is too weakly typed.

type Lvl1
and Lvl2
and Lvl3

I don't like the naming here. The name Lvl2 doesn't really say much. Better names would be something like Namespace, Type and Member (or maybe TypeMember).

Choice<Lvl2, Lvl3, Constructor>

I think that constructor is logically a type member, just like a property or function. So I would make Constructor another case in the Lvl3 (or Member) union. I think making the model simpler is worth having the possibility of a constructor in an interface.

With that change, struct, class and interface look exactly the same, so I would refactor it further by combining the three cases into one (called something like ComplexType), and distinguishing between them by an additional field (something like ComplexTypeKind).

Also, I would encode the possibility of a nested type by adding a case to Lvl3 (a.k.a. Member). But if you keep your current design, you should remove Lvl2 from the Interface case, because interfaces can't have nested types.

System.Reflection.PropertyInfo

There is no need to repeat the namespace name, you can open it.

Property of string * System.Reflection.PropertyInfo

Why do you keep the name, when it's already accessible through the PropertyInfo? This question applies to most of your cases.


I don't care for empty quotes designating an empty string. It should be replaced with String.Empty. It simply clarifies your intention and leaves no ambiguity that you perhaps forgot to put something in the quotes, or maybe even meant to put a space in there. Otherwise, I feel this is very simple and solid.


In general, the code you have is neat, and easy to follow. The QuickSort algorithm is relatively traditional, and the pieces I expect to see are about where I expect them to be.

Let's go through the issues that I see though... and some of them are serious...

Namespaces

Using namespace::std is generally a poor idea. The possibility of namespace pollution is real. In fact, you have implemented a swap function and there already is one std::swap, but we'll get to that.

Style

You have a variable min, but this should be mid.
sometimes you put the function parameters with the left/right indices before the array, and sometimes after. You have:

void quicksort(int *arr, int left, int right) {

and you also have:

void swap(int i,int j, int *a) {

pick one, and stick with it. I would personally recommend putting the array first, and the indices afterwards.
Use whitespace appropriately. Operators like the << operator on cout are operators like any others. Use the space to improve readability:

cout<<"QS:"<<left<<","<<right<<"\n";

should be:

std::cout << "QS:" << left << "," << right << "\n";

Bugs

You have a few bugs in here which should be addressed:

There's the potential for integer overflow when calculating the mid point. This is a 'famous' bug. Your code int min = (left+right)/2; should be done as:

int mid = left + (right - left) / 2;

The above solution will not overflow.
You should, when partitioning the data, consider values equal to the pivot value, to be either left or right of the pivot. Your code you use  a strict < or > depending on whether you are on the right or left. One of those should include =. Your code, as it is, will run through the actual pivot value and do some funky business with it. You end up moving the pivot around in various ways.
You have a potential overrun (buffer overflow) in your loop conditions. It is posible, when you get to this line in the pivoting:

    while(arr[i]<pivot)
        i++;

for i to run off the end of the array. If all the remaining values are less than the pivot, there's nothing stopping it from going off. You still need to check against j in these loops.

Swap

C++ has a swap function, use it. To get it, from C++11 #include<utility> and before that #include<algorithm>

Algorithm

The classic quick-sort is done in 5 stages:

find a 'pivot value'.
move all values less than (or equal to) the pivot value to 'the left'.
move all values larger than the pivot to 'the right'.
quick-sort the values less than(or equal)
quick-sort the values larger than.

Note that many text books extract the first 3 stages in to a 'partitioning' function. The purpose of that function is to identify the pivot value, move the candidates around, and then insert the pivot value back in to the data at 'the right place'.

That last part is key, it leaves the pivot value in the exact place it is supposed to be. This means you never have to include that pivot value in the sorts again.

Let's break that logic down in to it's methods, then, with the assumption that' there's a 'pivoting' function that does the first 3 steps. That leavs a simpler quicksort that looks like:

void quicksort(int *arr, const int left, const int right){

    if (left >= right) {
        return;
    }

    int part = partition(arr, left, right);

    quicksort(arr, left, part - 1, sz);
    quicksort(arr, part + 1, right, sz);
}

Notice, in the above, that the check to make sure the inputs are valid are done on entry to the recursive function. This simplifies the last part of the function. The same code could, alternatively, be written similar to yours, as:

void quicksort(int *arr, const int left, const int right, const int sz){

    int part = partition(arr, left, right);
    std::cout << "QSC:" << left << "," << right << " part=" << part << "\n";
    print (arr, sz);

    if (left < part - 1) {
        quicksort(arr, left, part - 1, sz);
    }
    if (part + 1 < right) {
        quicksort(arr, part + 1, right, sz);
    }
}

I prefer the first.... it makes it more easy to spot the recursion terminator.

So, that's now a simpler quicksort, partition the data, sort each partition (but not the actual partitioning value which is in the right place).

How do you partition the data?

The trick here is to swap the pivot value to the front of the sequence, partition the rest of the values, and then swap the pivot value back to where it belongs:

int partition(int *arr, const int left, const int right) {
    const int mid = left + (right - left) / 2;
    const int pivot = arr[mid];
    // move the mid point value to the front.
    std::swap(arr[mid],arr[left]);
    int i = left + 1;
    int j = right;
    while (i <= j) {
        while(i <= j && arr[i] <= pivot) {
            i++;
        }

        while(i <= j && arr[j] > pivot) {
            j--;
        }

        if (i < j) {
            std::swap(arr[i], arr[j]);
        }
    }
    std::swap(arr[i - 1],arr[left]);
    return i - 1;
}

Note how the code above double-checks the buffer overflow?

Putting this all together, and leaving in some of the debug statements you have, I would have the code:

#include <iostream>
#include <algorithm>

void print(int *a, int n)
{
    int i = 0;
    while(i < n){
        std::cout << a[i] << ",";
        i++;
    }
    std::cout << "\n";
}

int partition(int *arr, const int left, const int right) {
    const int mid = left + (right - left) / 2;
    const int pivot = arr[mid];
    // move the mid point value to the front.
    std::swap(arr[mid],arr[left]);
    int i = left + 1;
    int j = right;
    while (i <= j) {
        while(i <= j && arr[i] <= pivot) {
            i++;
        }

        while(i <= j && arr[j] > pivot) {
            j--;
        }

        if (i < j) {
            std::swap(arr[i], arr[j]);
        }
    }
    std::swap(arr[i - 1],arr[left]);
    return i - 1;
}

void quicksort(int *arr, const int left, const int right, const int sz){

    if (left >= right) {
        return;
    }

    int part = partition(arr, left, right);
    std::cout << "QSC:" << left << "," << right << " part=" << part << "\n";
    print (arr, sz);

    quicksort(arr, left, part - 1, sz);
    quicksort(arr, part + 1, right, sz);
}

int main() {
    int arr[8] = {110, 5, 10,3 ,22, 100, 1, 23};
    int sz = sizeof(arr)/sizeof(arr[0]);
    print(arr, sz);
    quicksort(arr, 0, sz - 1, sz);
    print(arr, sz);
    return 0;
}

I have put this in ideone too.


Some style notes:

In Python, function names are snake_case, not PascalCase.
You should always put spaces around operators, for example for i in range(0, digits - 1) instead. (That example could be tightened to for i in range(digits - 1), as ranges implicitly start from 0.)
I'm not a big fan of the variable names num or num_digits. At the very least spell out the word "number" – characters are cheap.

Some more substantial suggestions:

There should be a docstring on your function. Right now, it's not clear what it's doing, or how I should use it. (I think it creates a number which complies to the Luhn formula, but I'm guessing.) Also, there are no comments. You should make it clear why you've written this code – explain how it relates back to Luhn's algorithm.
To save yourself an indentation level, I'd turn the if statement into an early return:

def Luhn(digits):
    if digits < 2:
        return
    # do rest of function

At the start of the function, you create a large N-digit number, convert to a string, then list, and then turn each list element into an integer. You can simplify this slightly:

num = random.randrange(10 ** (digits - 2), 10 ** (digits - 1))
num_digits = [int(digit) for digit in str(num)]

Note that this implementation precludes the returned number starting with 0. I don't know if that was intentional, but if it was, you should have a comment explaining why.

(Luhn's algorithm is generally used with identification numbers, not just base-10 integers, so it's quite plausible it could encounter a number whose first digit is 0.)
You can tidy up the if statement as follows:

range_start = digits % 2

I would also create a variable range_stop, which makes the level of abstraction in the range limits more consistent:

range_start = digits % 2
range_stop = math.ceil(digits + range_start - 1) / 2)

for i in range(range_start, range_stop):
    # do some stuff

Within the for loop, you have very similar repeated code. I'd pull out the index into a separate variable, and then you can cut down on repetition.

for i in range(range_start, range_stop):
    idx = 2 * i + digits % 2
    num_digits[idx] = 2 * num_digits[idx] % 9


Find all distinct palindromic sub-strings for a given string

Time complexity

Yes, your solution has a O(n^2) time complexity. As the output is n^2 where the input is n, achieving a better time complexity is impossible.

Look at the following code + output:

for i in range(1, 51):
    string = "a" * i
    permutations = list(palindrome_substrings("a"*i))
    print(len(string), len(permutations), len(permutations) /  float(len(string)))

(1, 1, 1.0)
(2, 3, 1.5)
(3, 6, 2.0)
(4, 10, 2.5)
(5, 15, 3.0)
(6, 21, 3.5)
(7, 28, 4.0)
(8, 36, 4.5)
(9, 45, 5.0)
(10, 55, 5.5)
(11, 66, 6.0)
(12, 78, 6.5)
(13, 91, 7.0)
(14, 105, 7.5)
(15, 120, 8.0)
(16, 136, 8.5)
(17, 153, 9.0)
(18, 171, 9.5)
(19, 190, 10.0)
(20, 210, 10.5)
(21, 231, 11.0)
(22, 253, 11.5)
(23, 276, 12.0)
(24, 300, 12.5)
(25, 325, 13.0)
(26, 351, 13.5)
(27, 378, 14.0)
(28, 406, 14.5)
(29, 435, 15.0)
(30, 465, 15.5)
(31, 496, 16.0)
(32, 528, 16.5)
(33, 561, 17.0)
(34, 595, 17.5)
(35, 630, 18.0)
(36, 666, 18.5)
(37, 703, 19.0)
(38, 741, 19.5)
(39, 780, 20.0)
(40, 820, 20.5)
(41, 861, 21.0)
(42, 903, 21.5)
(43, 946, 22.0)
(44, 990, 22.5)
(45, 1035, 23.0)
(46, 1081, 23.5)
(47, 1128, 24.0)
(48, 1176, 24.5)
(49, 1225, 25.0)
(50, 1275, 25.5)

As you can see, not only the output size grows with the input, the ratio between output size and input size grows too. This means that the time complexity is quadratic.

Generators and all

As far as the code is concerned, it is not Pythonic, it looks like C as it does not make use of generator expressions and built-ins like any or all.

def is_palindrome(word):
    return all(word[i] == word[-1*(i+1)] for i in xrange(len(word)//2))

I kept your way of looping and multiplying by -1, but now the code reads at a higher level: all the i-th chars must equal the (-1 * (i+1)) - th  chars. And the efficiency is the same as all short-circuites (aborts the computation as soon as it finds a counterexample.)

Separation of concerns

Getting the substrings of a string is interesting in its own right.Why am I forced to get only the palindrome ones? Make substrings a separate function.

Going one level deeper

You can actually nest the loops in the generator expression, getting the substrings of a string may be written as:

def substrings(string):
    return (string[i:j+1] for i in range(len(string)) for j in range(i, len(string)))

Or in a more imperative-looking (but equivalent) manner:

def substrings(string):
    for i in range(len(string)):
        for j in range(i, len(string))):
            yield string[i:j+1]

The final function

And getting the palindrome substrings is now very easy:

def palindrome_substrings(string):
    return (i for i in substrings(string) if is_palindrome(i))

Side note about names

Use long descriptive names, over cryptic abbreviations:

check_palin -> check_palindrome or following the is_ convention (boolean-returning functions should have a name starting with is_) is_palindrome
all_palindromes: What does all stand for? It stands for substrings so just write it like  that: -> palindrome_substrings

Bug fix

a is a palindrome, in general all single char strings are palindromes, so your code not returning them means it has a bug. My code rightly returns single char palindromes.


Your code has a couple of problems:

It is a void (synchronous) whose only task is to start a Task, lying to the caller since it's in fact an asynchronous Task.
You are using Task.Factory.StartNew instead of the preferred Task.Run

So, a better approach to this would be something like this:

private async Task testArrayConsuming()
{
    foreach (var x in arrayOfBlockingCollection)
    {
        await Task.Run(() =>
        {
            foreach (var y in x.GetConsumingEnumerable())
            {
                Console.WriteLine(x.Element.Value.ToString());
            }
        });
    }
}

This would block execution, consuming one x at a time. If you want this to be parallel, use this instead:

private async Task testArrayConsuming()
{
    var tasks = new List<Task>();
    foreach (var x in arrayOfBlockingCollection)
    {
        tasks.Add(Task.Run(() =>
        {
            foreach (var y in x.GetConsumingEnumerable())
            {
                Console.WriteLine(x.Element.Value.ToString());
            }
        }));
    }

    await Task.WhenAll(tasks); // wait for all of them
}


There is a simple way to calculate rolling averages in SQL, with a caveat.

SELECT CreationDate
     , Score
     , avg(CAST(Score AS FLOAT)) OVER (
         ORDER BY CreationDate
         ROWS BETWEEN ##RollingAvg:INT?10## PRECEDING AND CURRENT ROW
       ) AS RollingAvg
    FROM Posts
    WHERE PostTypeId = 2 AND OwnerUserId = ##UserId:INT##;

The problem with that is that a window that includes up to n preceding rows is one row larger than the window in your original query.  Unfortunately, SQL Server requires the window frame bound to be specified using an unsigned integer literal — it cannot be an expression.

That turns out to be the most annoying off-by-one error to fix:

DECLARE @UserId AS INT = ##UserId##;
DECLARE @RollingAvg AS INT = ##RollingAvg:INT?10##;

DECLARE @Sql AS NVARCHAR(1000) = 'SELECT CreationDate
     , Score
     , avg(CAST(Score AS FLOAT)) OVER (
         ORDER BY CreationDate
         ROWS BETWEEN ' + CAST(@RollingAvg - 1 AS VARCHAR) + ' PRECEDING AND CURRENT ROW
       ) AS RollingAvg
    FROM Posts
    WHERE PostTypeId = 2 AND OwnerUserId = ' + CAST(@UserId AS VARCHAR);

EXEC sp_executesql @Sql;

It's arguable that your original formulation, calculating the window average the "hard" way, is better than constructing the SQL dynamically to be EXECuted.

Of course, if you are willing to redefine the meaning of the window size parameter, then the window aggregate function would be the way to go.


Check if bit is only set once in a vector of int

Let me start by pointing out problems in your code:

Wrong type

The type of your global constant N is uint16_t. There are several problems with this:

as you are using cstdint the type should be std::uint16_t (because the C++ header provides them in the namespace std, this note should be applied to all instances of uint16_t in your code)
you are using N to indicate the size of the std::vector but sizes are specified using std::size_t
you are using uint16_t for the variables counter and ind, which are not related to the type. counter just counts, so you would be fine with std::size_t and ind is an index to a vector so it might be an std::size_t as well

Magic number

The loop boundary 16 in your code is related to the size of the type that is stored in the vector and offers possibilities for inconsistencies between the two. You should not rely on that, instead calculate it from the type:

int numberOfBitsPerEntry = sizeof(vec[0]) * CHAR_BIT;

And use that as loop boundary.

Variable names

While N is borderline (as soon as there are more then one containers it becomes ambiguous) the other variable names are not:

i is about as generic as it can get for a loop counter variable. What it actually does is signify the index of the bit you are currently looking at, so how about: bitIndex
ii just tells me that i was already taken and you temporarily forgot what was the next letter in the alphabet. This index actually walks through the std::vector's elements, so you might call it elementIndex (which is still too generic but I don't know what exactly is stored in the vector)
counter has already some information but it still does not inform you what is counted, how about enabledBitsCounter or if you take the notion of arranging your elements above each other so that the bits with the same index form a column: columnBitsCounter (in that light elementIndex might be named rowIndex)
ind (probably short for index) is just another generic name. It signifies the index of the element that is the only one that has a one bit in this column. columnWinnerRowIndex might be a bit too verbose but the general idea should be clear
vec does not say much about the contents. By staying in the table metaphor we might choose rows as the new name

This is C++

You are using printf in C++ where there are better alternatives (at least typesafety wise). Also you haven't included cstdio or stdio.h where printf comes from.

As it is C++ I would pledge for std::cout instead:

std::cout << bitIndex << " @ " << columnWinnerRowIndex << "\n";

Algorithm

Now to the algorithm itself. You need to walk through every column and look at each row so there is not much to change on the loops. (Besides the fact that auto might be overkill for int variables)

However, I find the loop break unnecessary (avoid changing the flow of loops from within the body) and the counter too heavyweight.

Basically there are 3 states for a column:
- 0 one bits
- 1 one bit
- too many one bits

This would fit nicely into an enum:

enum ColumnState {
    NO_ONE_BITS,
    ONE_ONE_BIT,
    TOO_MANY_ONE_BITS
};

Your counter is replaced with this:

    ColumnState columnState = NO_ONE_BITS;
    for(int rowIndex = 0; rowIndex < (int)rows.size() &&
                          columnState != TOO_MANY_ONE_BITS; ++rowIndex) {
        if(rows[rowIndex] & (1 << columnIndex)) {
            switch(columnState) {
            case NO_ONE_BITS:
                columnState = ONE_ONE_BIT;
                columnWinnerRowIndex = rowIndex;
                break;
            case ONE_ONE_BIT:
                columnState = TOO_MANY_ONE_BITS;
                break;
            default:
                assert(!"Invalid state");
            }
        }
    }

On second thought the enum looks too verbose and the main problem I had with the break was the counter++ == 1 part that is a bit mind bending. Reverting to a counter might be more readable:

    int columnBitsCounter = 0;
    for(int rowIndex = 0; rowIndex < (int)rows.size(); ++rowIndex) {
        if(rows[rowIndex] & (1 << columnIndex)) {
            ++columnBitsCounter;
            if(columnBitsCounter > 1) {
                break;
            }
             columnWinnerRowIndex = rowIndex;
        }
    }

Encapsulation

You might want to separate the logic of finding the column winners from the output code and the input. The signature of a function that allows this could be

std::vector<std::size_t> findRowWinners(const std::vector<std::uint16_t> &rows);

Where the result vector gives the winning row for each column or rows.size() if there is no winner in this column.


Correctness

  Also, all of the code works.

No, it doesn't, so let's start with that.

                 $username = mysqli_real_escape_string($conn, $_POST["username"]);

  ...

                 $result = mysqli_query($conn ,"SELECT * FROM users WHERE username='" . $username . "'");

                    if(mysqli_num_rows($result) > 0)
                    {
                    echo "Username exists . Try again
 ";
                    } else {

  ...

                       $stmt = $conn->prepare("INSERT INTO users (username, pw, email) VALUES(?, ?, ?)");
                       $stmt->bind_param("sss", $username, $pw, $email);

                      $username = $username;
                      $pw = $pw;
                      $email = $email;
                      $stmt->execute();

If the supplied username is such that mysqli_real_escape_string is not a no-op, the check for an existing user and the insertion of the user use different usernames. This is an important bug. Quite how important depends on things you haven't shown us, in particular on the database schema.

Given the current mix of database access techniques, you should ditch the one which requires you to escape things yourself (dangerous, because it's easy to forget when you change the code) and use prepared statements for everything.

I also struggle to see how this can possibly work:

//check if form is submitted
if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register']))
{
// looks like a hack, send to index.php
header('Location: index.php');
die();
}

  ...

                    } } } else{
            echo "The passwords do not match.";  // and send them back to registration page

If registration.php is the registration page then (a) it seems rather lacking in content; and (b) there seems to be a catch-22 with rendering it for the first time in order to submit data.

Maintainability

Maintainability is important in its own right, but also particularly relevant to  security because unmaintainable code is more likely to acquire bugs over time.

Fix the indentation. It currently appears to be at random, and is completely unreadable.

Avoid massive chains of if statements. The various checks here would be better refactored into a function which can take advantage of early return.

Avoid pointless code such as

                      $username = $username;
                      $pw = $pw;
                      $email = $email;

Security

This code leaks far too much information to a malicious caller.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

is absolutely not something you want to do on a production system unless you're also using set_error_handler to log it to somewhere private and ensure that the end user never sees the error messages.

Similarly

echo mysqli_error($conn);

The registration form asks for an e-mail address. Why? If you don't use it, don't ask for it. If you do use it, does your security model not require it to be correct? So shouldn't there be an e-mail validation step in the registration process?


Some general improvements:

Use <cstdlib>, not <stdlib.h>.  The latter is a deprecated header that is kept for C compatibility.  It should not be used in new C++ code.
Do not use void in an empty parameter list.  It is counterintuitive and is not necessary in C++ at all.  It is only used in C prototypes.
The copy constructor should take by const reference because it does not modify the argument.  Same for push.
You are using assignment in constructors when you ought to use member initializer clauses.  This is bad practice.
front should return by const reference, not by value.  Returning by value makes an unnecessary copy.
MAX_SIZE is not a macro and should not be in ALL_CAPS.  And it should be constexpr.  Or better, a template parameter.
It is advised in C++ to use std::array instead of raw arrays.

There are still many things to improve, but this should be enough to get you started.


There is a method in bitarray.util called ba2int:
from bitarray import bitarray
from bitarray.util import ba2int

ba = bitarray('1001')  # 9

i = ba2int(ba)

print(f'Value: {i} type: {type(i)}')
# Output: Value: 9 type: <class 'int'>

From the doc:

ba2int(bitarray, /, signed=False) -> int
Convert the given bitarray into an integer. The bit-endianness of the
bitarray is respected. signed indicates whether two's complement is
used to represent the integer.


Change size of elements until parent reaches certain height

It looks difficult to decypher indeed. Let's try it though. Some little bits which came to my mind at first glance:

I'd recommend using 4 spaces of indentation
maybe it's personnal taste but I would try not mixing jquery and vanilla js
as I understood, this keyword always refers to the same object, doesn't it? in that case maybe you could declare the selectors at the top of the function?

const thisElementId = get(this, 'elementId');
const selectorOwlDots = `#${thisElementId} .owl-carousel .owl-dots`;
const selectorButtonSpans = `#${thisElementId} div.owl-dots > button > span`;

declarations of const elCopy = el; are useless, just refer to el and rename it to something more meaningful
the handler of _waitFor should be declared as a function:

this._waitFor( selectorButtonSpans ).then( changeSizes ).catch( handleError );

function changeSizes() {
    ...
}

function handleError( err ) {
    ...
}

you can also simplify the initial exit condition a bit

let dotRowHeight = $(selectorOwlDots).height() || 25;
if ( dotRowHeight <= 25 ) {
    return;
}

you have two initial checks on dotRowHeight - I think you could reduce them to just one ( one is the one I simplified, the other is inside the _waitFor handler )

That should make the code a bit more readable BUT I think this code is doing the wrong thing altogether. The problem is - you are changing the size of elements in a loop until some condition is met. This is a bad practice - I've seen people ending up with infinite loops when doing such things. What I think you should do instead is:

read all the sizes you need
calculate sizes to apply to elements
apply sizes
if anything breaks - you do not have an infinite loop of elements jumping up and down on your page

Always try to minimize the number of interactions between your script and the UI.


Conditionally truncating a filename to a max length without damaging the file extension

Use early exit: reverse the null-checking conditional and return.

if(is_null($clientFilename))
    return;

If your code isn’t in a function, change that.

Next, use consistent indentation for the else: it belongs on the same level as the if, not as the content of the if.

I’d also encourage you to follow general usage in PHP, i.e. to use the braced if style even though I agree with you that the other style is fundamentally more readable.

I’d also get rid of unnecessary variables such as $clientFilenameLength, and of magic constants (255). And as a small clean-up, use string interpolation instead of concatenation where it makes sense.

That leaves us with:

define('MAX_LENGTH', 255);
$clientFilename  = $this->file->getClientOriginalName();
$clientExtension = $this->file->guessExtension();

// Assume a failure in reading client filename
$defFilename = $defRandFilename = uniqid('fid_', true);

if(is_null($clientFilename))
    return;

// Remove strlen($clientExtension) + 1 chars from the end
$hasClientExtension = !is_null($clientExtension);
$removeFromEnd = $hasClientExtension ? 1 + strlen($clientExtension) : 0;
$appendAtEnd = $hasClientExtension ? ".$clientExtension" : '';

if(strlen($clientFilename) > MAX_LENGTH)
    $defFilename = substr($clientFilename, 0, -$removeFromEnd) . $appendAtEnd;
else
    // User original upload name
    $defFilename  = $clientFilename;

if(strlen($defRandFilename) + $removeFromEnd > MAX_LENGTH)
    $defRandFilename = substr($defRandFilename, 0, -$removeFromEnd) . $appendAtEnd;
else
    // Use random file name plus .ext
    $defRandFilename .= $appendAtEnd;

But this code probably doesn’t do what you want: the whole check for strlen($clientFilename) is a red herring because the result will not be truncated. It will remove (a string of the length of) the client extension, and subsequently replace it. Is that really what you intended?


std::ostream wrapper for network logging device

You should not do this:

class device_ostream : public std::ostream {
public:
  device_ostream() : std::ostream(new device_buffer) {}

  ~device_ostream() {
    delete rdbuf();
  }
};

You do not know if the user of the class has reset the buffer while you were not watching.

device_ostream   data;
....
MyImprovedStreamBuffer   myBuffer;
data.rdbuf(&myBuffer);               // Your destructor will not play well with that.

I would make it an internal member.

class device_ostream : public std::ostream
{
    device_buffer   buffer;
  public:
    device_ostream()
        : std::ostream(nullptr)
    {
        rdbuf(&buffer);
    }
};

You should validate the return code of C functions.

fwrite(buffer_, 1, size_t(pptr() - pbase()), fp_);

Does not guarantee that it will write everything you asked for. Personally I would use a lower level write function so I can accurately check the error state and compensate accordingly.

std::size_t written = 0;
std::size_t size    = pptr() - pbase();

while(written != size)
{
    std::size output = write(fp_, buffer_ + written, size - written);
    if (output == -1)
    {
        if (errno == EINTR || errno == EAGAIN)
        {
             continue; // Ignore the error and try again.
        }
        // Something bad happened.
        abort(1); // or set the state of your stream to bad in
                  // some way (I used abort() simply because I am
                  // to lazy to look up what to do. (you should).
    }
    written += output;
}

The value returned by overflow is incorrect.

According to the specs:

  In case of success, the character put is returned, converted to a value of type int_type using member traits_type::to_int_type.
  Otherwise, it returns the end-of-file value (EOF) either if called with this value as argument c or to signal a failure (some implementations may throw an exception instead).

On success you return 0.

The value returned by sync is incorrect.

According to the specs:

  Returns zero, which indicates success.
  A value of -1 would indicate failure.

On failure you return EOF. Yes I get that it is -1. But your making assumptions. Follow specs to the letter.

Things like this scare me:

  else
    return EOF; // return EOF on device failure

I have been bitten a couple of times were macros expand to more than a single statement. Which renders the block incorrect. As a result I always use '{}' for sub blocks. I recommend it for everything it will prevent those impossible to find errors.

Since we now live in 2014 (nearly 2015). You should be using the modern version of the compiler. So add override to functions that override virtual functions.

int overflow(int ch = EOF)  override;
int sync()                  override;

Definitely worth overriding the method streamsize xsputn (const char* s, streamsize n);


Powershell script for zipping up old files

I spent several weeks writing and tuning a script that moves old files to a timestamped Zip file. Here are a few guidelines I learned that may help:

1) Move variables into script parameters so they can be changed at runtime without editing the file:

Param($File_Path = "C:\Users\Administrator\Downloads\Testing\*", #File path of file to be cleaned
  $Send_To = "C:\Users\Administrator\Documents\ARCHIVE2", #Location of ZIP file
  $Old_Files = "C:\Users\Administrator\Documents\OLD_FILES", #Location of old files before being zipped
  $Days = "-65"
)

2) Filter usually means 'criteria for filtering a list'.  Calling the list of files $Filter is misleading. $FilesToZip might be a better variable name.

3) There are lots of reasons a file can't be moved or zipped (in use, doesn't exist, no read/write permission, etc.) You should have a try-catch block around Compress-Archive to account for this, and fail or proceed gracefully. Using ZipFileExtensions, an error created an unusable file until it was finalized. Compress-Archive may be more robust, but there are still chances for failure (try pulling your network cable while creating a large archive of files on your LAN).

4) There's no need for an intermediate folder, and it creates more opportunities for failure. You can just compress the file into the zip and delete on success.

5) The message 'No old files found' is misleading. Reading it, I would think that there were no files found matching the age criteria, when it really means the intermediate folder doesn't exist.

6) Don't you need a .Zip file name for the -DestinationPath?

7) Write-Output is usually used for return values rather than messages. Write-verbose, or Write-Host are more appropriate for status messages.


Test cases right off the bat are a good sign. You only have one, but it is now easier to expand other conditions. I like to add in conditions for list has 0 elements and list is null. You'll be able to prove that those work, or if they don't work, prove that changing it didn't break anything.

Two of the methods use the word Reserve instead of Reverse: ReservseLinkedListTest and Reserve.

For a 15 minute code interview, I'd give it a passing grade.


The beginnings of a bootloader using GNU-based tools

Your code is well-commented. Other assembly answers on this site mention the importance of good comments: and yours are good.
An infinite loop at the end of the program is strange; instead I would have expected a ret or retf statement to return to the O/S shell which launched this program; but maybe that's different/excusable for what may in future evolve to become a boot-loader.
Writing to memory at 0xb8000 may or may not work depending on the current video mode. Here is a thread which discusses whether it's safe to assume 0xb8000 on computer startup (perhaps it is, but there are alternatives)
You code would be more compact (perhaps less readable) if you initialized entire words, instead of separate instructions for each byte; for example in the first program you could initialize ax and bx; and in the second program you could write 0x1E42 into the first word of video memory.
Using the 2nd method you'll probably start writing whole strings (not single characters) to the screen; the lods/stos/movs opcodes are useful for that. For example, you could do:

mov $0x1e, %ah # Write text attributes for the text right after
loop:
lodsb          # load byte from ds:si and increment si
cmp $0x00, %al # test for end-of-string
jz done
stosw          # store word (not byte) to es:di and increment di
jmp loop       # loop back to load-and-then-store next byte of the string
done:

For this kind of reason it's unconventional of you to use the ds register to point to video memory; I would have expected you to use the es register instead.
According to the GNU Assembler manual if you write %ds:0x00 then it will emit the ds prefix, which is unnecessary (I think that ds is the default segment for memory access); perhaps (based on the manual, I don't know) the syntax without the segment prefix is something like just 0x00 or perhaps 0x00(,1).

(I'm unable to give you feedback on the linker.ld section).


Any way of simplifying the following two short snippets regarding Dictionary?

Also an alternative:

if (!myList.ContainsKey(myKey))
{
    myList.Add(myKey, 0);
}
myList[myKey]++;


Pandas nested loop which checks if values from one series are in another series

Disclaimer, I am not the best at pandas, and I'm absolutely sure there is a far more readable way to accomplish this, but the following will rid you of your for loop and nested if statements, which are slower than vectorized numpy/pandas operations.

Your filter if 'MBTS' not in y won't work the way you think it will, at least, given the limited sample input, as y is a Series made from the column ser_one, not type. Let's assume that's an easy fix so in pseudocode it should be something like:

for x in df_one.ser_one:
    for y in df_two: # iterate through the rows so you get both columns
        if 'MBTS' not in y.type and x in y.ser_two:
            if 'L' not in y.ser_two:
                print(y)

This is a bit clunky, and pandas is great for vectorizing these sorts of operations, so let's filter it down to just Series operations. I'm working with a small part of your dataframes, so as a sanity check, they look like

df_one
     ser_one  type
0   VUMX1234  MBTS
1   VUMX6436  MBTS
2   VUMX5745  MBTS
3   VUMX5802  MBTS
4   VUMX8091  MBTS
5   VUMX1234  XXXX
6  VUMX1234L  XXXX

df_two
     ser_two
0   VUMX8091
1  VUMX8091L
2   VUMX1234
3  VUMX1234L
4   VUMX5838

I added a few entries that were non-MBTS to fit your problem.

The first bit, you want to find where 'MBTS' is not in df_one.type, but we want to filter the entire dataframe for that. df.loc will give you the rows that pass a given filter:

df_one.loc[df_one['type'] == 'MBTS']
    ser_one  type
0  VUMX1234  MBTS
1  VUMX6436  MBTS
2  VUMX5745  MBTS
3  VUMX5802  MBTS
4  VUMX8091  MBTS

# or
df_one.loc[df_one['type'] != 'MBTS']
     ser_one  type
5   VUMX1234  XXXX
6  VUMX1234L  XXXX

Now you can check if the results of ser_one are contained within ser_two, since the output of that previous check is a Series, like so:

df_one.loc[df_one['type'] != 'MBTS']['ser_one'].isin(df_two['ser_two'])
5    True
6    True

Just get the .loc back from that, and you should be left with two records in this example:

df_one.loc[df_one.loc[df_one['type'] != 'MBTS']['ser_one'].isin(df_two['ser_two']).index]
     ser_one  type
5   VUMX1234  XXXX
6  VUMX1234L  XXXX

It might be a bit easier to do the filtering against any ser_one that contains 'L' ahead of time:

df_one[~df_one['ser_one'].str.contains("L")]
    ser_one  type
0  VUMX1234  MBTS
1  VUMX6436  MBTS
2  VUMX5745  MBTS
3  VUMX5802  MBTS
4  VUMX8091  MBTS
5  VUMX1234  XXXX

Now, combining all of that into one big gigantic horrible expression

df_one.loc[df_one[~df_one['ser_one'].str.contains("L")].loc[df_one['type'] != 'MBTS']['ser_one'].isin(df_two['ser_two']).index]

    ser_one  type
5  VUMX1234  XXXX

The outer loc will take an array of index values as returned by the .index call near the end of the expression. The rest is just chained filters which are operations in native pandas, implemented in C and fast.


function $get(input) {
    return document.querySelectorAll(input);
}
function $grab(input) {
    return document.querySelector(input);
}

If I would like to get DOM elements from the page, its overhead to think about having 2 ways to get them and having 2 possible values to deal with. Best if you just deal with sets. If you just need one, it's as simple as the grabbing the set, and get one. No extra code needed.

var justOneDiv = $get('div')[0];

Speaking of sets and array-like objects, querySelectorAll returns a NodeList. It's like an array, but without the array methods. What you could do is to convert the NodeList into a real array. That way, you have instant access to array methods. This could be done with array.slice.

function toArray(arrayLike){
  return Array.prototype.slice.call(arrayLike);
}

function $get(selector){
  return toArray(document.querySelectorAll(selector));
}

// We have instant access to forEach
$get('div').forEach(function(div){
  div.style.color = 'red';
})

// We can use filter
$get('div').filter(function(div){
  return ~toArray(div.classList).indexOf('bold');
}).forEach(function(div){
  div.style.fontWeight= 'bold';
});
.red{
  color: red;
}

Red

Red

Red

Now we're almost like jQuery but jQuery takes it a bit further. It has the concept of a "jQuery object" which is a custom object that holds the set we're interested in, and has a prototype containing all the methods that operate on that set.

function $(selector){
  if(!(this instanceof $)) return new $(selector);
  this.set = this.find(selector);
}

$.prototype.find = function(selector){/* code that finds elements */};
$.prototype.insert = function(something){/* code that inserts something */};
$.prototype.each = function(callback){ this.set.forEach(callback} };

var div = $('div').each(function(div){/* do something */});

The above is a contrived example of how jQuery works. Adding methods is as easy as adding to the prototype (jQuery exposes it to the world as $.fn). This is how jQuery is so extensible in addition to just exposing one object to the global namespace.

var g = $make('button', {
    style:'float: left',
    class:'myClass',
    text:'Some text here',
    value:'myValue'
});

Still, text is the odd one here. Text are separate nodes, totally different from the element itself. They're essentially "children" of the element and not part of the element. I'd suggest you do something similar to jQuery's text() method. value is different because it is a legit property of some inputs.

Also, all your functions reside in the global scope. You risk clobbering other methods of the same name, or risk yours getting overridden. I suggest you take up just one name in the global scope and nest your methods under it. Mozart would be a good name.

var Mozart = {
  $get: function(){...},
  $remove: function(){...},
  ...
};

var divs = Mozart.get('div');


Mostly minor things, but could still be helpful:

Functions should generally be named in a verb form, so rename the function to something like calculate_binomial_coefficient().
This is a little hard to read:

if (r_mult / mult != r)

and could use more parenthesis for clarity:

if ((r_mult / mult) != r)

Consider using curly braces for these single-line conditional statements.  It could also help with avoiding some additional bugs, if you end up adding anything to them.
Since this is C++ and not C, use std::uint64_t.  Try to use all the equivalents that are found in the std namespace.


Compute the outputs of a generator in parallel

Here's a condensed illustration of how to achieve your stated purpose, namely
to compute the outputs of a generator in parallel. I offer it because
I could not understand the purpose of most of the complexity in your current
code. I suspect there are issues that you have not explained to us or that I
failed to infer (if so, this answer might be off the mark). In any case,
sometimes it helps to look at a problem in a simplified form to see
whether your actual use case might work just fine within those parameters.
import multiprocessing as mp

def main():
    for chunk in process_data(1000, 50):
        print()
        print(len(chunk), chunk)

def process_data(n, chunksize):
    # Set up the Pool using a context manager.
    # This relieves you of the hassle of join/close.
    with mp.Pool() as p:
        s = set()
        # Just iterate over the results as they come in.
        # No need to check for empty queues, etc.
        for res in p.imap(worker, source_gen(n)):
            s.update(res)
            if len(s) >= chunksize:
                yield s
                s = set()

def source_gen(n):
    # A data source that will yield N values.
    # To get the data in this example:
    # curl 'https://www.gutenberg.org/files/2600/2600-0.txt' -o war-peace.txt
    with open('war-peace.txt') as fh:
        for i, line in enumerate(fh):
            yield line
            if i >= n:
                break

def worker(line):
    # A single-argument worker function.
    # If you need multiple args, bundle them in tuple/dict/etc.
    return [word.lower() for word in line.split()]

if __name__ == "__main__":
    main()

This example illustrates a garden-variety type of parallelization:

The data source is running in a single process (the parent).

Downstream computation is
running in multiple child processes.

And final aggregation/reporting
is running in a single process (also the parent).

Behind the scenes, Pool.imap() is
using pickling and queues to shuttle data between processes. If your real
use case requires parallelizing data generation and/or reporting,
a different approach is needed.


From a short review, considering you are a beginner;

keep your variables in lowerCamelCase so

COLORS -> colors
CODES -> codes

on the whole, avoid to have data type in the variable name

colorArray -> colors

your commenting is quite good
Your indenting is inconsistent, it easier to read your code when code is properly indented
catchInvalid probably should return a boolean
I would have called catchInvalid -> isInvalidColor it gives more detail
catchInvalid should either use the global, or know the colors locally
I would use COLORS.includes() over COLORS.indexOf
There is way to calculate the return code without making a distinction between 1 or 2 elements

Per the comment, a bit more explicit
    function decodeColorValues(colors){
      //These are all the possible colors
      const knownColors = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"];

      //Functions should return a consistent datatypes, so I return -1 instead of a message
      //If the caller did not provide an aray but say "orange", then this will return -1 as well
      if(!colors.length){
        return -1;
      }

      //Filter out unknown colors
      colors = colors.filter(color => knownColors.includes(color));

      //If all colors were unknown then return -1
      //You could change this so that if 1 color is unknown it returns -1
      if(!colors.length){
        return -1;
      }

      //We only deal with the first 2 entries (why?)
      colors = colors.slice(0,2);
      let value=0;

      //Abuse the fact that 10 times zero is still zero
      for(const color of colors){
        value = value * 10 + knownColors.indexOf(color);
      }

      return value;
    }

    console.log(decodeColorValues(["blue"]),
                decodeColorValues(["nothing"]),
                decodeColorValues(["blue", "green"]),
                decodeColorValues(["blue", "nothing"])
           );


First attempt at generating prime numbers

First of all, there's a slight problem with your code. I get this output:

2, 3, 5, 5, 5, 7, 7, 7, 7, 7, 9

So it repeats quite a bit, and -- wait, 9 is not a prime number. Oops.

For, say, numbers up to 25, you'd get 21 instances of 23 in your array. And we'd get a 24 too, although that's not prime. We'll deal with that in a second.

The way your code runs, you don't need the labels (primes_loop and divisors_loop); when you continue or break you do so for the "closest" loop you're in. So simply writing continue with no label will skip to the next iteration of the outer (prime) loop, and break will break the inner (divisor) loop.

However, a label might be handy for a revised version that actually does find primes and only primes (of course, there are other, smarter approaches to all of this, but I'm just sticking to the code that was posted):

var primes = [],
    limit = 10,
    n, divisor;

outerLoop: for( n = 2 ; n <= limit ; n++ ) {
  for( divisor = 2 ; divisor < n ; divisor++ ) {
    if( n % divisor === 0 ) {
      continue outerLoop; // not a prime, try the next n
    }
  }
  primes.push(n); // if we made it all the way here, then n is prime
}

After that, you'll be left with a primes array that looks like this:

[ 2, 3, 5, 7 ]

No repetition, and no false positives.

Of course, it'd be nicer to wrap as a function:

function findPrimes(limit) {
  var primes = [], n, divisor;

  outerLoop: for( n = 2 ; n <= limit ; n++ ) {
    for( divisor = 2 ; divisor < n ; divisor++ ) {
      if( n % divisor === 0 ) {
        continue outerLoop;
      }
    }
    primes.push(n);
  }

  return primes;
}


To extend jQuery EACH I think it will confuse other developers especially during the maintenance period without you. To be better looping your collections you may need to use UnderscoreJS vs Lodash. They come with many useful collection functions.


Controllers for interacting with a vacation service

Should I create a new Controller for Insert?

Yes, and here's why. From a maintenance perspective, this is nightmare waiting to happen. The problem will start to appear when you want your popup used somewhere else independent of the list. However, if you bound your popup to the list controller, you can't move it out because you potentially bound the UI of the popup to some variable in the list controller.

The state of the popup should be independent of the list, thus you need to have a controller (or should I call it "view-model") for it.

As for your code:

I suggest you use the more standard then for promises instead of success and error. This makes it easier to swap out your promise libs/native promises when the time comes.
Use breakpoints to debug code instead of alert (or console or debugger). This prevents you from potentially leaving behind debugging code when you push to production.


You misspelled "movement" as "movment".

Typically (as per PEP-8), indentations are specified by one hard tab or four spaces, so you're good in that respect.

To be sure about formatting you can read up on PEP-8.

I am also wondering about _man. This doesn't seem to be displaying a man (but I haven't run it) so why name it that way? Also, epilepsy doesn't seem like a suitable name. Perhaps colored_box would be more formal?


I'll go out on a limb and say most senior developers would discourage any form of datetime arithmetic involving raw numbers rather than DateTime objects. There are a whole heap of problems you can avoid (leap years, leap seconds, timezone changes etc.) by always using datetime objects rather than timestamps. See for example Falsehoods programmers believe about time. In short, the potential for bugs completely outweighs the tiny memory savings.


Fetching translated strings, keeping in the philosophy of Zend framework

The two real questions are:

What are the advantages of having this in Zend_Registry?
What would you loose when using a helper function?

I believe the answers to these questions lead to this: use the helper function. This will:

save you a lot of typing,
highlight more importants parts of the code,
only add a tiny new layer of abstraction which is trivial to understand.

"Good design" is not about factories, registries, or whatever. It's about code that is easy to maintain and improve. The function is not going to make this any harder. If there's a translation error, the fix will stay the same: was the key correct? Is the stored translation correct? Still easy.


Collecting all relevant data from xlsm files

It's been a while since I wrote VBA, but I seem to remember Application.Calculation = xlCalculationManual often sped up my programs considerably. This prevents formulae from being evaluated while you're updating cell values, and can be reversed via Application.Calculation = xlCalculationAutomatic.


Checking HTTP headers with asyncio and aiohttp

IMO your code should look more like this:

import asyncio
import aiohttp
URLS = [...]

if __name__ == "__main__":
    print(
        asyncio.get_event_loop().run_until_complete(
            asyncio.gather(*(foo(url) for url in URLS))))

Where individual URL is processed something like:

async def foo(url):
    async with aiohttp.ClientSession() as s:
        async with s.head(...) as r:
            return url, r.headers[...]

Note separate session for each URL.

Additionally, exception handling may be needed, in which case, it should be encapsulated inside foo.


PySpark code that turns columns into rows

There is a function in the standard library to create closure for you: functools.partial. This mean you can focus on writting your function as naturally as possible and bother of binding parameters later on.

As for your function:

Don't explicitly increment a running index, use enumerate instead;
You can use zip to iterate over two iterables at the same time;
Prefer using a list-comprehension to using [] + for + append;
You can use next on an iterator to retrieve an element and advance it outside of a for loop;
Avoid wildcard imports, they clutter the namespace and may lead to name collisions.
Use an if __name__ == '__main__': guard for your top-level code.

Proposed improvements

from functools import partial

from pyspark.sql import spark, Row

def flatten_table(column_names, column_values):
    row = zip(column_names, column_values)
    _, key = next(row)  # Special casing retrieving the first column
    return [
        Row(Key=key, ColumnName=column, ColumnValue=value)
        for column, value in row
    ]

if __name__ == '__main__':
    sample = spark.read.format("csv").options(header='true', delimiter = ',').load("/FileStore/tables/sample.csv")
    sample.rdd.flatMap(partial(flatten_table, sample.columns)).toDF().show()


Here's few things to avoid "ugly" dups and long-long methods:

Don't duplicate variables

Like your mainContainer variable, because you used one variable for each fragment and pass it to another global variable:

postmainFragment = new Fragment_PostMain(); // global variable outside fragmentChange()
mainContainer = postmainFragment; // global variable outside fragmentChange()
...
postaccountFragment = new Fragment_PostAccount();
mainContainer = postaccountFragment;
...

It should be better to use just one variable, and you will avoid duplicate allocations:

Fragment mainContainer = null; // inside fragmentChange()
...
mainContainer = new Fragment_PostMain(); // directly set the fragment
...
mainContainer = new Fragment_PostAccount();

Therefore, you will not create global fragments variables for each fragments in parent class (postmainFragment, postaccountFragment, etc).

Use "switch" as @dacories said

You can do with Integers instead of Strings (it might be faster), for example:

private final static int FRAGMENTCHANGE_FADEIN = 0;
private final static int FRAGMENTCHANGE_FLIP_FORWARD = 1;
private final static int FRAGMENTCHANGE_FLIP_BACK= 2;
...
private void fragmentChange(Bundle data) {
    int transition = data[0];
    switch(transition) {
        case FRAGMENTCHANGE_FADEIN:
             ...
        case FRAGMENTCHANGE_FLIP_FORWARD:
             ...
    }
}

You can do the same for fragments...

Do a general method and avoid long-long switch

Instead of passing an array and switching between all your fragment in the fragmentChange method, you could pass directly the fragment concerned:

private void fragmentChange(Fragment frag, String tag, int transition) {
    if (frag != null) {
        ...
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        switch (transition) {
            default:
            case FRAGMENTCHANGE_FADEIN:
                ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
                break;
            case FRAGMENTCHANGE_FLIP_FORWARD:
                ft.setCustomAnimations(R.animator.card_flip_right_in,
                                    R.animator.card_flip_right_out);
                break;
            case FRAGMENTCHANGE_FLIP_BACK:
                ft.setCustomAnimations(R.animator.card_flip_left_in,
                                    R.animator.card_flip_left_out);
                break;
        }
        ft.replace(R.id.main_fragment, frag, tag).commit();
    }
}

So, you could directly call the change method as follows:

fragmentChange(new Fragment_PostMain(), "PostMain", 0);

You will in this case avoid a global fragment variable mainContainer which is constantly allocated in the whole class and avoid a very long switch or if/else condition.

But, if I want to pass datas to the next fragment?

One solution could be using static instance methods to pass datas with setArguments.
You could have an instance in fragment class to attach the datas and return just the fragment into the fragmentChange method.
An example might be in each fragment:

public static Fragment_PostMain newInstance(int i, String n, boolean b) {
    Fragment_PostMain frag = new Fragment_PostMain();
    Bundle datas = new Bundle();
    datas.putInt(i);
    datas.putString(n);
    datas.putBoolean(b);
    frag.setArguments(datas);
    return frag;
}

You could retrieve these datas with getArguments methods in fragment.
And call the method by passing the fragment with datas:

Fragment_PostMain frag = Fragment_PostMain.newInstance(12, "NameSection", true);
fragmentChange(frag, "PostMain", 0);

Like this, you won't have to create a Bundle array in the method.

Finally

Your solution with long-long if/else can be more readable with switch statement, yes. My solutions above will be more readable with less code, yes again.
However, you will have to think of what you really need: a long condition code (which can be easier to change in future if one fragment change for all class) or a short version (with class customization and direct access to the datas).
I hope this will help you.

Just an advice: in Java, the standard naming conventions is Classes should begin with an uppercase whereas methods with lowercase.


Accessing nested data properties in Handlebars

Kevin Decker (one of the contributors Handlebars on Github) answered on the GitHub issue I had created.

  The with form will be slightly faster than the generic block form due
  to some optimizations that can be made for known cases like that. You
  also have the option of making pathed lookups, {{amount.preTax}} for
  example. All work and unless you have extremely hot code I wouldn't
  worry too much about the performance of one vs. the other and leave to
  to which feels stylistically the best for you.

So I guess there is no real winner, unless as Kevin points out, you have an extremely used template then with might be a better option.


Finding the keys of map with the highest values (equality may occur)

To use streams you'd have to make the score part of the object (at least on an intermediate level) so that you can find the maximum based on the score.

Here's a little example based on a string/string map and String.length() as score replacement (as I don't have your original objects). Should be sufficient to illustrate the idea:

    Map<String, String> m = ...

    Map<Integer, List<Entry<String, String>>> intermediateByScore = m.entrySet().stream()
        .collect(Collectors.groupingBy(e -> e.getValue().length()));

    Entry<Integer, List<Entry<String, String>>> highest = intermediateByScore.entrySet().stream()
        .sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
        .findFirst()
        .get();

    Map<String, String> result = highest.getValue().stream()
        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

... or, after a few inlines of intermediate variables:

    Map<String, String> result = m.entrySet().stream()
        .collect(Collectors.groupingBy(e -> e.getValue().length()))
        .entrySet().stream()
        .sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
        .findFirst()
        .get().getValue().stream()
        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

Is this better than the loop: I don't personally think so. My advice: stick to your loop or revise your data structures to better support this approach.


I would suggest the following:

function combine_keys_with_arrays($keys, $arrays) {
    $results = array();

    foreach ($arrays as $subKey => $arr)
    {
       foreach ($keys as $index => $key)
       {
           $results[$key][$subKey] = $arr[$index];
       }
    }

    return $results;
}

$keys    = array('u1', 'u2', 'u3');
$names   = array('Bob', 'Fred', 'Joe');
$emails  = array('bob@mail.com', 'fred@mail.com', 'joe@mail.com');
$ids     = array(1,2,3);

combine_keys_with_arrays($keys, array('name'  => $names,
                                      'email' => $emails,
                                      'id'    => $ids));

The second parameter to the function can be built as you need it.  It avoids array shifting and variable arguments, but I think it should be pretty fast.


Clean code attempt at ATM problem on codechef.com

This looks quite readable and easy to follow.  I just have a few things that have stuck out to me:

It would not be good to use a floating-point type for currency, and it's especially worse for a more accurate type like a double.  For instance, you can wind up with a value like 0.0001, which is not an ideal value to deal with.  Unfortunately, C++ doesn't have a standard library to deal with this, such as Java's BigDecimal.  You need an integer type for this, which avoids these problems.

Refer to this, this and this for more info.  There are already many resources on this very topic.
Your "getters" should be const as they're not supposed to modify data members:

int getSomeMember() const {
    return someMember;
}

mMinDenominations should also be const for the same reason.  Initializer lists do also allow initialization of const members (be aware that constructors cannot do this).

Moreover, consider redesigning this to avoid getters.  They (and also setters) are generally bad for encapsulation as they expose implementation details.  You may not even need them here, either.
You can replace displayBalance() with an overload of operator<<:

friend std::ostream& operator<<(std::ostream& out, ATM const& obj) {
    return out << obj.mAccount.getBalance() << '\n';
}

Since mAccount is private, this will have to be defined within the class.  This will still work, even if you remove the getters.


Convert Persian and Arabic digits to English

Be nice to the maintenance programmer, even (especially?) if you expect it to be you. If you're mixing characters which are visually indistinguishable but don't need to be literal self-representations, you can use Unicode escapes and hexadecimal offsets as so:

convertNumbers2English: function (string) {
    return string.replace(/[\u0660-\u0669]/g, function (c) {
        return c.charCodeAt(0) - 0x0660;
    }).replace(/[\u06f0-\u06f9]/g, function (c) {
       return c.charCodeAt(0) - 0x06f0;
   });
}

Just that small change accomplishes the following:

I can easily see that I haven't missed any digits without having to count;
I can easily see that I haven't accidentally mixed digits from the two styles;
I can easily see that the offset subtracted is correct in each case;
I can easily see that the values returned by the anonymous functions are integers from 0 to 9 and not strings or codepoints corresponding to '0' to '9', which is useful if I'm not primarily a JS developer;
If I care about squeezing every last byte out of my JS, I can see a way to combine the two into one:

convertNumbers2English: function (string) {
    return string.replace(/[\u0660-\u0669\u06f0-\u06f9]/g, function (c) {
        return c.charCodeAt(0) & 0xf;
    });
}

The minimiser should take care of unescaping the Unicode escapes.
It might be slightly easier for me to find which characters they are, because I can look up the hex values in a Unicode character table.


Search for directories with a certain prefix that contain no files of a given type

Looks alright.

Your style is more spread out than is usually the case in ruby (though that's not necessarily a bad thing.) For example

is_num = num !~ /\D/
if is_num
  ...

could as well be one line sans assignments, without loosing clarity. if num !~ /\D/  # is a number

Instead of declaring nums to be a Hash, then having an if statement to check if a pair needs initialised with an array, you can just declare the hash with a block that it then uses to default all values to new arrays like so nums = Hash.new { |h,k| h[k] = [] }.

Instead of iterating through the array v of sorted nums and pushing each item to result, you can just do result.concat v. Sometimes for simple logic, denser one liners are arguably easier to read in ruby: e.g. nums.sort.each { |k, v| result.concat v }

Be aware that you can initialise arrays and hashes as literals, e.g. a = [] and this is sometimes prefered.

Your level of commenting seems appropriate to me, i.e. explaining what the code is meant to do (or why but not how) when it's not obvious from the code itself.


Count "Word Order" with further optimization

TLE

You're probably getting a TLE because,

if value not in array:

Is a O(N) operation meaning it has to traverse the entire array (worst case) to check if the value exists in the array

I can understand why you felt the need to have an extra array, because of dictionaries are not ordered.

But you can make use of the collections.OrderedDict module, to have an ordered dictionary!

Other

join!

print(*(i for i in elements.values()), end=' ')

This can be done cleaner with joining the values instead of unpacking

print(" ".join(map(str, e.values())))

Counter

Python is often described as batteries included,

Your element dictionary is the same the collections.Counter

Code

We can make an OrderedCounter class to combine these two and make get the most out of the included modules.

from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

c = OrderedCounter(input() for _ in range(int(input())))
print(len(c))
print(" ".join(map(str, c.values())))


It could be made more functional by avoiding the mutation of acc. The effects are contained within judgeCircle so it's not a big deal, but it feels like if you're going to mutate the accumulator, you might as well just use an imperative loop.

I also preferred to be explicit about the final check. I find the intent of !h && !v isn't quite as clear as h == 0 && v == 0;.

I ended up with:

const judgeCircle3 = moves => {
  const [hori, vert] = [...moves].reduce(([h, v], move) => {
    switch(move) {
      case "U":
        return [h, v + 1];

      case "D":
        return [h, v - 1];

      case "R":
        return [h + 1, v];

      case "L":
        return [h - 1, v];
    }

  }, [0, 0]);

  return hori == 0 && vert == 0;
};

The need for the switch here is unfortunate, but the only other alternative I could think of was some mess where a you'd do a lookup on a map which returned a function that returned a "altered" accumulator state.

I also got rid of the default since it didn't seem to be doing anything. You could have done error handling in there (and should in most cases), but if it's a challenge with predefined input, that's probably not necessary unless it's part of the challenge.


General

You should reconsider the naming of some methods. For example,

interface IComparable
{
    public function equals($obj);
}

is more clear about what it really does (comments are omitted to save space; of course, proper DocBlock comments should always be included with your code). This way, you can easily add other methods like isLessThan, isGreaterOrEqual, and so on. A method named compareTo as in

$a->compareTo($b)

I'd expect to be a valid callback for usort, thus returning -1 on $a < $b, 0 on $a == $b, or 1 on $a > $b.

Cart

One day, you might want to store your cart items in a database, so using $_SESSION directly is not optimal. I'd define a cart interface:

interface ICart
{
    public function add(IComparable $obj);
    public function remove(IComparable $obj);
    public function getQuantity(IComparable $obj);
    public function setQuantity(IComparable $obj, $qty);
    public function isEmpty();
    public function getAll();
    public function clear();
}

class Cart implements ICart
{
    const IDENTIFIER = '_CART_';
    protected $container;

    public function __construct(&$container = null)
    {
        if (is_null($container)) {
            if (session_id() == '') {
                session_start();
            }
            if (!isset($_SESSION[self::IDENTIFIER])) {
                $_SESSION[self::IDENTIFIER] = array();
            }
            $container = &$_SESSION[self::IDENTIFIER];
        }
        $this->container = &$container;
    }
}

With this approach, you can always build other cart implementations, like a database-aware one. The Cart class can be provided with an array, which will be used to store the data. If you want, you can pass in the $_SESSION superglobal directly, or use any other array. If omitted, a kind of namespace within the session variables (self::IDENTIFIER, '_CART_') is used to store the data.

Since the session - if needed - is started within the constructor, you can rely on its existence in the subsequent methods. BTW: the existence of the $_SESSION array does not guarantee that a session has been started! Use session_id() to check that instead.)

Internal Data Structure

Since your data array can be accessed from outside the cart, the current data structure is prone to get out of sync. It is more robust to swap the indices. Then you can replace getIndex() with getEntry(), which makes the handling much easier.

class Cart implements ICart
{
    ... // see above

    public function add(IComparable $obj)
    {
        $entry = &$this->getEntry($obj);
        $entry['quantity']++;

        return $entry['quantity'];
    }

    public function remove(IComparable $obj)
    {
        $entry = &$this->getEntry($obj);
        $entry['quantity'] = max(0, --$entry['quantity']);

        return $entry['quantity'];
    }

    public function getQuantity(IComparable $obj)
    {
        $entry = &$this->getEntry($obj);
        return $entry['quantity'];
    }

    public function setQuantity(IComparable $obj, $qty)
    {
        $entry = &$this->getEntry($obj);
        if ($entry['quantity'] > 0) {
            $entry['quantity'] = (int) $qty;
        }
        return $entry['quantity'];
    }

    public function isEmpty()
    {
        $total = 0;
        foreach ($this->container as $entry) {
            $total += $entry['quantity'];
        }
        return $total <= 0;
    }

    public function getAll()
    {
        $cart = array();
        foreach ($this->container as $entry) {
            if ($entry['quantity'] > 0) {
                $cart[] = $entry;
            }
        }
        return $cart;
    }

    public function clear()
    {
        $this->container = array();
    }

    private function &getEntry(IComparable $obj)
    {
        foreach ($this->container as &$entry) {
            if ($obj->equals($entry['item'])) {
                return $entry;
            }
        }
        $entry = array(
            'item' => $obj,
            'quantity' => 0
        );
        $this->container[] = &$entry;
        return $entry;
    }
}

As you can see, all methods (excl. isEmpty()) become much simpler.


These two declarations are useless:

  var lowestDiff;
  var closestRate;

As you re-declare them later:

  var currentRate = data.renditions[0].encodingRate;
  var lowestDiff = Math.abs(currentRate - targetRate);

And, on that note, you shouldn't use the var keyword when you reference an already defined variable. However, in this case, the first block can be removed, making the second block the variable declaration.

The following block can be simplified:

  $.each (data.renditions, function(id, rendition){
    var newItem = {
      file: rendition.url,
      label: Math.round(rendition.encodingRate / 1000) + ' Kbps'
    }

    // Set default rendition
    if (rendition.encodingRate == closestRate) {
      newItem["default"] = true;
    }

    sources.push(newItem);

  });

into the following:

  $.each(data.renditions, function(id, rendition){
    sources.push({
      file: rendition.url,
      label: Math.round(rendition.encodingRate / 1000) + ' Kbps',
      default: (rendition.encodingRate == closestRate)
    });
  });

  How can I be sure buildSourcesFromBrighcoveID is completed before doing anything else? I currently run the function that builds the player from within the first function to be sure the Ajax completed, but I would like them to be independent.

You should make the function a promise and use a done callback to ensure the function has been completed successfully before continuing. Read this Stack Overflow question for more information.

  Could I build the sources array in a more efficient way? I am currently iterating the renditions 3 times (to sort, to search for the best rendition and to build the sources array).

Each loop does a different thing, so I'm not 100% sure whether they can be slimmed.


What you are trying to archive is very similar to the BlockingCollection. Note that you can look at the .net framework's source code to get an idea how to implement it professionally ;).

The overall implementation seems to work and I think the blocking mechanism does what it is supposed to.

However, some points to note:

Do not use the instance of the buffer as synchronization object (Monitor.Enter(this);) because the object can be locked by someone else from outside... Create a private sync object instead.
In method Read, the temporary variable val is not required - just return the value.
I would rename the class to make clear, that the call of Write may block the current thread (maybe BlockingBuffer, BlockingStack or something like that).
Why not making the class generic?


Forcing type-safe IDs for use with Collections and Maps

Do not use floating point numbers as IDs! Floating point is a horrible minefield of gotchas out there to sabotage your program in subtle ways: Losing precision, imprecise equality, NaNs, …. Using a double only defers, but not solves these issues.

For IDs, always use an integral type like long.

Now you've found a sufficiently elegant solution to represent typesafe IDs by using generics. There are a few other possibilities you might want to consider:

Lazy self-loading classes. Each instance has a boolean field initialized which defaults to false. In each public method you put in a if (!initialized) this.initialize() test to load the other fields – but only when they are needed.

Usage example:

class LazyThing {
    private boolean initialized = false;
    ... // state that is loaded lazily

    private void initialize() {
        ... // initialization code
        initialized = true;
    }

    public void frobnicate() {
        if (! initialized) initialize();
        ...
    }
}

The advantage here is that this pattern is completely invisible to the user.
A Deferred<T> wrapper which is basically a “promise” or “future” (or any other single-element monad-like container of your choice). A deferral wrapper represents an object that may or may not be fully loaded. You can get() the element to force loading. This is a bit more awkward to use but properly separates the lazy loading from the wrapped type. The full interface might look like:

abstract class Deferred<T> {
  boolean initialized = false;
  T instance;

  abstract T initialize();  // sadly, Java does not have traits

  public T get() {
    if (! initialized) {
      instance = initialize();
      initialized = true;
    }
    return instance;
  }
}

Usage example:

Deferred<Thing> foo = new Deferred<Thing>() {
  private long id;

  // anon classes can't have constructors :(
  Deferred<Thing> init(long id) {
    this.id = id;
    return this;
  }

  @Override
  Thing initialize() {
    ... // code to load the instance
  }
}.init(1234);

foo.get().frobnicate();

This scheme is extremely flexible because it does not assume the existence or type of an ID.


1. You can add some comments !

2. In my opinion you should create another struct that will be named like linked_list_t which will have two pointers, node_t * start ,node_t* end.In terms of efficiency, by doing this, you don't have to iterate all the list on add_at_end to add a single node (this is a common practice when you create a linked_list)

3. When you malloc you can check the returned pointer and if it is NULL you should perror() the message.

4. The code

typedef struct node {
    int data;
    struct node * next;
} node_t;

void print_list(node_t * head);
void push(node_t ** head, int data);
int pop(node_t ** head);
int add_at_end(node_t ** head, int data);
int remove_last(node_t * head);
int add_at_index(node_t ** head, int n, int data);
int remove_by_index(node_t ** head, int n);

should be put on a header file as it just contains declarations

5. Use Sentinel Nodes in order not to iterate on int remove_last(node_t *)


You could be saving important variables that are being used frequently in the register like the following:

register const unsigned int targetWidth

Make sure memory accesses are cache-optimized, i.e. clumped together.

Investigate if signed/unsigned for integer operations have performance costs on your platform.

Investigate if look-up tables rather than computations gain you anything (but these can blow the caches, so be careful).

Even though you've already avoided floats I'm going to post this anyway:
If you can avoid double and float variables, use int. On most architectures, int would be test faster type for computations because of the memory model. You can still achieve decent precision by simply shifting your units like you've been doing (ie use 1026 as int instead of 1.026 as double or float).

And, of course, do lots of profiling and measurements.


You are in dire need of a lookup table. What you want to do is define a mapping somewhere else, and then just percent-encode all characters you have mapped. This gets rid of that unwieldy, huge and btw. hacky switch-statement.

consider the following:

StringBuilder sb = new StringBuilder(toEncode.length());
for (Character c : toEncode.toCharArray()) {
    if (MAPPING.containsKey(c)) {
       sb.append(MAPPING.get(c));
    } else {
       sb.append(c);
    }
}

This should be equally fast, if not faster. Also it makes use of a MAPPING you can change, without significantly affecting how this method works. btw. I am prespecifying the StringBuilder's capacity, since it's more efficient when the backing collection in there does not need to be resized too often.

Oh and another thing. Your switch-case only works by sheer luck. continue; is not the correct keyword to use there, instead you should rely on break; that allows you to add more work in the loop body, which is currently more or less impossible.


Check return values

You're not making sure fopen isn't failing when opening a file:

f = fopen(filename, "r");

Also check the return value of fread for failure:

  The total number of elements successfully read is returned. If this
  number differs from the count parameter, either a reading error
  occurred or the end-of-file was reached while reading. In both cases,
  the proper indicator is set, which can be checked with ferror and
  feof, respectively. If either size or count is zero, the function
  returns zero and both the stream state and the content pointed by ptr
  remain unchanged. size_t is an unsigned integral type.

const parameters

The function should never modify the contents of the string filename, so declaring the parameter const char *filename is good practice.

How does read_file signal a failure

You're asserting on realloc failure. I usually prefer returning gracefully even on alloc failures and leave it open to the caller to be able to cope and at least shutdown nicely. But that is not necessary in all cases.

However, touching the same area is how the read_file function signals a failure to it's caller? One way would be:

struct file_data fd = {NULL, 0};
return fd;

Or changing the function to:

int read_file(const char *filename, struct file_data *fd)
{
     assert(fd);
     ...
     fd->data = data;
     fd->numChars = totalChars;
     return 0; // On success.
     ...
     return -1; // On failure.
}

Read directly into the data buffer

You're doing unnecessary copying by using memcpy and a separate temporary buffer to read the file contents into.

How you could read it into the data buffer directly instead (getting rid of buffer):

size_t offset = 0;
nchars = fread(&data[offset], 1, BUFFER_SIZE, f);
// TODO: Remember to check nchars for error condition.
offset += nchars;


Reliably setting the system clipboard in a spawned thread and having the spawner wait

This code is quite confusing. Do you know about parallel threads mechanisms?

CLUtilCompact.waitForMe = true;
set.start();

A new thread is started now and executes the run method from the interface. It is not defined when the thread is run, how fast and when he will execute any statements (and can not, the OS is responsible for this, not the JVM)

So, sometimes, this lines is called first:

while(CLUtilCompact.waitForMe){}

Sometimes this line is called first:

CLUtilCompact.waitForMe = false;

Even if the second line is called first, nobody knows when the field update will propagate to the other thread.

What we can do about this? In general, nothing. This is the (desired) behavior of threads.
For your problem, you can either block the application until the job is done, or hope that it is done fast enough asynchronously. You could implement some logic, which will display some error message after a given time. But this is quite a bad solution for slow system or systems under heavy load.

If you want to do something after the run method has finished, try SwingWorker (read the java documentation).

Some more things:

ClipSetThread set = new ClipSetThread(theApp);
set.arg = arg;

Use the constructor, add a second argument.

while(true)
{
    try
    {
        sysClip.setContents(new StringSelection(arg), null);
    }
    catch(Exception e)
    {
        try {Thread.sleep(20);} catch (InterruptedException e1) {}
        continue;
    }
    break;
}
return;

Without discussing the pattern, this could be more readable:

boolean isSuccessful = false;
while(!isSuccessful) {
    try {
        sysClip.setContents(new StringSelection(arg), null);
        isSuccessful = true;
    }
    catch(Exception e) {
        try {Thread.sleep(20);} catch (InterruptedException e1) {} //you could use a method wait(seconds) for this
    }
}
return;

And you should, if possible, document inside the catch block why you are doing nothing there.


Kattis Challenge - Recount - count who has the most votes in a list of names

There are 2 important performance issues here:

find(...) in a vector performs a linear search, \$O(n)\$. You would do better by using a hash map instead, that would allow constant-time search, \$O(1)\$.
Sorting the candidates by vote count is unnecessary to find the ones with the maximum count. Sorting is an \$O(n \log n)\$ operation. You can find the maximum with a linear search, \$O(n)\$, and in a second linear pass you could verify if a run-off is needed. (You could as well make this part of step 1 and do it in a single pass, but that wouldn't change the order of complexity of the algorithm.)

Lastly, a minor thing, but the implementation will fail if there are less than two candidates :-)


I believe these two lines are causing all the trouble.

 List* temp1 = head;
 List* temp2 = temp1->next;

temp2 never gets the head node because it is initialized as head->next to begin with.

I prefer double pointers since I find them rather cleaner.

void remove(Node<ItemType> * & head, double value) {
    Node<ItemType> **pp = &head;
    Node<ItemType> *curr = head;
    while (curr) {
        if (curr->item == value) {
            *pp = curr->next;
            delete curr;
            curr = *pp;
        }
        else {
            pp = &curr->next;
            curr = curr->next;
        }
    }
}


I wanted to know if the pop() implementation can cause a memory leak?

It will not cause a memory leak, because java is a garbage collected language. When top is no longer accessible the garbale collecter will free top if it sees fit.

feedback:

In push() the null check is unnessecary, because node.next is already null by default.

public void push(E data) {
    Node node = new Node(data);
    node.next = top;
    top = node;
}

Rather then have a print() method, create a toString() method. toString() is a method of Object that is used across java to get a string representation of an object. This will make it easier to print your object to different streams.
In Node, create a getData() (and optionally setData()) method to control access to the data class, or make data final.
make top private to control use of your class to the supported methods.


You could consider terminating with the exit codes from <sysexits.h>, especially if the client is expecting them.  For instance, if fork() fails, return or call exit() with EX_OSERR.
It may be helpful to make the 127 error code a macro with a relevant name, since it's probably not a very commonly-known error code, especially returned from main().  I assume it's being used correctly (based on this post).
It would look clearer to put execlp()'s return value in a conditional, rather than always printing an error afterwards.  Since the exec functions only return a value (-1) on error, have the error message displayed only if this value gets returned.  Of course, have errno printed out as well.
You should also check to see if the child process has terminated from a signal.  This can be done by calling WTERMSIG() and displaying its returned signal value.  That can be determined by first checking the return value of WIFEXITED() (before doing the other checks).

Example:

int status;

// do checks with waitpid()

if (WIFEXITED(status))
{
    fprintf(stderr, "the process exited with code %d\n", status);
    exit(WEXITSTATUS(status));
}
else
{
    fprintf(stderr, "the process died with signal %d\n", WTERMSIG(status));
    exit(EX_OSERR);
}

I don't see a need for printerr() when you can just use perror(), which is already provided in <stdio.h> and does more than your function.  Regardless, it's a little redundant to put "failed" into the argument.  Clients receiving such a message should already be able to see that it's some kind of error, and it's automatically printed to stderr.
Instead of just having default provide an ambiguous error message, have it display the current value of errno with perror().  Again, your function doesn't do very much.


Here's the code I have, which works perfectly

int k = 0;
for (int i = 0; i < a.GetLength(1); i++) {
    for (int j = 0; j < b.GetLength(1); j++) {

        //if fragment falls in bin, add it to the new object
        if (a[0, i] <= (b[0, j] + binSize / 2) &&
            a[0, i] > (b[0, j] - binSize / 2)) {

            c[0, k] = a[0, i];
            c[0, k] = b[0, j];

            c[1, k] = a[1, i];
            c[1, k] = b[1, j];
            k++;

        }
        if (k >= a.GetLength(1)) {
            break;
        }
    }
}

It is obviously better to extract the binSize / 2 outside of the for loops, as binSize is never changed. So the repeating binSize / 2 isn't needed. Assuming binSize is an int:

int halfBinSize = binSize / 2;

Also a.GetLength(1) and b.GetLength(1) won't change, but are queried each time in the inner loop so refactor like this:

int lengthA = a.GetLength(1);
int lengthB = b.GetLength(1);

As you overwrite the values of

            c[0, k] = a[0, i];
            c[0, k] = b[0, j];

            c[1, k] = a[1, i];
            c[1, k] = b[1, j];

this can be reduced to

c[0, k] = b[0, j];
c[1, k] = b[1, j];

As the context isn't known let's keep the check for k >= a.GetLength(1)

the check for k >= a.GetLength(1) can be removed as you are using the a[,] only to compare with b[,] the check can be removed completely

but we place it to the looping condition

for (int j = 0; k >= lengthA && j < lengthB; j++)

and we should refactor a[0,i] to outside the inner loop

double currentA = a[0,i];

which results overall in

int halfBinSize = binSize / 2;
int lengthA = a.GetLength(1);
int lengthB = b.GetLength(1);
double currentA;

int k = 0;
for (int i = 0; i < lengthA; i++)
{

    currentA = a[0,i];

    for (int j = 0; k >= lengthA && j < lengthB; j++)
    {
        //if fragment falls in bin, add it to the new object
        if (currentA  <= (b[0, j] + halfBinSize) &&
            currentA  > (b[0, j] - halfBinSize))
        {

            c[0, k] = b[0, j];

            c[1, k] = b[1, j];
            k++;

        }
    }
}


Implementation of Parallel.ForEach for .NET 3.5

if (items == null)
        throw new ArgumentNullException("enumerable");

In the execution path where this exception is thrown, the reported argument name will not match the actual argument name. If this is the result of a rename refactoring (i.e. it's the parameter formerly known as "enumerable"), it's unfortunate, the string literal wasn't taken care of. That doesn't happen with ReShaper performing the refactoring, but if you're using the refactoring built into VS, I'm not sure it handles string literals; if you've manually "renamed" the argument, ...next time, use refactor/rename! ;)

Your implementation queues a work item for each item in items.

  ThreadPool.QueueUserWorkItem

  Queues a method for execution. The method executes when a thread pool thread becomes available.

The interesting bit is about its return value:

  Return Value

  Type: System.Boolean

  true if the method is successfully
  queued; NotSupportedException is thrown if the work item could not be
  queued.

There's the slight possibility that thread pooling might not be supported on the platform code is running on (from what I gathered of reasons for this exception to be thrown), in which case the first iteration will throw a NotSupportedException that the ForEach code might not be expecting at all... but letting it bubble up might just be the best thing to do in this case.

If I correctly understand what's going on, you're essentially spawning a thread to run an action, for each item in items. This might not be as efficient as you'd think it is: there's only so many concurrent operations that can happen on a quad-core processor, and then there's overhead too; sometimes it's more efficient to simply run the tasks sequentially.

And that's what Parallel.ForEach does:

  Parallel.ForEach

  Executes a foreach operation on an IEnumerable in which iterations may run in parallel.

Thus, I'd use your implementation with care, and perhaps use a profiler and benchmark against a "normal" foreach for a given number of iterations, but then your dev environment might have different computing power than your test and/or production environments, so careful with benchmarks, too.

It might be simpler to use the Microsoft NuGet package @JesseC.Slicer and @PhilBolduc mentioned in the comments...


As t3chb0t suggested, when creating SQL based on user input use ALWAYS SqlParameters to prevent sql injection!

Instead of creating SQL using a StringBuilder, I would try to abstract common structures and create classes to represent them. That makes the code more readable and maintainable.

A more structured solution could look like that:

    private class Condition
    {
        public Condition(string field, string parameterName, object paramerterValue)
        {
            this.Field = field;
            this.ParameterName = parameterName;
            this.ParameterValue = paramerterValue;
        }

        public string Field { get; }
        public string ParameterName { get; }
        public object ParameterValue { get; }

        public override string ToString() => $"{Field} = @{ParameterValue}";
    }

    public class SqlQuery
    {
        public SqlQuery(string sql, SqlParameter[] parameters = null)
        {
            this.Sql = sql;
            this.SqlParameters = parameters ?? new SqlParameter[0];
        }

        public string Sql { get; }
        public SqlParameter[] SqlParameters { get; }
    }

    public SqlQuery CreateSearchQuery(SearchViewModel model)
    {
        if (model == null) return new SqlQuery("SELECT * FROM newTbl.files");

        var sql = "SELECT * FROM newTbl.files fi INNER JOIN newTbl.folders fo ON fo.id = fi.f_folders_id";

        var conditions = new List<Condition>();
        var sqlParameters = new SqlParameter[0];
        var pcount = 1;

        if (model.NumberClubs > 0) conditions.Add(new Condition("fo.numberClubs", $"p{pcount++}", model.NumberClubs));
        if (model.MrDateFrom != null) conditions.Add(new Condition("fo.mrDate", $"p{pcount++}", model.MrDateFrom.Value));
        if (model.Period > 0) conditions.Add(new Condition("fo.period", $"p{pcount++}", model.Period));

        if (conditions.Count > 0)
        {
            var whereClause = " WHERE " + string.Join(" AND ", conditions);
            sqlParameters = conditions.Select(c => new SlqParameter(c.ParameterName, c.ParameterValue)).ToArray();
            sql += whereClause;
        }

        sql += " ORDER BY newTbl.period DESC";

        return new SqlQuery(sql, sqlParameters);
    }


Understanding OO JavaScript with a simple scenario

Pretty good code.

From an OOP perspective, this is exactly right. From a formatting perspective, this is almost flawless. I hardly have anything to say about this code, but I see very little that I would change.

The only issue that I see is an irregular formatting choice. These commas:

Shape.prototype = {
    constructor: Shape
    , getId: function() {
        return this.id
    }
    , getSize: function() {
        return this.size
    }
    , setSize: function (size)  {
        this.size = size
    }
}

should be like this:

Shape.prototype = {
    constructor: Shape,
    getId: function () {
         return this.id
    },
    getSize: function () {
         return this.size
    },
    setSize: function (size)  {
        this.size = size
    }
};

Oh and you need to read this world-changing answer about OO practices in JS.

Be sure to press B while reading that, because if not, you'll evolve into a legendary OOP developer.