Split a file into individually allocated lines

Bugs

If flock() fails, you don't close the file descriptor.  Instead of goto out it should be goto close.
If the file does not end in a newline, you allocate extra space for it but you don't actually fill it in.  This means that you leave your buffer with an uninitialized last character and no null terminator.  Later, in countlines(), your call to memchr() will return NULL if it doesn't find a newline on the last line, and your program will crash.

Simplification #1

This code:

tmp = getlines(buf, size);
if (tmp == NULL)
    goto free;

lns = tmp;

could be simplified to:

lns = getlines(buf, size);

Simplification #2

Instead of allocating *size bytes and then reallocating one extra byte if you need to add an extra newline, just allocate the one extra byte to start with.

Simplification #3

Instead of defining and undefining a macro like this:

#define LENGTH ((end) - (buf) + 1)

ln = malloc(LENGTH + 1);
if (ln == NULL)
    return NULL;
ln[LENGTH] = 0;
(void)memcpy(ln, buf, LENGTH);

#undef LENGTH

just use a variable:

size_t length = end - buf + 1;

ln = malloc(length + 1);
if (ln == NULL)
    return NULL;
ln[length] = 0;
memcpy(ln, buf, length);


Looks pretty standard to me! The only minor tweak I would make just for readability is to eliminate the else in AppointmentBookingController::verify(); since you return in the if, the else block is not necessary, and using guard clauses like this will (arguably) make your code more readable. See Invert "if" statement to reduce nesting.


Pandas : Apply Merge operations from a column

Wrap the logic in a function, then .apply that function.

Consider then doing another function lookup using a simple dictionary. This keeps your functions very short and simple.

Something like:
def _op_get_a(row):
    return row.data_a

def _op_get_b(row):
    return row.data_b

def _op_avg(row):
    return (row.data_a + row.data_b) / 2.0

def _op_sum(row):
    return row.data_a + row.data_b

def _op_concat(row):
    return np.concatenate([row.data_a, row.data_b], axis=0)

def process_row(row):
    return {
        'data_a': _op_get_a,
        'data_b': _op_get_b,
        'avg': _op_avg,
        'sum': _op_sum,
        'concat': _op_concat,
    }[row.operation](row)

# The "axis=1" is critical to apply this row-wise rather than column-wise
dataframe['new_column'] = dataframe.apply(process_row, axis=1)

I haven't tested this code, but you get the idea. Supporting new row operations is as simple as writing it as a row-wise function and hooking it into the lookup dictionary. The code is written at the smallest possible unit and able to be individually documented without creating a big cluttered mess.


Checking whether the max and min values occur equally frequently

Reviews:

Nomenclature "a" : Name doesn't reflect the motive.
">2" is incorrect. It should be ">1".
{1, 1, 1, 1, 1, 1} will be incorrect in your case as min and max are same.
a could be null so we should check

if(input == null || input.size <2){
    return 0;
}

Multiple returns, though debatable but advisable.
Coming to reducing the loops:

for (int num : a) {
    if (num > max) {
        max = num;
        maxCount = 1;
    } else if (num == max) {
        maxCount ++;
    }

    if (num < min) {
        min = num;
        minCount = 1;
    } else if (num == min) {
        minCount ++;
    }
}

If you wish to minimize further: return (max != min && maxCount == minCount)


How can I make this C code for checking checksum shorter?

Use a 2D array instead of 6 1D arrays (vs. character0, character1, ...)

Use a 1D array for n instead of (n0, n1, ...)

Add EOS termination to the string that gets passed to strtol

Here's a refactored version:

bool
checksum(char card[])
{
    char chars[6][3];
    long nx[6];

    for (int col = 0;  col < 6;  ++col) {
        int lo = col << 1;
        int hi = lo + 2;
        for (int i = lo;  i < hi;  ++i)
            chars[col][i - lo] = card[i];
    }

    for (int i = 0;  i < 6;  ++i) {
        char *ptr = chars[i];
        ptr[2] = 0;
        nx[i] = strtol(ptr,NULL,16);
    }

    if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] == nx[5])
        return true;
    else
        return false;
}

UPDATE:

Here's a cleaner/simpler version:

bool
checksum(char card[])
{
    char tmp[3];
    long nx[6];

    tmp[2] = 0;
    for (int col = 0;  col < 6;  ++col) {
        int lo = col << 1;

        tmp[0] = card[lo + 0];
        tmp[1] = card[lo + 1];

        nx[col] = strtol(tmp,NULL,16);
    }

    if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] == nx[5])
        return true;
    else
        return false;
}

UPDATE #2:

Here's an even simpler version:

bool
checksum(char card[])
{
    char tmp[3];
    long nx;

    tmp[2] = 0;
    nx = 0;
    for (int idx = 0;  idx < 12;  idx += 2) {
        tmp[0] = card[idx + 0];
        tmp[1] = card[idx + 1];

        nx ^= strtol(tmp,NULL,16);
    }

    if (nx == 0)
        return true;
    else
        return false;
}

UPDATE #3:

Based on some feedback ...

The first two examples above, were to eliminate "parallel scalar" variables (e.g.) v0, v1, v2, ... vN in favor of an array: v[N+1]. This allowed replicated code to be replaced with loops. OP's code had two such instances for character* and n* variables, so I converted both to arrays.

When starting out [as a programmer], when to use an array isn't always obvious [particularly for small numbers]. In the above case, N was 6. So, the code could be built up by cut-and-paste.

If, however, N had been a much larger number, say, 1000, the original code would then not scale well. And, the array solution would have become [more] obvious.

OP's code was trying to copy two bytes from the buffer into different char arrays of the form character* in the first code block [to add an EOS char to allow strtol to work]. This still had a bug because there was no space for the EOS.

OP's second block would use strtol on the intermediate character* variables to produce n* variables.

My first example [in my original post], did the conversion from separate scalar variables to arrays.

My second example [in my first update], combined both blocks/loops into one, so that character* [which I had replaced with the 2D chars array], could be eliminated with a single tmp array.

When I did my example in update #2, I assumed that OP's algorithm was correct. I didn't realize that:

if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] == nx[5])

was being interpreted [by the compiler, based on precedence] as:

if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ (nx[4] == nx[5]))

I assumed it was grouped as:

if ((nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4]) == nx[5])

Because that's what made sense for the CRC calculations [and I assumed OP had done it correctly].

My refinement [to eliminate the nx array in favor of a running CRC], was based on the following identity:

(x == y) === ((x ^ y) == 0)

So, XORing all values (including the checksum), if the message was correct/intact, would produce a final value of zero. So, by doing this, I fixed OP's second bug, based on some serendipity.

Others have pointed out that:

if (nx == 0)
    return true;
else
    return false;

Can be replaced with:

return (nx == 0);

I had debated doing that, but decided that the example was already far afield from OP's original and that it would be clearer to leave the return sequence as it was. And, the optimizer would [probably] produce the same exact code for both.

At that point, I had debated coming up with a hex function that decoded a single hex char as others have suggested, calling it twice and eliminating the copy to tmp and call to strtol, but, again, felt I was getting far enough away from the original code.

But, just for the sake of completeness, here is my final/best example, generalized to allow an arbitrary buffer size:

unsigned int
hex(unsigned int chr)
{

    // NOTE: hopefully, this function gets inlined ...

    do {
        if ((chr >= '0') && (chr <= '9')) {
            chr -= '0';
            break;
        }

        chr = tolower(chr);

        if ((chr >= 'a') && (chr <= 'f')) {
            chr -= 'a';
            chr += 10;
            break;
        }

        // should blow up here (but there was no error checking in original)
        chr = 0;
    } while (0);

    return chr;
}

bool
checksum(const char *card,size_t len)
{
    unsigned int cur;
    unsigned int crc = 0;

    for (size_t idx = 0;  idx < len;  idx += 2) {
        cur = hex(card[idx + 0]);
        cur <<= 4;

        cur |= hex(card[idx + 1]);

        crc ^= cur;
    }

    return (crc == 0);
}

Note that even this could be tweaked a bit more for speed with some careful benchmarking ...

UPDATE #4:

Eliminating the call to hex in favor of a [single] table lookup may be faster and provide some error checking:

int
checksum(const char *card,size_t len)
{
    static unsigned char hex[256] = { ['0'] = 0xFF };
    unsigned int chr;
    unsigned int cur;
    unsigned int crc = 0;

    // one time init of translation table
    if (hex['0'] == 0xFF) {
        for (chr = 0x00;  chr <= 0xFF;  ++chr)
            hex[chr] = 0xFF;

        for (chr = 0;  chr <= 9;  ++chr)
            hex[chr + '0'] = chr;

        for (chr = 0x00;  chr <= 0x05;  ++chr) {
            hex[chr + 'a'] = chr + 0x0A;
            hex[chr + 'A'] = chr + 0x0A;
        }
    }

    for (size_t idx = 0;  idx < len;  idx += 2) {
        chr = hex[card[idx + 0]];
#ifdef ABORT_ON_ERROR
        if (chr == 0xFF)
            return -1;
#endif
        cur = chr;
        cur <<= 4;

        chr = hex[card[idx + 1]];
#ifdef ABORT_ON_ERROR
        if (chr == 0xFF)
            return -1;
#endif
        cur |= chr;

        crc ^= cur;
    }

    return (crc == 0);
}


Android RecyclerView holding rows of razzles

Remove mContext member. You're not using it anywhere.
Your code tells us that onClickListener will not change during life of Adapter object. Please make ViewHolder class static to not have implicit reference to Adapter and pass OnClickListener as a constructor parameter to ViewHolder.
ViewHolder class and it's bindRow method can be private.

Point 2 explanation :

You are passing SelectRazzleRowListener to Adapter class via constructor and don't provide a setter method to change that field during lifetime of Adapter object - so once adapter will be created with that listener he uses it always. And that's ok. But in that situation you can do a little tune to ViewHolder class. For now it's non-static inner class. By default if inner class is not static it contains implicit reference to parent class object (Adapter in this case). It may be risky in terms of memory leaks and it's good to be aware of that relationship (it's easy to test - try to create ViewHolder object somewhere outside adapter class in current state - without static - you won't be able to). It's also a reason why you can access Listener object from adapter inside ViewHolder class.
In my opinion you should make ViewHolder class static (so public static class RecyclerViewHolder .... Then you need to pass SelectRazzleRowListener object to ViewHolder by defining a field in ViewHolder class and constructor parameter. Then Adapter will pass Selection listener to ViewHolder during onCreateViewHolder.


Code Style notes:

follow PEP8 style guide, in particular:

one empty between the class methods
two empty lines after the class definition and before the next block

use print() function instead of a statement - this way you are staying compatible with the Python 3.x
rename nextNode to next_node
don't forget about the docstrings

Other improvements:

you should probably explicitly inherit from object to have a new-style class (reference)
instead of a print_reverse(), how about you create a generator method that would yield nodes instead of printing - this can come out handy later when you would actually need to use the node values, not just have them on the console

With all the suggestions applied (except the docstrings):

class LinkedListNode(object):
    def __init__(self, value, next_node):
        self.value = value
        self.next_node = next_node

    def reverse_traversal(self):
        if not self.next_node:
            yield self.value
        else:
            for node in self.next_node.reverse_traversal():
                yield node
            yield self.value

if __name__ == "__main__":
    head = LinkedListNode('a', LinkedListNode('b', LinkedListNode('c', LinkedListNode('d', None))))
    for node in head.reverse_traversal():
        print(node)

As a side note, if you would be on Python 3.3+, this part:

for node in self.next_node.reverse_traversal():
    yield node

can be rewritten using the generator delegation:

yield from self.next_node.reverse_traversal()


Ignored code

From the code sample provided, you're not actually doing anything with the AppSettingsRequest object after you've created it. Why? What is the purpose of this object?

Global variables

byte[] exportXml = exportSolutionResponse.ExportSolutionFile;

What is exportSolutionResponse? It comes out of nowhere, without being defined anywhere. This seems to be a global variable (I can't otherwise explain its existence).

Global variables are generally a bad idea. They create shortcuts in code that is one of the straws that will eventually break the camel's back (in this case, unmaintainable spaghetti code).

Stringly typing

As you seem to be using a console application, the parameters can be parsed an an array of values, not as a single string. Why are you concatenating these values into a string, only to then split the string again?

This can be improved by using explicit method parameters:

internal static void ExportSolution(SqlService service, string name, params bool[] values)

This means you no longer have to do the conversion in this method; which is a good separation of concerns.

Given that you are expect a fixed amount of booleans, it's better to explicitly name these booleans instead of allowing any array of arbitrary length:

internal static void ExportSolution(SqlService service, string name, bool managed, bool prefix, bool managedprofile, bool email, bool calendar, bool appsettings)

Vague names

Your variable names leave something to be desired. I can only guess at what these variables mean. Rename them to something clearer. I've guessed at what these booleans are used for:

internal static void ExportSolution(SqlService service, string userName, bool isManaged, bool hasPrefix, bool useManagedProfile, bool importEmail, bool importCalendar, bool overrideAppSettings)

Don't get caught up on the names, my interpretations are only a guess. But these examples are much clearer on what the impact of these booleans is.

No null checking

This ties into the earlier point. In your original code, you are taking in any string and splitting it into an array, and then assuming that this array will contain at least 8 values.

What happens when the array contains less than 8 values? You're going to end up with an IndexOutOfRangeException. While you do catch and display exceptions, it's still better to avoid exceptions where possible. It's not that hard to validate the length of the array before you try to access its elements.

if(args.Length < 8)
{
    Console.WriteLine("Insufficient parameters provided");
    return;
}

Pokémon exception handling (link)

catch (Exception ex)
{
    Console.WriteLine(ex);
}

Instead of catching all exceptions, catch the exceptions you're interested in. For example:

catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Insufficient parameters provided");
}

Note: as mentioned before, it is better to prevent the exception when possible, instead of just catching it afterwards. This only serves as a simple example of how you catch specific exceptions instead of all possible exception types.

Needlessly verbose code

AppSettingsRequest.Managed = (managed == true) ? true : false;

this can immediately be refactored to:

AppSettingsRequest.Managed = managed;

For two reasons:

== true is redundant. If the variable is already a boolean, its "trueness" doesn't need to be checked. managed == true will always equal managed.
? true : false is redundant. The evaluation (left of the ?) is already a boolean, and what you're doing here is saying "if this evaluation is true, set this to true; if this evalutation is false, set it to false". It's much short to just say "set this to the evaluation's value". managed ? true : false will always equal managed.

Note: if you were using nullable booleans, bullet point 1 wouldn't necessarily be correct (as you're also checking for non-null in that case), but you're not using nullable booleans here.

Saving some lines of code

bool managed = Convert.ToBoolean(args[2]);
AppSettingsRequest.Managed = managed;

Can be shortened to

AppSettingsRequest.Managed = Convert.ToBoolean(args[2]);

In general, I wouldn't advise this. The added clarity from separating the steps makes things easier. However, given that one of your main issues is the amount of settings, combining the two steps will halve your line count. At the same time, the combined line is not unreadable by any stretch of the imagination so it's perfectly okay to combine them here.

Separating your concerns

In general, your method is taking on too many tasks. It manipulates the input string, converts the values, handles them, writes to storage and updates the UI (console output). This is too many responsibilities for a single method.

However, this seems to be a very small and simple console application, and the overhead cost of implementing some separations may end up costing more effort than it's worth. I would still suggest a basic separation between the following tasks:

Parsing the input values (to their correct string/bool types)
Instantiating the settings object and settings its properties
Writing your data to disk


Checking if command line input is an integer

strtol will work just fine for this job:

char *end;
int correctInput = strtol(argv[1], &end, 10);

if (*end != '\0') {
    std::cout << "invalid input.\n";
    return 1;
}
std::cout << correctInput << "\n";

That said, let's do a quick review of your existing code.

Avoid using namespace std;

This is common in quite a few tutorials and such, largely of the sake of brevity. In any case, it's generally best avoided in real code.

Avoid global variables

Right now, you've defined correctInput and userInputString as global variables, even though they're only used inside of main. As a general rule of thumb, you want to restrict variables to the smallest scope necessary to do their job.

Prefer initialization to assignment

In this case, moving userInputString inside of main would have one more beneficial effect: it's better to initialize than to create an uninitialized variable (a string, in this case) and assigning a value to it later. I'd prefer to use:

std::string userInputString(argv[1]);

...or:

std::string userInputString{argv[1]};

This means that userInputString contains the correct value as soon as it exists.

Check argc before using arguments

You always want to check that argv[1] actually exists before trying to use it (and, by strong preference, print out a meaningful error message if it doesn't):

if (argc < 2) {
    std::cerr << "Usage: check <int>\n';
    return 1;
}

This tends to be more helpful than the default error message (e.g., Segmentation fault (core dumped)).

Use meaningful return values

You return 0 from main (indicating success) regardless of the input. You't typically want to indicate failure when the input was bad:

        cout << "invalid input." << endl;
        return EXIT_FAILURE;

Avoid std::endl

std::endl flushes the output stream, which is rarely needed, and tends to be undesirable. In this particular case it doesn't make much difference, but I'd get in the habit of using '\n' when you want to print a new-line, so you won't accidentally use std::endl when you're producing enough output for it to make a real difference.

Use standard algorithms where applicable

If you do decide to continue checking that the input is all digits, it's probably better to use std::all_of (or perhaps, std::any_of) instead of writing a loop to do the job:

std::string input(argv[1]);

if (std::any_of(input.begin(), input.end(), [](char ch) { return !isdigit(ch); }) {
    cout << "invalid input." << endl;
    return EXIT_FAILURE;
}


Conway's Game of Life in JavaScript sprawling iterative function

Functional Techniques

The post was tagged with functional-programming but the example doesn't appear to make use of many functional-programming approaches.

You could use functional approaches when iterating over the states, like using Array.forEach(), Array.filter(), but bear in mind that each iteration involves calling a function so it won't be as efficient as using the for loops - especially considering that there are 4900 states!

For example, the loop starting with:

for (let i=0; i<s.length; i++) {
    //check adjacents to determine if death or birth
}

Could be rewritten as:

this.states.forEach(function(state, i) {
    //check adjacents to determine if death or birth
});

And this block:

for (let j=0; j<adjacents.length; j++) {
    if (s[adjacents[j]] == "X") {
        neighborCount++;
    }
}

Could be re-written utilizing Array.filter():

const neighborCount = adjacents.filter(function(adjacentIndex) {
    return s[adjacentIndex] == 'X';
  }).length;

which can eliminate the lines for initial assignment (i.e. let neighborCount = 0;) and re-assignment (i.e. neighborCount = 0;) at the end of each iteration. Note that const is used there because the value is not re-assigned (within the context of the loop).

These functional JS exercises are really helpful for those who want to learn more about using functional programming in JavaScript.

Single assignment for adjacent squares

Correct me if this leads to a difference in functionality but the array adjacents could be set with the following line:

const adjacents = [i-1, i+1, i-n-1, i-n, i-n+1, i+n-1, i+n, i+n+1];

That way it doesn't need to be re-assigned (and cleared after evaluating the neighbors) in every iteration (and the initial line let adjacents = []; can be removed from the start of cycle()).


For big numbers and for many numbers checking for divisibility with prime numbers under the sqrt will give a big speed increase, you could still use the same method. But there are many ways to optimize factorization, many many ways.

I like your code! But some styling notes and then a suggestion.
I think the usual way to check if a number is a perfect square is:

if root*root == n:
        yield int(root)
        start += step

the check:

root.is_integer()

is more implicit and explicit is better.

Now, in line comments is hard to read. You shouldn't use those.

if n % 2 == 0:
    step = -1  # n is even, so check both evens and odds
else:
    step = -2  # n is odd, so check only odds
    start = start // 2 * 2 + 1  # Round start to odd number

instead:

if n % 2 == 0:
    # n is even, so check both evens and odds
    step = -1
else:
    # n is odd, so check only odds
    step = -2
    # Round start to odd number
    start = start // 2 * 2 + 1

but even better would be to not repeat what the if statement already says.

if n % 2 == 0:
    # only check evens
    step = -1
else:
    # check only odds
    step = -2
    # Round start to odd number
    start = start // 2 * 2 + 1

start = start // 2 * 2 + 1

might be implicit, could be more readable:

start = int(root)
start += 1 if start % 2 == 0 else 0

Now to the suggestion

If with any number that is even, it has a number of factors 2. So remove the factors 2 and do you algorithm on that number. Like this:

def factors(n):
    """
    Generates all factors of n. Iterates from sqrt(n) down to zero.
    When a factor x is found, another factor must be n divided by x.
    If n is odd, only odd numbers need to be checked.

    >>> sorted(list(factors(1001)))
    [1, 7, 11, 13, 77, 91, 143, 1001]
    """

    root = sqrt(n)
    step = -2
    start = int(root)
    start += 1 if start % 2 == 0 else 0

    if root*root == n:
        yield int(root)
        start += step

    for x in range(start, 0, step):
        if n % x == 0:
            yield x
            yield n // x

def brigde(n):
    twos = 1
    while n % 2 == 0:
        twos += 1
        n //= 2

    for num in factorss(n):
        for i in range(twos):
            yield num*(2**i)

You'll have to multiply each of the factors returned with the factors of two that the original number contained. But you remove the need to check even numbers, ending up with only the faster of the two ways your code can go.


First of all, please make sure that your indentation is correct, especially when posting Python code.  Also, take a look at PEP 8.   You are violating it in at least the following places:

You have tabs, not spaces
Comments should be in English
It is apparently not directly against PEP 8, but giving locals CapsWords names makes the code harder to understand, in my opinion (especially seeing as SE highlights them a different colour).

You also seem to have an awful lot of duplicate code.  Try to factor common operations (such as setting up all those members) into separate functions.

Speaking of which, your functions aren't particularly clear.  Why does a method called get not return anything?  What is it supposed to get?

You've got plenty of hard-coded values in there.  I hope that strYourSecretKey is a placeholder value; the other ones should be passed in as parameters.  Could you make it determine the agent ID based on the email?  As things are, it seems like this is prone to incorrect combinations of input if anything is changed.


If you have to prepare a word counter, then the more adequate container is collections.defaultdict

Then your make_dict function could be written much more simply:

def make_dict(filename):
    """returns a word/count dictionary for the given input file"""
    wordcount_dict = defaultdict(int)
    with open(filename, 'rU') as myFile:
        for line in myFile:
            words = line.strip().lower().split()
            for word in words:
                wordcount_dict[word] += 1
    return wordcount_dict

Note that you don't need to care about initialization of dictionary entries for new keys for word counting, as defaultdict takes care of it.

Another different approach is to use OOP. That is, to create a word counter object with state initialization, methods and all the stuff. The code gets simplified, encapsulated and ready to be extended.

Below, there is a working OOP proposal. There are some improvements that can be implemented also in your functional version if you don't like OOP:

1) I simplified your methods. Now there is only one method print_words(self, number=None). If you want the best 20 then just indicate the number of words.

2) I included some optimizations to clean words that are splitted with punctuation characters (otherwise house, house. and house' would be counted as different), using constants from the string module.

non_chars = string.punctuation + string.whitespace
words = [item.strip(non_chars).lower() for item in line.split()]

3) I used operator.itemgetter for the sorting key (instead of lambdas. More readable, imho)

4) I used formatting for the print for a better look. Used classical %.

import operator
import string
from collections import defaultdict

class WordCounter(defaultdict):
    def __init__(self, filename):
        defaultdict.__init__(self, int)
        self.file = filename
        self._fill_it()

    def _fill_it(self):
        "fill dictionary"
        non_chars = string.punctuation + string.whitespace
        with open(self.file, 'rU') as myFile:
            for line in myFile:
                words = [item.strip(non_chars).lower() for item in line.split()]
                for word in words:
                    self[word] += 1

    def print_words(self, number=None):
        """prints the words with the top <number> counts"""
        wc_pairs = self.items()
        wc_pairs.sort(key=operator.itemgetter(1), reverse=True)
        number = number or len(wc_pairs)
        for word, count in wc_pairs[:number]:
            print "%-20s%5s" % (word, count)

my_wc = WordCounter('testme.txt')

print my_wc['aword']    # print 'aword' counts
my_wc.print_words()     # print all (sorted by counts)
my_wc.print_words(3)    # print top 3

And a final note: leaving a blank space before and after an operator and after commas in lists, increases readability of the text and is considered good practice.


Haskell Either Applicative where the Left is a Monoid

Your Functor instance doesn't need a to be a Monoid. We can remove that constraint to make fmap on EitherLeftMonoid more general.

Your Applicative instance could be made a little bit more readable if you provide a fromLefty :: Monoid a => EitherLeftMonoid a b -> a function:

instance Functor (EitherLeftMonoid a) where
  fmap _ (Lefty a)  = Lefty a
  fmap f (Righty b) = Righty (f b)

instance Monoid a => Applicative (EitherLeftMonoid a) where
  pure                  = Righty
  Righty f <*> Righty x = Righty (f x)
  x        <*> y        = Lefty $ fromLefty x `mappend` fromLefty y

fromLefty :: Monoid a => EitherLeftMonoid a b -> a
fromLefty (Left x) = x
fromLefty _        = mempty

With fromLefty we can take advantage of mappend mempty x = x = mappend x mempty.

In this case everything is in a single module and everything gets exported. This enables a user to use the Person constructor immediately. If you want to prevent that you need to make sure that only the type, but neither the records nor the data constructor get exported. Otherwise mkPerson can get circumvented.


Binary to decimal (and back) converter in c++

General Observations

I'm mainly looking for error checking / type safety advice.

There doesn't seem to be a lot of error checking on user input and user input is one of the places where error checking is most important. For instance, the code doesn't handle negative numbers but there is not checking for negative input.
The code also doesn't check for lack of input, and there are no error messages when the input is wrong.
Type Safety
Since the program doesn't process negative numbers it might be better to use unsigned or unsigned int for conversion rather than int.
Unnecessary Function Prototypes
If the main() function were placed at the bottom of the file rather than the top of the file, the function prototypes
void binaryToDecimal();
void decimalToBinary();

are not needed.
Magic Numbers
There is a Magic Numbers in the binaryToDecimal() function (32), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
In this case 32 probably refers to word size, but that is an arbitrary number, most computers these days have a 64 bit word size. You could get the actual size of the word by using the sizeof() function and then multiplying it by 8 since sizeof() the number of char in the object and 8 bits is the size of a char, there also might be a word size constant hidden in an include header.
Complexity
While main() is pretty simple now, once you start adding the error checking you need it will get more complex, and it should be broken up into different function.


Understanding exceptions in a constructor (by the conversion C-string to long example)

From the c++ specification's point of view a constructor is allowed to throw an exception (in opposite to destructor). So your code is fine.

On the other hand I don't see any advantage why it should be validated directly in the constructor. You could do it in is_valid method as well. Furthermore, if you moved the valifation code out from the constructor to a private method, you would gain an easy way to keep responsibility of handling low-level exceptions inside you class.
So, although your code is valid semantically, its design needs some improvement.

I hope I helped:)


Is there a situation where the compiler will not optimize away the wrapper because the wrapper and the original function have different semantics?

Yes to the first part and no to the second. Any optimizing compiler will inline your wrapper, as it consists of only one return statement.

But on the other hand, the original function might have different semantics: It might be constexpr for example, and your alias will not be.

  Does this fail to compile for some functions?

No (except for the constexpr part).

So here are some improvements you can use:

Templates are implicitly inline, so you don't need to write it explicitly.
Use a lambda to combat the missing constexprness of the alias, because since C++17 lambdas are implicitly constexpr if they can be.

This will get you:

#define FUN_ALIAS(NEW_NAME, ...)                                                \
  inline auto NEW_NAME = [](auto &&... args)                                   \
    noexcept(noexcept(__VA_ARGS__(std::forward<decltype(args)>(args)...)))     \
    -> decltype(auto) {                                                        \
    return __VA_ARGS__(std::forward<decltype(args)>(args)...);                \
  };


Parsing of XML in Python using minidom, and inserting data into a database

You're right, the delimiter doesn't seem pythonic. The whole logic behind your split function either.

Let's start by analyzing the problem: you want to extract parameters by name in your XML, associate it to an other name, add default values and insert it in a database.

There is nowhere a need to fetch every values before storing a row in the database, so we could write a function that does all that at once:

def connect(user, host, pwd, db, port):
    c = mysql.connector.connect(user=user, password=pwd, host=host, database=db, port=port)
    return c

def get_default_values(doc):
    rc = doc.getElementsByTagName('Recipe')[0].firstChild.nodeValue
    rid = doc.getElementsByTagName('RunNumber')[0].firstChild.nodeValue
    tid = doc.getElementsByTagName('ToolID')[0].firstChild.nodeValue
    return 1069, rc, rid, tid

def from_xml_to_db(doc, xml_name, db_name, connexion, default_values):
    param_value = int(doc.getElementsByTagName(xml_name)[0].firstChild.nodeValue)
    db_row = (param_value, param_name) + default_values
    param_binding = ', '.join('?' * len(db_row))
    sql_query = 'INSERT INTO runspecdata(param_value, param_name, ics_runnum, '\
                'recipe, batch, tool) VALUES ({})'.format(param_binding)
    cursor = connexion.cursor()
    cursor.execute(sql_query, db_row)
    cursor.close()

ics_rc_rid_tid = get_default_values(doc)
connexion = connect(USER, HOST, PASSWORD, DB, DB_PORT)
from_xml_to_db(doc, 'Target', 'target', connexion, ics_rc_rid_tid)
from_xml_to_db(doc, 'CumulTarget', 'cumul', connexion, ics_rc_rid_tid)
from_xml_to_db(doc, 'CTarget', 'c-target', connexion, ics_rc_rid_tid)
from_xml_to_db(doc, 'SITarget', 'si-target', connexion, ics_rc_rid_tid)
connexion.close()

I didn't considered the case of 'sio-target' as there is no value associated and it doesn't appear in the DB screenshot. If you want to support adding a row with no parameter associated in the XML, you may want to consider using a default value (say None for xml_name will lead to param_value = 0 or something along the lines).

However, this code is still not ideal. There are repetitions at several levels and, more importantly, there is a tight coupling between reading from XML and writing to DB. You can see that I moved the the DB connection out of the writing function to lessen coupling, let's do more of those.

To start with doc.getElementsByTagName(...)[0].firstChild.nodeValue need to be factorized. Let's add handling of default values when names does not exist:

def read_parameter(doc, name=None, default=0):
    if name is None:
        return default

    try:
        value = doc.getElementsByTagName(name)[0].firstChild.nodeValue
    except IndexError:
        value = default

    return int(value)

Here we handle the IndexError in case there is no tag named name in the document and the returned list is empty. If there is a possibility that a tag does not have elements within it, firstChild may be None and you might have to deal with an AttributeError as well (speculations, I’m not that versed into minidom).

This let us simplify:

def get_default_values(doc, ics=1069):
    return (
        ics,
        read_parameter(doc, 'Recipe'),
        read_parameter(doc, 'RunNumber'),
        read_parameter(doc, 'ToolID'),
    )

Next we need to separate reading from XML from writing to DB. Let's start with the writing:

def store_target(connexion, db_row):
    param_binding = ', '.join('?' * len(db_row))
    sql_query = 'INSERT INTO runspecdata(param_value, param_name, ics_runnum, '\
                    'recipe, batch, tool) VALUES ({})'.format(param_binding)
    with connexion.cursor() as cursor:
        cursor.execute(sql_query, db_row)

Much simpler. I also changed the cursor creation to ease its management, the context manager should be implemented as part of the DB API 2.0 but if it doesn't, just use connexion.cursor() and cursor.close() as previously.

Now the XML reading is already handled by read_parameter, so let's bring it all together:

ics_rc_rid_tid = get_default_values(doc)
connexion = connect(USER, HOST, PASSWORD, DB, DB_PORT)
row = read_parameter(doc, 'Target'), 'target'
store_target(connexion, row + ics_rc_rid_tid)
row = read_parameter(doc, 'CumulTarget'), 'cumul'
store_target(connexion, row + ics_rc_rid_tid)
row = read_parameter(doc, 'CTarget'), 'c-target'
store_target(connexion, row + ics_rc_rid_tid)
row = read_parameter(doc, None), 'sio-target'
store_target(connexion, row + ics_rc_rid_tid)
row = read_parameter(doc, 'SITarget'), 'si-target'
store_target(connexion, row + ics_rc_rid_tid)
connexion.close()

Well… no… this seems not right. Let's improve that as well.

XML_TO_DB_TABLE = (
    ('Target', 'target'),
    ('CumulTarget', 'cumul'),
    ('CTarget', 'c-target'),
    (None, 'sio-target'),
    ('SITarget', 'si-target'),
)

def read_parameter(doc, name=None, default=0):
    if name is None:
        return default

    try:
        value = doc.getElementsByTagName(name)[0].firstChild.nodeValue
    except IndexError:
        value = default

    return int(value)

def get_default_values(doc, ics=1069):
    return (
        ics,
        read_parameter(doc, 'Recipe'),
        read_parameter(doc, 'RunNumber'),
        read_parameter(doc, 'ToolID'),
    )

def connect(user, host, pwd, db, port):
    c = mysql.connector.connect(user=user, password=pwd, host=host, database=db, port=port)
    return c

def store_target(connexion, db_row):
    param_binding = ', '.join('?' for _ in db_row)
    sql_query = 'INSERT INTO runspecdata(param_value, param_name, ics_runnum, '\
                'recipe, batch, tool) VALUES ({})'.format(param_binding)
    with connexion.cursor() as cursor:
        cursor.execute(sql_query, db_row)

def xml_to_db(doc, connexion, table):
    common_values = get_default_values(doc)
    with connexion:
        for xml_name, db_name in table:
            specific_values = read_parameter(doc, xml_name), db_name
            store_target(connexion, specific_values + common_values)

if __name__ == '__main__':
    doc = #Initialize it somehow
    cnx = connect(USER, HOST, PASSWORD, DB, DB_PORT)
    xml_to_db(doc, cnx, XML_TO_DB_TABLE)
    cnx.close()

Here the with connexion part is supposed to commit or rollback the transactions depending if anything went well of if there was an error. Again, if it doesn't work for MySQL, just use the management method you're used to.

A few other comments to finish with:

Your indentation is very weird on your connect call;
Using global variables inside a function can impair reusability, try to pass them as parameters instead;
The if __name__ == '__main__' part lets you import your module and tests functions without having any code executed beforehand;
You're building the binding list ((?, ?, ?, ?, ?, ?)) based on the length of the row you want to insert but you are actually expecting 6 arguments (by looking at the name of the columns involved); why not enforce that anyway and let the DB handle wrong number of arguments itself?

That last point would lead to a much simpler store_target:

def store_target(connexion, db_row):
    with connexion.cursor() as cursor:
        cursor.execute(
            'INSERT INTO runspecdata(param_value, '
            'param_name, ics_runnum, recipe, batch, tool) '
            'VALUES (?, ?, ?, ?, ?, ?)', db_row)


Python solution to Code Jam's 'Rounding Error'

1. Review

It is hard to test this code because it gets its data from standard input.

This means that in order to test it or measure its performance you have to write the test case to a file and then run the code with standard input redirected from that file. It would be easier to test if the code were refactored so that the input-reading part of the code was in a separate function from the problem-solving part, like this:

from functools import reduce

def gen_sums(total, freq, remaining):
    """Generate percentages' sums"""
    if not remaining:
        yield reduce(lambda x, y: x + (y*100+total//2)//total, freq, 0)
    else:
        seen = set()
        for i in range(len(freq)):
            if not freq[i] in seen:
                yield from gen_sums(total,
                                    freq[:i] + [freq[i]+1] + freq[i+1:],
                                    remaining-1)
                seen.add(freq[i])
        yield from gen_sums(total, freq+[1], remaining-1)

def max_percentage(total_people, languages_frequency):
    if not 100 % total_people:
        return 100
    not_responded = total_people - sum(languages_frequency)
    return max(gen_sums(total_people, languages_frequency, not_responded))

def main():
    T = int(input())
    for i in range(1, T+1):
        total_people, num_languages = map(int, input().split())
        languages_frequency = [int(x) for x in input().split()]
        result = max_percentage(total_people, languages_frequency)
        print('Case #{}: {}'.format(i, result))

Now it's easy to test the code from the interactive interpreter or from a unit test, for example:

>>> max_percentage(11, [1, 2, 3, 4])
99

and easy to measure its performance:

>>> from timeit import timeit
>>> timeit(lambda:max_percentage(14, []), number=1)
8.237278351996792

2. Performance

As demonstrated above, the code in the post takes more than 8 seconds to figure out that when there are 14 voters (and no votes cast yet), the maximum rounded percentage is 101%.

Why does the code in the post take so long to solve this problem? Well, it's because it carries out a search over all possible assignments of votes. But if there are \$n\$ voters then there are of the order of $$\exp{\pi\sqrt {2n \over 3}}$$ possible assignments of votes (see the asymptotic formula for the partition numbers) and so the runtime is exponential in the number of votes.

But in fact the problem is easy to solve by hand with a little bit of mathematics. If there are 14 voters, then each vote is worth \${100 \over 14} = 7{1\over7}\$ percent, and so four votes are worth \$28{4\over7}\$ percent, which rounds up to 29. Fewer than four votes will round down, and more than four will be wasteful since the extra votes over four could be used to contribute to another block of four votes. So the maximum rounded percentage is found when we group as many of the votes as possible into blocks of four votes. In this case there are three such blocks, leaving two votes over, giving a rounded total of \$29·3 + 14 = 101\$.

Similar analysis shows that if there are 19 voters, then each voter contributes \${100\over19} = 5{5\over19}\$ percent, and so it is most efficient to put voters in pairs, because two votes contibute \$10{10\over19}\$ percent, which rounds up to 11. So we have nine pairs of votes and one left over, giving a rounded total of \$11·9 + 5 = 104\$. But it will be a very long time before max_percentage(19, []) returns the result.

So searching over all possible assignments of votes is not going to work even for moderately large problem sizes. Instead, you need to program the kind of mathematical analysis that I carried out in the examples above. I'm not going to spoil the problem for you by giving away my solution, but I'll just show one performance measurement:

>>> timeit(lambda:max_percentage2(14, []), number=1)
0.00011452200124040246

This is more than 70,000 times faster than the code in the post.


Grouping sorted coordinates based on proximity to each other

General comments:

You are basically using the groups dict like a list.  Might as well just use a list.

An empty data structure (list, dict, set, tuple) is False in a boolean context, so while len(points) > 1: can be simplified to while points:

It is generally slower to pop from the front of a list than the back of a list, because after removing the first item all the rest of the items get moved up one spot.

points.pop() actually changes the list passed in.  Make sure that's what you want.

filter(None, points) filters out all "False" items.

[ ... ] creates a list.  So, list( [ ... ] ) is redundant.

You can just use x1, y1 = ref.

Put that all together and you get something like:

def group_points(points):
    groups = []
    while points:
        far_points = []
        ref = points.pop()
        groups.append([ref])
        for point in points:
            d = get_distance(ref, point)
            if d < 30:
                groups[-1].append(point)
            else:
                far_points.append(point)

        points = far_points

    # perform average operation on each group
    return [list(np.mean(x, axis=1).astype(int)) for x in groups]

def get_distance(ref, point):
    # print('ref: {} , point: {}'.format(ref, point))
    x1, y1 = ref
    x2, y2 = point
    return math.hypot(x2 - x1, y2 - y1)

You also might want to look at functions in scipy.cluster.


Merge into an object from two different API calls

I beleive the issue with

When setting the object at the end with setAllSdksInfo(objCopy) there
was a problem in which it would not set it ok.

Is because Object.assign is not doing what you're expecting it to do, it does not create a deep copy of the source object
TLDR;
When you modify a nested property of the copied object, it will affect the original one, one way of creating a deep copy of the object is JSON.parse(JSON.stringify(obj)) :

const obj_original = {
  a: {
    b: {
      c: 'hello'
    }
  }
}

const obj_copy = Object.assign({}, obj_original);

const deep_copy = JSON.parse(JSON.stringify(obj_original));

obj_original.a.b.c = 'test';

console.log(obj_original); // { a: { b: { c: 'test' } } }
console.log(obj_copy); // { a: { b: { c: 'test' } } }
console.log(deep_copy); // { a: { b: { c: 'hello' } } }

Keep it DRY :
instead of objCopy[id]["churned_total"] = data["churned_total"]; you could use destructuring assignment to avoid repeating :
selectedSdksKeys.forEach(async (id, i) => {
  if (allSdksInfo[id]?.num_installed_apps) return;

  const res = await fetch(`/api/sdk/general_info?sdk_id=${id}`);

  const { num_installed_apps, acquired_total, churned_total } = await res.json();;

  objCopy[id] = {
    ...objCopy[id],
    num_installed_apps,
    acquired_total,
    churned_total
  }
});


Print all possible combinations of size r, from an array of size n

I think that by avoiding duplicates, you are essentially changing the definition of the question at hand.

If that is indeed the definition of question, then instead of sorting the array and avoiding duplicates, you can simply get rid of the duplicates to begin with by using a set instead of an array:

Set<Integer> set = new HashSet<Integer>();
for (int i : arr)
    set.add(i);

In addition, for better modularity, I think that you should separate the algorithm itself from the printing:

Create an empty List<List<Integer>> instance
Pass it to the doCombine method, to fill it in with all combinations
Print it in the main method (the combine method looks kind of redundant)


Calculating direction based on index of array

"none" can be treated as a default returned value, thus eliminating multiple occurrences of direction = "none" assignment. In that way it'd be enough to just consider non-none cases:

function getDirection(component) {
    let oldIndex, newIndex,
        lastComp = this.lastComponentInViewport;

    if (lastComp) {
        oldIndex = this.components.indexOf(lastComp);
        newIndex = this.components.indexOf(component);
        if (newIndex > oldIndex) return "next";
        if (newIndex < oldIndex) return "previous";
    }
    return "none";
}


Generating a range of ints as strings in Java 8

Can you use a stream rather than an array in the rest of your application? If so I'd simply cut off the toArray bit at the end. Otherwise this looks exactly like what I'd expect in Java 8.


Questionnaire program using many wxPython windows

import wx

a1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',
     "Don't remember", 'None of the above']

a2 = ['No', 'Yes']

a4 = ['No', 'Yes']

The Python style guide recommend ALL_CAPS for global constants.

class Fruit(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))

        #create panel and button
        panel = wx.Panel(self)

        # B1 - create multiple choice list
        box = wx.MultiChoiceDialog(None, """

A1.    What kind of fruit did you buy at the store?""", 'Fruit', a1)

When strings get long enough that they force breaking across multiple lines, its usually best to move them to global constants

        if box.ShowModal() == wx.ID_OK:
            a_1 = box.GetSelections()

        print (a_1, '\n')

I don't think this does what you think it does. For python 2.x (which unless wxPython has been ported to python 3.x recently, must be what you are using), you shouldn't put parenthesis around your print statements.

            # A2 - create single choice list
        box = wx.SingleChoiceDialog(None, """
A2.    Do you like eating fruit?
""", 'Fruit', a2)
        if box.ShowModal() == wx.ID_OK:
            a_2 = box.GetStringSelection()

        print (a_2, '\n')

        if a_2 == 'Yes':
            box = wx.TextEntryDialog(None, "A3.    What kind of fruit is your favorite? ", "Fruit", "")
        if box.ShowModal() == wx.ID_OK:

If the answer to the previous question was "Yes", then box is now the result of asking question A3. However, otherwise its the still the previous question. As a result, it'll ask the same question again. You probably want to indent this if block so that it only happens if a_2 was Yes.

            a_3 = box.GetValue()

        print (a_3, '\n')

        box = wx.SingleChoiceDialog(None, """
A4.    Did you eat the fruit that you bought?
""", 'Fruit', a4)
        if box.ShowModal() == wx.ID_OK:
            a_4 = box.GetStringSelection()

        print (a_4, '\n')

As for your questions:

You can probably get away with creating that many windows. However, you can make sure that a dialog gets destroyed by calling its Destroy() method.
I explained above what was wrong with your logic.


I read that MySQLi prepare statements will prevent SQL injections. Is there any possibility to hack my db by my design?

No, there shouldn't be a way. Prepared statements are the recommended way to prevent SQL injection, and you are using them correctly and consistently.

  I am planning to create a utils.php and will add handlePrepareStmtErrors function there. In that function, I am exiting the scripts if any errors are there. So only I am not using break statement there because it will not get executed. Is it right way?

Yes, you don't need break if you are exiting or returning. Having a default is still a good idea though.

But you shouldn't exit. Helper functions and classes in general should not exit/die, they should throw exceptions or return false. If you just die, the calling function has no change to recover, thus making the function hard to reuse.

  I feel like my functions are not properly written, but it does what I want. I tried and registration is successful.

I think that your feeling is correct.

I could for example imagine multiple usages for the function getUserByEmail, but the way you are writing it, it can't really be reused, as it needs the POST value email to be set.

Ideally, the signature would look like this: getUserByEmail($email). I also just noticed that it doesn't actually get the user, so doesUserExist($email) which then returns true or false would be more fitting.


Download a zip archive and extract one file from it

PEP-8 Line Length

For particularly lengthy lines, you can always use parentheses to wrap them instead of the usual \ sign:

x = (1 + 2 + 3 +
     4 + 5 + 6)

Function Refactor

I would skip the step in your if statement where you use shutil.move, just save the file in /tmp directly:

def download_and_return_content():
    if not os.path.isfile('/tmp/junar.zip'):
        url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'
        with urllib.request.urlopen(url) as response, open('/tmp/junar.zip', 'wb') as out:
            data = response.read() # a `bytes` object
            out.write(data)

Furthermore, if you are just looking to extract a single file, you can open one of the archives directly using ZipFile.open

    with ZipFile('/tmp/junar.zip') as myzip:
        with myzip.open('junar1.in') as f:
            return f.read()

ZipFile can also take a file-like object, so you can use a BytesIO object to hold your zip-file bytes, since /tmp implies you might not need to hold onto this data:

from io import BytesIO

def download_and_return_content():
    # your temporary file-handle
    tmp_file = BytesIO()

    url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'
    with urllib.request.urlopen(url) as response:
        tmp_file.write(response.read())

    tmp_file.seek(0)

    with ZipFile(tmp_file) as myzip:
        with myzip.open('junar1.in') as fh:
            return fh.read()

Lastly, the if check implies that maybe you want to cache the data somehow. You could in theory use BytesIO as a mutable default. You can use BytesIO.tell() as your check if it has content:

def get_content(tmp=BytesIO()):
    # buffer is at position 0, it has not been read or written to
    # therefore it is probably empty
    if not tmp.tell():
        tmp.truncate() # just in case
        url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip'
        with urllib.request.urlopen(url) as response:
            tmp.write(response.read())

    # set buffer to position 0 to read content
    tmp.seek(0)

    with ZipFile(tmp) as myzip:
        # this will move the buffer to a non-zero position
        # so, now tmp.tell() will be non-zero and will pass the
        # if check on the next function call
        with myzip.open('junar1.in') as fh:
            return fh.read()

As a caveat, there are caching libraries in python that can accomplish this as well, I'm just not familiar enough with them to suggest any in a meaningful way.

Before everybody grabs their torches and pitchforks, the non-mutable-default way (usually mutable defaults are seen as bad design) could look something like this:

# refactor into two functions, one that does the actual urllib call
# for you to retrieve your data
def get_data(tmp=None):
    tmp = tmp or BytesIO()

    with urllib.request.urlopen(url) as response:
        tmp.write(response.read())

    return tmp

# and one to actually extract the file
def extract_file(tmp=None):
    tmp = tmp or get_data()

    tmp.seek(0)

    with ZipFile(tmp) as myzip:
        with myzip.open('junar1.in') as fh:
            return fh.read()

# now you can hold that BytesIO object
tmp_file = get_data()

content = extract_file(tmp_file)
# returns b'10\r\n6\r\n1\r\n4\r\n10\r\n7\r\n2\r\n3\r\n9\r\n5\r\n8\r\n'

# and if you want to write that temp file somewhere
with open('/tmp/somefile.zip', 'wb') as fh:
    tmp_file.seek(0)
    fh.write(tmp_file.read())

Of course this all depends on what you need that zipfile for, but this cuts down on the amount of reads and writes you are doing under the hood.


Compare two arrays of objects and get the objects based on ids

Use Map to reduce search complexity
Currently your method is rather complex at \$O(n^2)\$. The reason is that for each Id you iterate each item to locate the one with the Id you want.
You can use a Map to reduce the complexity. Map uses a hash to locate items, you can add each id to a map linking ids to each category.
Then just iterate the items array using the map to locate the correct category and add the item.
The result is achieved in a time complexity of \$O(n)\$.
The example shows how this can be implemented.

const categories = [{name: 'A', ids: [1, 2, 3]}, {name: 'B', ids: [4, 5, 6]}, {name: 'C', ids: [7, 8, 9]}]
const items = [{ id: 1, color: 'red'}, { id: 2, color: 'black'}, { id: 3, color: 'blue'}, { id: 4, color: 'yellow'}, { id: 5, color: 'green'}, { id: 6, color: 'pink'},{ id: 7, color: 'orange'}, { id: 8, color: 'white'}, { id: 9, color: 'teal'}];

function categorizeById(cats, items) {
    const idMap = new Map();
    const result = cats.map(cat => {
        const category = {name: cat.name, data: []};
        cat.ids.forEach(id => idMap.set(id, category));
        return category ;
    },[]);
    items.forEach(item => idMap.get(item.id).data.push({...item}));
    return result;
}
console.log(categorizeById(categories, items));


elif self.month is None:
            day = self.day
            month = future_date.month
            year = future_date.year
            date = datetime.date(year, month, day)
            if date < future_date:
                return date
            else:
                month = future_date.month - 1
                if month == 0:
                    month = 12
                    year = future_date.year - 1
                date = datetime.date(year, month, day)
                return date ```

This can be simplified to:

if len(a_date) > 1:
            if (curr_month and a_date[1] > curr_month):
                curr_year -= 1
            curr_month = a_date[1]

Also,

        elif self.year is None:
            day = self.day
            month = self.month
            year = future_date.year
            date = datetime.date(year, month, day)
            if date < future_date:
                return date
            else:
                year = future_date.year - 1
                date = datetime.date(year, month, day)
                return date ```

Can now use a shared statement such as:

if len(a_date) > 1:
            if (curr_month and a_date[1] > curr_month):
                curr_year -= 1
            curr_month = a_date[1]
        if len(a_date) > 2:
            curr_year = a_date[2]

Then,

if self.year is None or self.month is None or self.day is None

Can be simplified using the any() operator which checks a list of items against a condition (in this case if they are not None) then returns true/false depending on if all items satisfied the condition.

day = self.day
            month = future_date.month
            year = future_date.year
            date = datetime.date(year, month, day)

I would turn this into a function as it is repeated again.

The final code after condensing the logic is:

def implicit_dates(history):
    computed_dates = []
    curr_day = None
    curr_month = None
    curr_year = None
    history = reversed(history)
    for a_date in history:
        curr_day = a_date[0]
        if len(a_date) > 1:
            if (curr_month and a_date[1] > curr_month):
                curr_year -= 1
            curr_month = a_date[1]
        if len(a_date) > 2:
            curr_year = a_date[2]
        if (curr_day and curr_month and curr_year):
            computed_dates.append(
                datetime.datetime(curr_year, curr_month, curr_day))
    return reversed(computed_dates)

for historical_date in implicit_dates(history):
    print(historical_date.strftime("%Y-%m-%d"))


You have overlooked a corner case: while you normally treat \r\n as a single separator, this not the case when the two bytes are split between blocks.
splitlines could handle the universal newlines for you.

Here's what I came up with; still not very pretty I'm afraid. Initialize self.carry_cr = False in constructor.

def emit(self):
    buf = self.buf
    if buf:
        # skip \n if previous buffer ended with \r
        if self.carry_cr and buf.startswith(b'\n'):
            del buf[0]
        self.carry_cr = False

    lines = buf.splitlines()
    if buf:
        if self.is_open and not buf.endswith((b'\r', b'\n')):
            buf = lines.pop()
        else:
            if buf.endswith(b'\r'):
                self.carry_cr = True
            del buf[:]
    self.buf = buf

    self.emitted_this_cycle = False
    if lines:
        self.emitted_this_cycle = True
        for line in lines:
            yield (self.fd, line.decode(self.enc).rstrip())
    if not self.is_open:
        self.emitted_this_cycle = True
        yield (self.fd, None)


Asynchronous API calls with delegates and event handlers

public static async void ApiAction<T>(Uri uri, CallExecuted cbDelegate, HttpMethod method, bool requireAuthentication) Here it

  receives a CallExecuted this is the delegate from the calling class.
  After serializing the JSON data it calls this delegate with the item
  as parameter cbDelegate(new CallbackArgs(item));

I think you should learn how to use async-await properly. Instead of using async void (which is a bad practice in general) and taking a delegate, your method should return something like Task<List<Track>>.

This way, your method would look like this:

public Task<List<Track>> GetTracksAsync()
{
    return ApiCaller.ApiAction<List<Track>>(ApiCall.UserTracks, Id);
}

You wouldn't need all the boilerplate around it and you would also handle exceptions properly.

To use GetTracksAsync(), you would then use await:

List<Track> tracks = await GetTracksAsync();


Well, to start with, there is 99% the same code, repeated twice. This is a very bad code smell. You need to turn the repeated code part into a function, like

function checkLiberties (color, otherColor) {
    if (liberties[x + 1][y] == 'clear') {
        liberties[x + 1][y] = color;
    } else if (liberties[x + 1][y] == otherColor) {
        liberties[x + 1][y] = 'both';
    }

    if (liberties[x - 1][y] == 'clear') {
        liberties[x - 1][y] = color;
    } else if (liberties[x - 1][y] == otherColor) {
        liberties[x - 1][y] = 'both';
    }

    if (liberties[x][y + 1] == 'clear') {
        liberties[x][y + 1] = color;
    } else if (liberties[x][y + 1] == otherColor) {
        liberties[x][y + 1] = 'both';
    }

    if (liberties[x][y - 1] == 'clear') {
        liberties[x][y - 1] = color;
    } else if (liberties[x][y - 1] == otherColor) {
        liberties[x][y - 1] = 'both';
    }
}

and then just call it twice, as

checkLiberties("black", "white");
checkLiberties("white", "black");

After this step, you need to check the same thing inside the function. Where you can spot a pattern in the code, try to turn into a function. I am sure the four chunks inside can become one.


Mixing arbitrary integers and enum values

Unless I am mistaken you are dealing with a int32, string key value pair, why not use a simple struct consisting of an int and a string?

although as this is CodeReview I have to say, your use of ternary operators nested in linq statements with more terniaries is damn near illegible.

Don't forget, code you wrote 6 months ago is indistinguishable from strangers code.

If you saw this code and had never seen it before you would think it is clear and makes sense?

to be polite that EntitiesNamed method is mostly gibberish.

You are trying to define relevance in your story entities, I get it, but a hard coded nest of grouping ids is scary to read and very easy to mess up.

you are basically talking about a rule engine, Given a name and a gamestate, find the right StoryEntities.

A level down from that is, if the current gamestate and name match a certain condition, filter the returned Entities.

then you are, based on conditions grouping those entities by relevance.

you method is doing a search, a filtering and a conditional grouping, these are different tasks and need to at least be method separate, certainly not be all on one or two lines.

what if you decide to swap return order?

Remember, great code looks like well written prose, would something like

var storyentities = GetEntitiesByName(entityName);
var orderedentities = OrderByContainer(storyentities,container);

not make more sense?

could the OrderByContainer method not even be a method on a ContainerOrderer interface of some kind defining the rules for deciding relevancy? would that not separate your concerns, make testing easier and over all make it clearer what each piece of your code is doing?


Map price values to bins where bins are of a larger price range

This can be solved using groupby directly. First, get the bins you want to use, then just pandas.cut the actual values into those bins.

binning = pd.qcut(bins['value'], 12, retbins=True)[1]
group_bins = price.groupby(pd.cut(price.value, binning)).amount.sum()

This produces basically the same output for the given example, except that it is a pandas.Series instead of a pandas.DataFrame:

value
(1.0, 2.333]         50
(2.333, 3.0]        400
(3.0, 5.0]          144
(5.0, 7.333]        130
(7.333, 8.667]      157
(8.667, 11.0]       275
(11.0, 13.333]        0
(13.333, 18.667]    146
(18.667, 22.0]      148
(22.0, 26.333]        0
(26.333, 34.333]      0
(34.333, 54.0]        0
Name: amount, dtype: int64

In addition, you should probaly put this into a function and only call it from a if __name__ == "__main__": guard to allow importing from the file.

I am not quite sure why you need to determine the binning the way you do, though. From your variable names I would have assumed that bins.value are the bin edges to be used instead.


Using __all__ = [] is mostly useless in the main program, and should probably be removed.

This is hard to read:
MSG_CORRECT = '\033[32mCorrect!\033[0m'
MSG_INCORRECT = '\033[31mIncorrect\033[0m'

This is much easier:
from colorama import Fore

MSG_CORRECT = Fore.GREEN + 'Correct!' + Fore.RESET
MSG_INCORRECT = Fore.RED + 'Incorrect' + Fore.RESET

Note: Style.RESET_ALL would be an exact translation of \033[0m.  Adjust as desired.

You could pull your loop body out into separate functions:
def generate_random_sequence(length: int, characters: str) -> str:
    """
    Generate a random sequence of characters.
    """

    return ''.join(random.choices(characters, k=length))

def show_sequence(sequence: str, seconds_per_character: float) -> None:
    """
    Display a sequence to the user, one character at a time, on one line,
    using the given delay between characters.

    After the last character has been shown, clear the line.
    """

    for i, ch in enumerate(sequence):
        print(' ' * i, ch, end='\r')
        time.sleep(seconds_per_character)

    print(' ' * len(sequence), ' ')

I've done several things here:

type-hints and a """docstring""" have been added
sequence is computed in one step
removed the s variable, since it can be directly computed as ' ' * i
looped directly over the sequence, using enumerate to keep track of the index.
speed, length and characters are all arguments to the functions, so the challenge could become programmatically harder (ie, faster or longer)

With the above function, the main loop becomes simpler:
def main():
    k = 4
    lines = r'|\-/'
    seconds = 1

    init()

    while True:
        sequence = generate_random_sequence(k, lines)
        show_sequence(sequence, seconds)

        guess = input(MSG_ASK)
        if guess == sequence:
            print(MSG_CORRECT)
        else:
            print(MSG_INCORRECT)
            break

    deinit()


AsyncTask for subscribing to current location

Note: the following refers to native Android development, I am not familiar with xamarin.

About the approach
It depends on what your aim is. The downside of using AsyncTask is that it's tied to the Activity you're calling it from. I recently implemented continuous location tracking, where AsyncTasks were not an option, as the process of continuous tracking is not tied to a particular activity. So I opted for an Android Service implementation instead. The Service was in it's own class and while you could bind to a service in a given Activity I instead went for the EventBus pattern (there are other options though) - meaning every time the LocationService obtained a new location it would cache the most recent location and propagate an Event via the Eventbus. This way subscribers (such as Activities) would be informed of location changes and could update the UI accordingly.

However, if you only want to query for locations within the Map Activity, then an AsyncTask may in fact be enough (I would put that in a separate class file though so it's reusable). The downside of this approach is, that since you only start asking for locations once you enter the Map view, it may take a moment to obtain a viable location.


Speed and ID concerns converting DOM object into JQuery objects

Here's what I did, comments in the code.

$ = cheerio.load(self.formPage.toString());
path = require('path'); //Move out path from the loop to avoid re-requiring it
$('form').each(function (index, form) {

  var $form = $(form);

  // Removed action here. You seem to use it after the next line.

  var baseUrl = self.config.url.substr(0, self.config.url.lastIndexOf("/") + 1);
  var action = $form.attr('action');
  var fullAction = path.normalize(baseUrl + action);

  // In the next block, input is in the context of this form
  // We can pull it out of the loop to avoid fetching it on every iteration
  var input = $('input', form);

  // You don't seem to use fullAction in the next block?

  stores.workspacesNinjaFormCodes.apiGetQuery({
    filters: {
      workspaceId: self.workspaceId
    },
    skipHardLimitOnQueries: true
  }, function (err, codesData) {
    codesData.forEach(function (codeData) {
      var code = codeData.code;
      var dataSubmitHash = {};

      // here's the input earlier
      input.each(function (index, inputField) {

        // Let's keep it readable, place then in variables
        var $inputField = $(inputField, form);
        var inputFieldName = $inputField.attr('name');

        // we could use the || operator to check for the first and use it, or use the second if not first.
        var fieldValue = $inputField.val() || code;

        dataSubmitHash[inputFieldName] = fieldValue
      });

      console.log("dataSubmitHash:", dataSubmitHash)
    })
  })
});

In addition, one should not create functions inside loops. Consider moving them out of the loops.


Determine whether to push or update object in array based on unique ID

Your pushToArray function is less efficient than it could be because it it looping over the entire array multiple times. We could instead use find()/findIndex() to loop over the array just once:

function pushToArray(arr, obj) {
    const index = arr.findIndex((e) => e.id === obj.id);

    if (index === -1) {
        arr.push(obj);
    } else {
        arr[index] = obj;
    }
}

This is still O(n) performance, but does less repeated work and does not require altering the data structure you are using.

If you need better performance than that, you can keep the array sorted by ID and implement a simple binary search, or you can change your data structure to one more optimized for fast lookups.


Yes, abandon input(), which is usually a less powerful and flexible choice.
Here's an approximation of your code using
argparse. Notice several
things: (1) very little repetition in our code; (2) much less algorithmic code,
which means fewer chances for error; (3) greater simplicity overall
and thus higher readability;
(4) good validation and user help messages out of the box; (5) many other
possibilities (see the library's documentation); (6) less hassle for
users to run the code repeatedly or in any kind of automated context;
and (7) less hassle during development of the code, for the same reason.
# Usage examples:

$ python demo.py George Washington 289 --pet
Namespace(age=289, first_name='George', last_name='Washington', pet=True)

# The code:

import argparse
import sys

def main(args):
    ap, opts = parse_args(args)
    print(opts)

def parse_args(args):
    ap = argparse.ArgumentParser()
    ap.add_argument('first_name', type = personal_name)
    ap.add_argument('last_name', type = personal_name)
    ap.add_argument('age', type = int)
    ap.add_argument('--pet', action = 'store_true')
    opts = ap.parse_args(args)
    return (ap, opts)

def personal_name(x):
    if x.isalpha():
        return x
    else:
        raise ValueError(f'Invalid name: {x}')

if __name__ == '__main__':
    main(sys.argv[1:])

But if you cannot or do not want to take that route, the roll-your-own approach
looks similar in spirit: we need a general-purpose function to get input;
it needs to take some type of text or label to tell the user what we are asking
for; and it needs a converter/validator to check the reply.
Here's a rough sketch of the new or different parts:
def main(args):
    d = dict(
        first = get_input(label = 'first name', convert = personal_name),
        last = get_input(label = 'last name', convert = personal_name),
        age = get_input(label = 'age', convert = int),
        pet = get_input(label = 'pet status [y/n]', convert = yesno),
    )
    print(d)

def yesno(x):
    if x in ('yes', 'y'):
        return True
    elif x in ('no', 'n'):
        return False
    else:
        raise ValueError(f'Invalid yes-no: {x}')

def get_input(label, convert):
    while True:
        reply = input(f'Enter {label}: ')
        try:
            return convert(reply)
        except (ValueError, TypeError):
            print('Invalid reply')


Data and vtables vs. objects and methods

This is the first time I have heard "vtabels", the more known term is decision table. Also, on the contrary, using decision tables is very idiomatic JavaScript and is used often, just rarely with lambdas and more often with named functions.

Also, your rows array (is this a global intentionally?) uses rows implying it's a row where every element is a single object.

That said, JavaScript has functional methods like Array.prototype.map, Array.prototype.filter and Array.prototype.reduce.

You can use those to map, filter and reduce things.

For example, your code (assuming it sums ages) could be written as:

var rows = [{id: 0, name: "Alice", age: "23"},
            {id: 1, name: "Bob", age: "25"} /* ... */];

var ageSum = rows.reduce(function(accum,next){return (+next.age)+accum},0);
ageSum; //48

Given the more functional style, your SQL WHERE becomes .filter

rows WHERE name = 'Bob'

Becomes:

rows.filter(function(name){
    return name==="Bob";
})

Similarly, aggregators become .reduce and mappings (and joins) become .map.


As you already noticed, your code will loop forever if all array elements
are false, so you have to check first if at least one element is true.

If the array has \$ N \$ elements with \$ t \$ of them being true, then
the probability that a random number in the range \$ 0 ... N-1 \$ is
"valid" is \$ t/N \$. This means that the expected number of iterations
is \$ N/t \$. For example, if half of the possible directions are valid,
you'll need 2 iterations in average. If only 1% are valid, you'll need
100 iterations in average.

Here is a possible alternative which needs only a single random number.
As I am not so familiar with C#, I'm
describing the algorithm only.

Count the number \$ t \$ of true elements in the array.
Terminate if \$ t = 0 \$.
Compute a random number \$ i \$ in the range \$ 1 ... t \$.
Traverse the array once to find the \$i^\text{th} \$ entry which is true.
The index of that element is your result.


Looping through the ResultSet efficiently and the add the values for columns in List

I am not that familiar with JDBC, but I think the method you search for is: isBeforeFirst: "true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows"

This does not modify the results cursor then.

if (id >= startValidRange && id <= endValidRange)

I would change it to:

if (startValidRange <= id && id <= endValidRange)

Only a small change, but increase readability a lot (at least for me)


How to simply express a desire to run a function when two properties are true?

jQuery.Deferred, or even just promises in general, would make your code simpler. In short, a promise can be unfulfilled, fulfilled, or failed. jQuery.when lets you compose multiple promises into one promise that's fulfilled when they're all fulfilled or failed as soon as one fails. This means that you can

create Deferreds for each event you want to monitor:

var userLoaded = new $.Deferred();
var playerReady = new $.Deferred();

Resolve the promises when whatever event they represent has completed, e.g.:

userLoaded.resolve();

If there's an error, you can signal that if you want as well:

userLoaded.reject();

Compose them together:

$.when(userLoaded, playerReady).then(function() {
    require(['foreground']);
});

If you pass a second argument to then, it will be called if either of the promises are rejected, simplifying error-handling, should you wish to do that.


Laravel controller Single Responsibility principle

Here are some simple tips on how you can improve your code. There are still more you can do to improve it, but is a good start and it helps you get closer to the single responsibility principle.

Move the API request to a service (App\Services\ProductsApi\Client).
Move the formatting of city to a helper (App\Helpers\Format).
Consider moving the formatting of city to CityRequest so the controller doesn't have to do it.
No need for new variables, use the properties returned by $response instead.
No need for else-statement, since the if-statement has return.

Your controller:

use App\Services\ProductsApi\Client;

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

public function displayData(CityRequest $request)
{
    if (isset($request->validator) && $request->validator->fails()) {
        return redirect()->back()->withErrors($request->validator->messages());
    }

    $response = $this->client->getRecommended(
        App\Helpers\Format::slugify($request->city)
    );

    if ($response->error) {
        return redirect()->back()->withErrors([
            'city' => $response->error
        ]);
    }

    return back()->with([
        'city' => $response->city ?? null,
        'condition' => $response->current_weather ?? null,
        'products' => $response->recommended_products ?? null,
    ]);
}

Helper:

public static function slugify($value)
{
    return Illuminate\Support\Str::slug(
        iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $value),
        '-'
    );
}

(None of the code above is tested)


Shutdown-Script for Don't Starve Together Dedicated Server

table.getn has been deprecated for more than 2 years now.
Why iterate only until n-1?
I'd prefer using the string.format over plain concatenation. This is just a personal preference, as the strings are easier to read that way.
Although you do not need to pass true to the c_shutdown, do mention in a comment what it does. Maintaining comments is a nice way to recognise engine specific hard-bound parameters; without having to refer the docs again.
Iterate over the table using ipairs

Rewritten, the code would be:

local function sleep(seconds)
    local diff, t = 0, os.time()
    while diff < seconds do
        diff = os.difftime(os.time(), t)
    end
end

local steps = {
  120, 60, 30,
  10, 5, 4, 3,
  2, 1
}
local notice = "The server shuts down in %d seconds"

for _, secs in ipairs(steps) do
  TheNet:SystemMessage(notice:format(secs))
  sleep(secs)
end
TheNet:SystemMessage("The server is shutting down now")
c_shutdown(true)  -- true parameter implies that the game will be saved


Get collection of objects from CSV string and vise-versa

I would suggest using the new() generic type constraint. Using Activator means you can match a private constructor which you would no longer be the case with the generic constraint but you would be able to catch incorrect use at compile time. Currently, if I tried to use a class like:

 public class Foo
 {
     public Foo(string bar, double baz) { /* ... */ }
 }

Your class would throw at runtime (a MethodMissingException I believe). If you added where T : class, new() instead of just where T : class, trying to use your class with the Foo type would produce a compile time error. An error I can fix before having to run the code is the most helpful kind.

Doing reflection in a loop when you don't need to is not a good thing. You do this for every line in the input file:

 T obj = GetObject();
 Type t = obj.GetType();
 PropertyInfo[] props = t.GetProperties();

You can create this all before processing the file and you don't need to create an instance to get the type information:

PropertyInfo[] props = typeof(T).GetProperties();

for (int i = 1; i < _csvLines.Length; i++)
{
    T obj = GetObject(); // or T obj = new T(); with the constraint added.

You probably want the PropertyInfo[] to be an IDictionary<string, PropertyInfo>. to simplify the lookup by column name.

As for whether this should be a class or not... If you do the reflection in the constructor and keep the instance around to process multiple files then I think it is okay to be a class to save on having to do the reflection over and over again.

If you are going to create an instance to process a file and then throw it away, or if you don't move the reflection to the constructor, I think it would be better as a static class with 2 methods as the other review suggests.

It's spelt: "separator" not "separetor". You've used both spellings. It's a word that I almost always spell wrong too :)


Creating a filtered list by comparing one list to another other list - Python

Unnecessary format strings
Unless you intend to format a string right then and there, you don't need an f before it.
Regex
This can be reduced to one line using regex:
import re

l3 = [item for item in l1 if re.match(r"\w{3,5}[.]\d\s[=]\s\d{1,}", item)]

Explanation

\w{3,5} matches any word character (equal to [a-zA-Z0-9_])

{3,5} Quantifier — Matches between 3 and 5 times, as many times as possible, giving back as needed (greedy)

Match a single character present in the list below [.]

. matches the character . literally (case sensitive)

\d matches a digit (equal to [0-9])

\s matches any whitespace character (equal to [\r\n\t\f\v ])

Match a single character present in the list below [=]

= matches the character = literally (case sensitive)

\s matches any whitespace character (equal to [\r\n\t\f\v ])

\d{1,} matches a digit (equal to [0-9])

{1,} Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)


Take a look at ReactiveExtensions (or specifically ReactiveUI). Then use something like in your VM constructor

this.WhenAnyValue(x => x.SearchString).Throttle(TimeSpan.FromMiliseconds(50).Subscribe(_ => Fitler.Refresh())

This will wait a little between each keystroke before starting the filter.

On the other hand, checkout DerivedCollection - it can move the filtering out of the UI thread, only pushing additions and removes of single items (or calling the full reset or ReactiveList if changes are big, you can set the threshold) to UI.

Still, your solution should be fast enough. Remember that it vastly depends on your DataTemplate for your filtered items - if it is complicated, most cost will be in displaying, not in filtering - especialy that it has to be done on UI thread.


It is not thread safe. You can use Lazy type to create a variable of HTML5Video in a thread safe manner.

Lazy<HTML5Video> dailyHtml5Video = new Lazy<HTML5Video>(() => new HTML5Video());
public HTML5Video DailyHtml5Video
{
    get {return dailyHtml5Video.Value;}
}

You can read about different versions of Singleton pattern here http://csharpindepth.com/articles/general/singleton.aspx


If you have another point to improve, please comment or answer, I will change the accepted answer

To change the require I use the composer.json classmap like this (follow this answer: Import Class without autoload and repository):

"autoload": {
    "classmap": [
        "./vendor/CakePHP-ImageTool-Component"
    ]
}

I don't use require now.

In saveFileLFS method now I'm using Exception if something don't work.

public function saveFileLFS($stringSeparator, $storeName, $productName)
{
    $key = $storeName . $stringSeparator . $productName . $stringSeparator .
        $this->request->data['Media']['file']['name'];
    if(!StorageManager::adapter('Local')->write($key,
        file_get_contents($this->request->data['Media']['file']['tmp_name']))){
        throw new MissingHelperException();
        //Or other Exception
    }
}


D.R.Y.

There is a widely accepted principle amongst developers: Don't Repeat Yourself. The following block appears three times (with varying spacing):

$("table").find("tr").each(function(index) {
    if (index === 0) return;
    var id = $(this).find("td").first().text();
    $(this).toggle(id.indexOf(value) !== -1);
});

That can be abstracted into a function (which could accept a parameter for the value) which could then be called in place of that repeated block.

For example:

function toggleRowsWithKeyword(value) {
    $("table").find("tr").each(function(index) {
        if (index === 0) return;
        var id = $(this).find("td").first().text();
        $(this).toggle(id.indexOf(value) !== -1);
    });
}

And usage:

function search() {
  $("#myInput").keyup(function() {
      toggleRowsWithKeyword(this.value);
  });
}
$('body').on('click','#searchFonts',function(){
    toggleRowsWithKeyword("Font");
});
$('body').on('click','#searchScripts ',function(){
    toggleRowsWithKeyword("script");
});

Cache DOM lookups

Even with abstracting that code into a function, it would still be performing a query on the DOM.

$("table").find("tr")

That can be stored in a variable (or constant if ES-6's const is used):

var rows = $("table").find("tr");

To be on the safe side, that assignment can be placed inside a DOM-loaded callback (e.g. a function wrapped to the jQuery callback wrapper: $()):

$(function() {  //DOM is ready
    var rows = $("table").find("tr");
    //Define  toggleRowsWithKeyword(), add click handlers, etc.
});

Then the function can utilize rows instead of querying for the rows:

rows.each(function(index) {...

CSS Selector for all except first row

The CSS Selector:

var rows = $("table").find("tr")

Could be simplified to:

var rows = $("tr")

And the check for the first row (i.e. if (index === 0) return;) could be eliminated using the :not pseudo-class along with :first-child:

var rows =  $("tr:not(:first-child)")

More tips in article

For more tips about improving Javascript that interacts with the DOM, see this post: Stop Writing Slow Javascript. I know it bashes jQuery initially but it has some very helpful tips (and nice quotes).


Reading a file without blocking the main thread

Not much to remark on. Beside some lack of documentation about which thread each function is expected to run in.

You can also do incremental append as you are reading to let the user see you are still doing something in case the file is really massive or slow to read:

def read_employees(self,read_file):
    emp_list = []
    with open(read_file) as f_obj:
        for line in f_obj:
            emp_list.append(line)
            if len(emp_list) > 5 #adjust as needed
                wx.CallAfter(self.combo.Append, emp_list)
                emp_list = []
    wx.CallAfter(self.combo.Append, emp_list)


Check if a string has 20 numbers in a row in it

If you use a regular expression to look for 20 digit characters (\d) in a row, then the code would be compact and the goal would be visible at a glance:

var twentyDigits = /\d{20}/;
if (twentyDigits.test(myString)){
  console.log("My string has 20 running numbers");
}

You can shorten this further as just:

if (/\d{20}/.test(myString)) console.log("Yup. 20");


Product of all but one number in a sequence

Here are some things that may help you improve your code.
Use all required #includes
The code uses memcpy, so it should #include <string.h>.  It might still compile on your machine, with your compiler, but it's not portable.
Think about potential errors
As one of the comments correctly notes, if one of the entries has the value of zero, this line will have a problem:
nums[i]=sum/nums[i];

Also, what happens if the passed arr_size is zero or negative?  What should the function return if there is exactly one item in the array? What if the passed pointer is NULL?
Follow directions exactly
The problem says to "return a new array" but that is not really what this code is doing.  This code is overwriting the input array.  One of the problems with that is that it's not possible to call this with a const pointer as mentioned in the next suggestion.  It also means that rather than returning a meaningless constant value in all cases, the function should probably return a pointer.
Use const where practical
As mentioned above, the code should return a new array rather than overwriting the passed one.  I would suggest that the function should be something like this:
int* exclusive_product(const int* nums, size_t nums_size)

Note that first, we use const and second, we use size_t rather than int for the second argument to more clearly indicate the type of variable we are expecting.
Use better variable names
I would say that nums, size and i are good variable names, but that fun and fun2 and definitely sum are not.  The problem is that fun doesn't tell the reader anything about what the code is supposed to do and sum is actually misleading (it's a product, not a sum).
Think about an efficient way to solve this
The \$O(n^2)\$ code you have in fun2 is not a terrible way to solve the problem and has the advantage of being obviously correct.  When I interview people, I typically like such answers because it's much easier to make slow correct code fast than it is to make fast incorrect code correct.  However, in a good interview, I like to ask the candidate to make comments on his or her own code, including any limitations, assumptions or potential improvements that might be made.  In this case, it helps if we think mathematically about the final values in the resulting array \$B\$ from input array \$A\$.  For example, we know that every value \$B_j\$ can be expressed as the product $$\displaystyle B_j = \prod_{i=0}^{j-1} A_i \prod_{i=j+1}^{n-1} A_i$$ if \$n\$ is the length of the array.  This suggests a more efficient approach I'll leave for you to figure out.


Retrieving multiple versions of source code for a file

If you upgrade to Java 7, you can use the new Multi-catch syntax. You could change the first block to:

    try {
        fileName = RestServices.getInstance().getClassName(getSourceCodeURI());
    } catch (ClientProtocolException | IOException | RestServicesException e) {
        fileName = "not available";
        e.printStackTrace();
    }

Essentially if there are many exceptions you catch and handle in the same way, you can use multi-catch


Printing right triangles recursively in Haskell

The recursion you used is very cumbersome, and should be avoided in favour of more expressive solutions in Haskell.  You figured out how to write replicate n c — why didn't you just run with that?  Add some list comprehensions, and you're done!

Instead of using recursion in printTriangle to print one line at a time, you can just write putStr $ unlines.

Naming each function starting with "make…" feels a bit redundant to me.

Splitting the menu between getTriangleType and makeTriangle is awkward.  You're using an integer to represent the type of triangle, and the two functions have to agree on which number represents which orientation.  The most natural way to represent a type of triangle is to use the corresponding triangle-generating function itself!  And I'd define a type synonym TriangleMaker for those functions.

type TriangleMaker = Char -> Int -> [String]

topLeftTriangle :: TriangleMaker
topLeftTriangle c n = [replicate i c | i <- [n, n-1 .. 1]]

bottomLeftTriangle :: TriangleMaker
bottomLeftTriangle c n = [replicate i c | i <- [1 .. n]]

topRightTriangle :: TriangleMaker
topRightTriangle c n =
  [(replicate (n - i) ' ') ++ (replicate i c) | i <- [n, n-1 .. 1]]

bottomRightTriangle :: TriangleMaker
bottomRightTriangle c n =
  [(replicate (n - i) ' ') ++ (replicate i c) | i <- [1 .. n]]

getTriangleType :: IO TriangleMaker
getTriangleType = do
  let menu = [topLeftTriangle, bottomLeftTriangle, topRightTriangle, bottomRightTriangle]
  putStr $ unlines [
    "What type of triangle do you want to print? (1, 2, 3, or 4)",
    "1) Top Left",
    "2) Bottom Left",
    "3) Top Right",
    "4) Bottom Right"]
  line <- getLine
  return (menu !! ((read line :: Int) - 1))

main :: IO ()
main = do
  triangle <- getTriangleType
  size <- getLine
  putStr $ unlines $ triangle '*' (read size :: Int)


Is there a method to add multiple properties to HtmlTextWriterStyle?

Under normal circumstances, you could use collection initializer to write your code this way:

var dynDiv = new HtmlGenericControl("Div")
{
    ID = "dynDiv",
    Style =
    {
        { HtmlTextWriterStyle.BackgroundColor, "Red" },
        { HtmlTextWriterStyle.Position, "absolute; left: 500px; top: 500px" },
        { HtmlTextWriterStyle.Height, "30px" },
        { HtmlTextWriterStyle.Width, "300px" }
    },
    InnerHtml = "New Object"
};

Unfortunately, this code won't compile, because CssStyleCollection doesn't implement IEnumerable, which is a requirement for collection initializers.


Recyclerview Adapter for weather app - Makes API calls for each item

First issue

You're calling the weather API on every OnBindViewHolder(), which means it will get called for each visible row, and on new rows entering, or re-entering the screen. So if you scroll the list a few times you will call the API for each city more than once.

Second issue

Your Adapter shouldn't make any API calls. In fact, it should only concern itself about displaying cities.

How can we solve this?

Your MyCity model should provide all information necessary to display the weather.

So let's add city name and temperature to your model.

Next we create a service which iterates over the cities and calls the API once for each city. This can be a regular Android Service for example, or something more advanced like WorkManager.

This logic will be triggered from your ViewModel.

Depending on how frequent you want the weather updates to be, you can call this each time you open the screen, or on certain intervals.

In all cases, once you get the response back, you need to persist the new data to your database.

Since you are observing the data, the adapter will be automatically notified of changes.

Note: when retrieving the cities to call the API you shouldn't use LiveData because when you update the city it will re-trigger the LiveData and you find yourself in an endless loop.

Your Dao will look something like this:

@Dao
public interface CitiesDao {

    @Query("SELECT * FROM cities")
    List<MyCity> getCities();

    @Query("SELECT * FROM cities")
    LiveData<List<MyCity>> observeCities();

    // etc

}

This is just the starting point.

More things you can consider:

Use different models for data and UI (e.g. MyCity and MyCityUiModel)
Use the Repository pattern


Input validation

A 0-sided dice for example 3d0 will raise an exception with an ugly stack trace. Since technically it's in "3d8 format", perhaps an additional validation will be a good idea.

Printing error messages

It's a common practice to print error messages to stderr instead of stdout.

Following the pythonic way

A good start will be to follow PEP8, notably:

the spaces in int( matched.group(1) ) should be removed
if len( matched.group(1) ) can be simplified to if matched.group(1)

The only thing that limits this script to Python 2.x is the print statements. You can easily make this work in Python 3.x by changing the print statements to print(...) function.

String concatenation is a bit awkward, for example you have to manually convert integers to strings. Instead of this:

    print "\troll " + str(z) + ': ' + str(rolled)

The recommend way:

    print("\troll {}: {}".format(z, rolled))

(Nice pun with the "troll" btw :-)

User-friendliness

An example output looks like this:

2d6:
  roll 0: 6
  roll 1: 2
  total: 8/12

"roll 0" huh... D&D is a nerdy thing, but not really in that way... The roll indexes would be better 1-based instead of 0-based in the output.

Variable span

The span of a variable is the lines between two statements that use it.
In this code, roll_sum has a large span. It's initialized early on, but not used until much later.

    print roll + ':'
    roll_sum = 0
    count = 0
    if len( matched.group(1) ):
        count = int( matched.group(1) )
    else:
        count = 1
    sides = int( matched.group(2) )
    for z in range(count):
        rolled = randrange(1, sides+1)
        print "\troll " + str(z) + ': ' + str(rolled)
        roll_sum += rolled

It would be better to move the initialization further down, right before the variable is actually used.

I would also move the print roll + ':' down closer to the statements that do the printing, so as to group similar operations together.

And some empty lines will be nice to create a visual grouping of closely related statements.

Misc

Instead of randrange, you can use randint for an inclusive range.
That is, randrange(1, sides+1) can be written equivalently as randint(1, sides).

Although it's "intelligent" to combine the rolling, summing and printing steps, the code would be slightly cleaner if these were separated. Something like this:

rolls = [randint(1, sides) for _ in range(count)]

for i, rolled in enumerate(rolls):
    print("\troll {}: {}".format(i + 1, rolled))

possible = sides * count
print("\ttotal: {}/{}".format(sum(rolls), possible))

Inside the main for loop for the arguments,
the if branch has a long body and the else branch just one line.
By the time you read the else branch,
the reader might have forgotten what the if was about.
In situations like this it might more readable to flip the branches.
Actually, once there, eliminating a branch becomes an option too, like this:

if not matched:
    print roll + ' is not a dice in 3d8 format'
    continue

# valid case, no more "else" branch, flatter code