Goroutine wait select operation on multiple channels

Not sure whether this site is the best place to ask this question, but the answer is quite simple. I'll answer the question, give a few alternatives, pro's and con's and some actual code-review on the little snippet you provided.

  Do not communicate by sharing memory; instead, share memory by communicating

This is the main idea behind channels. When talking about communicating and sharing memory, it's obvious we're talking about concurrency. The example you have isn't really dealing with concurrency all that much. Such an artificial example will almost always be fairly limit in explaining the mechanisms/concepts behind something that is, effectively, a weapon in the armoury of concurrent programming. Either way, worth checking out the effective go document for more on this.

To answer your question:

Looking at the select spec:

  A "select" statement chooses which of a set of possible send or receive operations will proceed.

Then, from the steps that a select statement executes, there's 2 steps to pay attention to:

  one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

And:

  The statement list of the selected case is executed.

This means that, even if both channels are ready to be read/received from, the select statement will only ever read from a single channel. Which channel that is, is not specified (other than the channel is chosen via a uniform pseudo-random selection).

If you'd have:

errs := make(chan error, 1)
success := make(chan struct{}, 1)
defer func() {
    close(errs)
    close(success)
}()
errs <- errors.New("some error")
success <- struct{}{}

select {
case err := <-errs:
    fmt.Printf("Receiver error: %+v\n", err)
case <-success:
    fmt.Println("Success received")
}

You would have no way of knowing which channel you'd read from.

Some code review:

You may have noticed, too, that I've changed a couple of things. This being a code-review site and all, here's why I made the changes I did:

Success or done channels are either unbuffered (indicating success/done on close), or are best defined as chan struct{}. A boolean can be false or true, indicating that the value does have a meaning to its receiver. Again as per spec, a type struct{} is defined as 0 bytes in size (slightly more optimised than bool), and clearly indicates the channel serves to signal something, rather than communicate something.
errors.New("Some error")  should be "some error". Error values should start with a lower-case letter. Check golang CodeReviewComments for details. There's a lot of conventions there, and overall the community seems to have adopted them.
I added a defer func(){}() to close the channels. It's bad form to not close channels...

Either way, the double select statements are there to ensure both channels are read.

More details

Be that as it may, having a quick look at the linked post, seeing as a waitgroup is used in the accepted answer, I'd probably prefer something more like this:

errs := make(chan error) // not buffered
success := make(chan struct{}) // not buffered
go func() {
    errs <- errors.New("some error")
}()
go func() {
    success <- struct{}{}
}()
err := <-errs
fmt.Printf("Received error: %+v\n", err)
close(errs) // we're done with this channel
<-success
close(success) // all done
fmt.Println("Success")

The trade-off being: You will always wait for the error channel before reading the success channel. The advantage: no waitgroup required, no verbose select statement...

Should you want to maintain the random-like output (having success and error printed out in a random order), you can easily replace the ordered reads from the channels 2 select statements, or use a waitgroup and read from the channels in routines:

func main() {
    errs := make(chan error) // not buffered
    success := make(chan struct{}) // not buffered
    wg := sync.WaitGroup{}
    // start reading from channels in routines
    wg.Add(2)
    go readRoutine(&wg, errs)
    go readRoutine(&wg, success)
    // routines are needed because the channels aren't buffered, writes are blocking...
    go func() {
        errs <- errors.New("some error")
    }()
    go func() {
        success <- struct{}{}
    }()
    wg.Wait() // wait for reads to have happened
    close(errs) // close channels
    close(success)
}

func readRoutine(wg *sync.WaitGroup, ch <-chan interface{}) {
    defer wg.Done()
    v := <-ch
    if err, ok := v.(error); ok {
        fmt.Printf("Received error: %+v\n", err)
        return
    }
    fmt.Println("Received success")
}

Now we're almost there... The rule of thumb is that the routine creating the channels should also be responsible for closing the channels. However, we know that the anonymous routines are the only 2 that are writing to the channels, and they are created and spawned by main, and they even access its scope. There's 2 changes we can make, therefore:

go func() {
    errs <- errors.New("some error")
    close(errs) // we can close this channel
}()
go func() {
    close(success) // we don't even have to write to this channel
}()
wg.Wait()
// channels are already closed

Hope this answered your question, provided some useful links to resources that can help you answer future questions, and maybe gave you a few ideas of how to use channels.


Saves Individual Worksheets as Workbooks in destination folder

What you're looking for is to turn off screenupdating, turn off alerts and auto-save and close.

    Application.DisplayAlerts = False
    ThisWorkbook.Save
    ThisWorkbook.Close False

So, like this -

Option Explicit

Sub SplitSheetsToBooks()
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Const PATH_TO As String = "C:\TEMP\"
    Const EXCEL_EXTENTION As String = ".xlsx"

    Dim index As Long
    Dim numberOfSheets As Long
    Dim targetSheet As Worksheet
    numberOfSheets = ThisWorkbook.Sheets.Count

    For index = 1 To numberOfSheets
        Set targetSheet = ThisWorkbook.Sheets(index)
        targetSheet.Copy
        ActiveWorkbook.SaveAs PATH_TO & targetSheet.Name & EXCEL_EXTENTION
        ActiveWorkbook.Close False
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


Make each element equal to its neighbouring element which is maximum in a matrix

please avoid them and focus on the problem here.

  The problem is my time complexity to traverse is going too high.

No, your variable naming and abuse of C++ features is also a problem. For the most part your code is structured OK. It's moderately understandable, but fixing those things could make it really easily understandable. You do need to think about these things, not just so others can read your code, but so your future self can understand it, too.

Naming

Your variable names are not clear at all. I'm all for 1-letter variable names for loop control variables like i and j. But you've gone too far for anyone who wants to understand your code. It's not hard to change t to numMatrixes or if you really need short names, numMats. (Also, you didn't really describe that there was more than one matrix in your description. Did I understand that correctly?) n and m should be numRows and numColumns (or numCols).

Your actual matrixes should have better names, too. a should be paddedMatrix. maxi is better than your other names. ma should be maxEntry. counti is also ambiguous. What is it counting? It looks to me like it's counting the number of values that match the maximum value, so maybe call it matchCount or numMatches?

Whitespace

This code is very dense and difficult for a human to parse. I recommend using far more whitespace in your code. For example, I'd put spaces before and after every operator. That means =, ==, +, -, >>, etc.

Also, you should add some empty lines between blocks of functionality from time to time. For example, between the for loops, the if statements, andwhile loops. Even better would be to…

Use Functions

I see 3 things happening in the outer while loop. You're:

Reading in the input values for the array (while finding the maximum element)
Replacing each element in the array with the maximum of its neighbors
Finding the number of times you need to do that until you've filled the array with the maximum values

Each of those things should be a separate function.

Careful with continue

The continue keyword is essentially a goto. As such, it can make code flow harder to understand than it needs to be. I don't think your use of it adds anything, so I'd remove it in favor of using else clauses in your ifs. For example in the first inner loop, I'd change it to look like this:

            if(i == 0 || j == 0 || i == n + 1 || j == m + 1)
            {
                a[i][j] = 0;
            }
            else
            {
                cin >> a[i][j];
                flag[i][j] = 0;
                if(a[i][j] > ma)
                {
                    ma = a[i][j];
                }
            }

It does the exact same thing, but is much clearer. Now I don't have to think, "does the continue apply to the inner or outer loop?" I just automatically understand what happens when the code runs.

I'd do the same thing with the other continue.

Avoid magic numbers

You have a couple of uses of the number 8. What does it represent? Does it need to change if you change anything else in the code? It appears that you're trying to use the number of values in the myints array. If that's what you want, you should use that directly. You can write it as:

const int numMyInts = sizeof(myints) / sizeof(myints[0]);

Stop Abusing C++

You say you know that using namespace std is bad, but you do it anyway. My compiler can't even find bits/stdc++.h, so I had to include the 2 headers you actually need: algorithm and iostream.

Errors and Warnings

My compiler (llvm) won't actually compile your code. It points out the error you have in the myints array. It's only big enough to hold ints, but you're trying to copy long ints into it. This might work for small values, but not for values that exceed the size of int.

You have an unused variable k. You should remove it.

Your algorithm fails for negative values.

Performance

In order to understand what's causing your code to be slow, you should profile it. That will tell you for certain where the slowdown is. You will often be surprised by the answer.

My first guess (and it's best to test it rather than guessing, because guesses are often wrong) is that it's costing you a lot of time copying the neighboring elements into the myints array. I wonder if you could avoid the copies by using some pointer arithmetic? Finding the max of several values is simple enough that you probably don't need to call max_elements(). You could manually unroll the loop into something like this:

const long int kRowStride = numCols - 2; // Number of elements to skip to get to the right element in the next row
long int *nextInt = &a[ i - 1 ][ j - 1 ];
long int currentMax = *nextInt;
nextInt++;
currentMax = std::max(currentMax, *nextInt);
nextInt++;
currentMax = std::max(currentMax, *nextInt);
nextInt += kRowStride;
//… etc.for the remaining 2 rows

It's possible that there's some matrix operation that will do the equivalent of your search in fewer steps. I don't remember enough matrix math to know off the top of my head whether that's true or not, but often the best optimization is not to optimize your algorithm, but to find a better algorithm. So I'd explore that route, as well.


Creating a list containing the rank of the elements in the original list

I believe your solution is \$O(n^2)\$, and we can reduce that to \$O(n \log n)\$. I'm not well-versed in python, but this is the general idea:

The output is a permutation of the indices \$0, 1, \ldots, n - 1\$, where \$n\$ is the length of the input.
We sort the indices based on the element at the specified index. In your example, we get \$6, 0, 4, 1, 2, 3, 5\$, i.e. the \$6\$th element (\$3\$) is smallest, so \$6\$ is first.
Seeing that \$6\$ is at index \$0\$, we know that the \$6\$th element of the output is \$0\$, and so on. This step is easier to explain in code than in words, sorry about that.

In code,

indices = list(range(len(input)))
indices.sort(key=lambda x: input[x])
output = [0] * len(indices)
for i, x in enumerate(indices):
    output[x] = i

Or the more terse

output = [0] * len(input)
for i, x in enumerate(sorted(range(len(input)), key=lambda y: input[y])):
    output[x] = i

I used the timeit module to compare the running times of this version and the original for different input sizes. The functions were each called 1,000 times on randomly shuffled input of size \$n\$. Here are some of the results

   n     this version (s)  original version (s)
  10                 0.02                  0.04
 100                 0.17                  1.40
1000                 1.81                133.35

This is asymptotically optimal, since if it were not, we would have a sub-linearithmic comparison sort:

sorted = [0] * len(input)
for i, x in enumerate(output):
    sorted[x] = input[i]


I don't think I'd get so fancy with the grouper; the data is small, a constant table will do:

comma_after_digit = set(3, 5, 7, 9, 11, 13, 15, 17)

result = '.' + ''.join(map(str, fractional_part))
for i, d in enumerate(integer_part_digits):
    if i in comma_after_digit:
        result = ',' + result
    result = d + result
result = {0:pos, 1:neg}[sign] + result
return result

Also:

Try and be a bit more consistent: you use reversed() to reverse a string on one line, and then the next you use [::-1].  You also use map(str, digits) in one place and [str(x) for x in digits] another! They do the same thing, but it's nice to the reader to pick one idiom and stick with it.
thousand = ''.join(islice(integer_part_digits, 3))[::-1] can be simplified into thousand = integer_part_digits[-4::-1]
Using .format() is overkill for concatenating strings.  + works just fine.  If you want to use it, you should 1) factor out constant strings (like the decimal point) and 2) use the args as your temporary variables, like:

return '{sign}{curr}{hundreds}{sep}{thousand}.{fractional_part}'.format(
    sign=neg if sign else pos,
    curr=curr,
    thousand=integer_part_digits[-4::-1],
    sep=',' if exponent > 3 else '',
    hundreds=','.join(map(''.join, grouper(integer_part_digits, 2, fillvalue='')))[::-1],
    fractional_part=''.join(map(str,fractional_part)) if fractional_part else ''
)

According to the wikipedia page you cite, there's no comma after the 1 in 10**19, so your code is wrong :) ... which leads inevitably to:
Needs tests!


Yes you forgot to cover some cases.

Your compiler should be able to detect one of them. Here is what ghc -Wall says:

slice.hs:2:1: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for `slice':
        Patterns not matched: [] _ (GHC.Types.I# #x) with #x `notElem` [0#]

slice.hs:4:8: Warning: Defined but not used: `x'

This version fixes those two warnings:

slice []     _ _ = []
slice _      _ 0 = []
slice (x:xs) 1 k = x : slice xs 1 (k-1)
slice (_:xs) i k = slice xs (i-1) (k-1)

But it is still incorrect, because there is another case that the compiler doesn't warn you about: a negative k value. Your code will return the entire list instead of an empty list.

Consequently, if you use a negative k on an infinite list you get an infinite loop:

> print $ slice [1..] 1 (-1)
[1,2,3,4,5,6,7,8,9,...


Approximating square root (loops and functions exercise)

One tiny thing: If you drop one set of parentheses:

return z - ((z * z - x) / (2 * z))

and then run go fmt, it will change it to

return z - ((z*z - x) / (2 * z))

The expressions around the * are close to the * and the expressions around the - are spaced out. In other words, go fmt implies the correct precedence.

Also, using line breaks to separate "sections" of a function is good, but there's no need to add an extra linebreak at the very beginning of a function or just before a }.


MATLAB and Armadillo, hints on translating

You're doing a copy in most of those snippets: if it was possible to do without a copy, it could be faster. Libraries such as Boost often offer two version a specific function: one which copies and another one which modifies in place.
*i is enough, you don't need (*i):

*i = log(*i);

This code:

if ( _s.is_empty() )
    return true;
else
    return false;

can be written as:

return _s.is_empty();


REST API to list books, where null means "everything"

I personally think it's fine, but it helps to turn your thinking around from a "selector" to a "filter". Then, the default is to return all books, and you selectively filter down the set you're going to eventually respond with.

(Note I haven't written Java in a long time, so grain of salt here,) I might specify a BookFilter object which can incrementally have fields set from the parameters, and then have BookDTO.filterBooks. Then, your request method becomes:

public ResponseEntity getBooks(@RequestParam(required = false) String genre) {
    BookFilter filter = new BookFilter();
    if (genre != null) {
      filter.setGenre(genre);
    }

    return filterBooks(filter);
}

I know it's not directly applicable (your DTO probably doesn't work this way, based on what you described above), but I think what you're doing with the null check in your controller is pretty much the same thing with the tools you've got.

You might consider trying to refactor your DTO so it can work with filters however, because eventually you may want ?genre=scifi&published=1970+&publisher=penguin etc. etc., at which point it'll be a lot easier to manage a single filter object than a bunch of explicit queries.


Nested loops - Random Forest, multiple parameters

Reproducible Example

Unfortunately, the code snippet that you gave does not lend itself to being reproducible. So, the advice being given is constrained.

Caches are nice

There are certain times where you should be caching a summation if the value is known to be constant through different iterations. In this particular case, we have: sum(train.target) and sum(TARGET3) that should be cached. Say:

stt = sum(train.target)
st3 = sum(TARGET3)

Knowledge (of size) is Power!

Immediately, one of the key issue you will face is the fact that you are rbind 60 items since you avoid giving stable numerical entries in the data.frame

## parameteres

ntrees <- c(300, 500)
zeros <- sum(train.target) * c(1, 2, 3, 4, 5)
mvars <- c(30, 50, 70, 90, 110, 130)

nitr = length(ntrees)*length(zeros)*length(mvars)

model_eff <- data.frame("ntrees" = numeric(nitr),
                        "zeros"  = numeric(nitr),
                        "mvars"  = numeric(nitr),
                        "eff"    = numeric(nitr),
                        "0_0"    = numeric(nitr),
                        "0_1"    = numeric(nitr),
                        "1_0"    = numeric(nitr),
                        "1_1"    = numeric(nitr),
                        "predict_sum" = numeric(nitr),
                        "triangle"    = numeric(nitr),
                        stringsAsFactors = F)

Declare count = 1 before the 3x for loops. Then save results using:

model_eff[count,] = c("ntrees" = ntrees[j],
                      "zeros" = zeros[k],
                      "mvars"= mvars[l],
                      "eff" = eff_measures$eff,
                      "0_0" = eff_measures$c.m[1, 1],
                      "0_1" = eff_measures$c.m[1, 2],
                      "1_0" = eff_measures$c.m[2, 1],
                      "1_1" = eff_measures$c.m[2, 2],
                      "predict_sum" = st3 ,
                      "triangle" = eff_measures$triangle))
count = count + 1

Parallel RandomForest via caret

The only other suggestion I have it to parallelize the build of the random forest via:

# caret modeling framework
library(caret)

# Parallel backend
library(doParallel)

# Register a cluster
registerDoParallel(cores = 5)

rf_model = train(train.target~.,data=train,method="rf",
                 prox=TRUE,allowParallel=TRUE)


Generating and re-using unique, sequential, positive integers

The only improvement I can see here is pretty marginal:

unordered containers have an average insert complexity of O(1), but that can become O(N) in degenerate cases (because of hash collision handling). That's pretty rare, but enough in my book to not use the datastructure if a simpler alternative would work just as well.

In your case, std::unordered_set doesn't provide anything you wouldn't get from a simple std::stack or std::queue anyways. So I would personally switch to one of these.

That being said, depending on the context behind how and why you use such an index generator, there are sometimes better ways to do this.

For example, if you are using this logic in order to manage a small block allocator, you can store the free list inside the unalocated memory. see example


You could write hilo as hilo :: Double -> Double -> [Double], which returns [hi,lo] for lo /= 0 and [hi] for lo = 0. Then you can write partials as

partials x = foldl' (\acc p -> (hilo x p) ++ acc) -> hi:acc []

BTW: How could lo ever become non-zero considering

lo = y - (hi - x) = y - (x + y - x) = y - y = 0

Rounding?


I would do a couple of things differently.
Early escape
Your use of early escape is good and makes the code easier to read but you don't need the else section if the body of if statement returns.
Node* merge(Node* list1, Node* list2)
{
    if (list1 == nullptr){
        return list2;
    }
    if (list2 == nullptr){
        return list1;
    }
    // Main body of code.

This is quite normal. It reduces the number of level of indenting and makes the code look clean.
Self documenting code
I would encourage you to split getting the next item into a separate function (this facilitates self documenting code).
Node* getNextNode(Node*& list1, Node*& list2)
{
    // Work out which list has the smallest value.
    Node*& smallList = (list1->data < list2->data) ? list1 : list2;

    // The head of this list is the result
    Node* result = smallList;

    // Move the list to the next value (notice the call be reference).
    smallList = smallList->next;

    return result;
}

Simplified Body
Now if we rewrite the main body of your code in terms of this helper function;
Node* result  = getNextNode(list1, list2);
Node* current = result;

// Looping over the list until one is empty
// becomes very trivial now.
while(list1 != nullptr && list2 != nullptr)
{
     // Get next node and remove it from its list.
     Node* next    = getNextNode(list1, list2);
     current->next = next;
     current       = next;
}

// One of the lists is empty.
// Add what is left of the other list on the end (ie after current).
current->next = (list1 == nullptr) ? list2 : list1;
return result;


Generic PHP function for making a struct out of multiple resultsets from a stored procedure call

In the way you formed your post it looks like you were asking for a better way to do what you are already doing, which it still apears that you are. That's fine, I just had no idea what you wanted from this code. I had to walk myself through your code step by step, so some of this is just going to be repeating what you've already said in an attempt to affirm it into my mind. I don't know why I was having difficulties before, I guess, as I said, I was just being dense.

First of all, your example function call does not call the same function as the one you provided, though this is most likely just a typo.

Alright, with you so far. You seem to be saying you don't like your current output and that you desire a ResultSet that uses associative indexing rather than numerical indexing, similar to:

array(
    [ "resultsets" ] => array(),
    [ "codes" ] => array(),
    [ "listings" ] => array(),
    [ "users" ] => array()
)

However, the ResultSet I'm seeing does not have this problem. I do see you are using the $row[ 'index' ] as a key for some reason, maybe that is what you mean? You can remove those and just use automatically generated incrementals, which I'll show you below. Let's take a look at that function.

Immediately I see a global. These are bad. Avoid globals at all costs. Globals don't exist. Forget you ever heard of them. If you need a variable to exist outside of the function in which you are using it, have it be the return value. If you need it inside a new function, have it be one of the parameters required to run it. In this case, you probably defined $conn just before this function is called, just pass it as a second parameter. Or rather, pass it as the first and the SQL as the second, that way it makes sense when compared to the other functions. The best way to do this would actually be to use a class and class properties, however this is beyond the scope of this review. I'd recommend becoming a little more familar with the "Don't Repeat Yourself" and "Single Responsibility" Principles, DRY and SR respectively, before attempting to learn OOP. Though SR is not usually abbreviated I will do so to save time.

Your loop seems odd. I'm not familiar enough with SQLSRV to be 100% sure, but it looks like your code is somewhat redundant. The only reason you haven't noticed it is because the internal iterator is smart enough to know better than to reset itself. Your first loop says it will continue looping through the results while there is a next result in the array. Your second, internal loop to the first, says the same. So, because you set up your first loop as a do/while loop, it will immediately perform the first iteration without checking the condition in the first while. So, as the second while loop iterates over the same array its as if that first loop were never there. Once you exit the do statement the internal pointer on the $results array is already pointing to the end of the array, this means when it checks that while statement at the end of the do/while block it will see that its job is already done and proceed with the code. Unless I miss my guess completely, you should be able to remove the do/while loop and this should perform the same.

Now, inside your loop. This is where the DRY and SR Principles begin. SR states that a function/method/class should only be concerned with a SINGLE RESPONSIBILITY. In other words its specialized to perform one task. Usually this task is repeatable, which is where the the DRY principle comes in. DRY states that you should never repeat yourself. If you find that you are performing the same task, create a function/method/class to do that task for you. So, if you want to "fetch" or "get" something, a repeatable task, you create a function that will do just that. And if there are any other smaller tasks associated with doing this one task it should be delegated to another specialized function that does just that. So this one big function you provided could actually be broken up into a few separate, more specialized, functions. So how do we separate it?

Believe it or not, you've already got the ground work laid out for it. Because we are in a loop, anything we do can be considered a repeatable task. While this isn't the only type of "repeatable" task, it is the easiest to spot. Tasks are any group of related actions done to accomplish an end goal. In plain english we refer to a task such as, "do this". In programming we refer to them much the same, but with slightly differnt termanology, such as "if, else, for, while, do, etc...". Sounds pretty daunting, but it isn't. Not everything in an if statement needs to be separated into its own custom function. Usually its already done for us. For example, isset(), count(), and empty() are all predefined tasks that do just one thing. But sometimes we can create a larger task that uses these smaller tasks.

Hopefully with those hints you will be able to figure out how to break this up. I don't want to do all the work for you, else you'll never learn. Now, I will show you a modified if/else statement that shows how to remove those $row[ 'index' ] indices and replace them with auto-incrementing indices. I'll also make a few other improvements and try explaining them below. I don't know enough about your data structure to determine if the initial if/else statement needs to be changed, but I can work with the rest.

if( isset( $row[ 'id' ] ) {
    $resultSetsKey = $row[ 'id' ];
}
if( ! isset( $resultSets[ $resultSetsKey ] ) ) {
    $resultSets[ $resultSetsKey ] = array();
}

if(isset($row['index']) && isset($row['id']) && count($row) == 2) {
    $resultSets[ $resultSetsKey ] [] = $row['id'];
} else {
    $resultSets[ $resultSetKey ] [] = $row;
}

So, first thing you will notice, I moved the code used to set the $resultSetsKey and initial value of that array index, outside of the initial if/else statement. This is to reduce the amount of DRY violations. The new if/else statement is much smaller. Now all its concerned about is which part of the arrow to set to the $resultSets array.

I hope these points helped.


Instead of having a static array of chars You could just use ASCII values from 0x41 to 0x5A. If You still insist having a static array, please consider marking it as a const.

Leaving Your int main() without any return value --- sign of the bad taste, to say the least. Consider having some proper error codes or at least return 0 on proper exit.

Your index of chars (letter2, letter3) can't be negative, so why would You use int instead of uint_* or size_t? Same applies to row and spaces variables.

In case of single char, putchar() is way faster then printf("%c", character).


The code is not optimal. Furthermore, it breaks the single responsibility principle since the method can be broken down to smaller, tighter pieces. For example, the for loop can and should be put in its own method. what this will give you? consider what if in the future you decide to change the folder hierarchy (perhaps add new folder layer or put some files in the root folder etc). what you need is a separate method that can travel along folder tree of any depth and gather the files (perhaps using recurssion?)

Regarding performance:

You call propertyService.getProperties().get("folderLocation") every time the method is called. However, it looks to me like this value is not changed with every call.
String.format is an expensive call since the format is parsed for tokens. Replace that with simple concatanation. and use forward slash - it works for *nix AND Windows systems (the JVM handles it)
You are using pre-java-7 IO library. Java 7 introduced a new, simpler, better, safer, faster library: java.nio. use it.
Each time the method is called, you scan the file system. Depending on the total size of the PDF library - you may consider loading the whole structure into memory. the java.nio has utilities that can alert your program when changes ocur in the file system (like new file or deleted file etc) so you can keep your in-memory tree in sync with the actual file system.
If pre-loading the file system structure is not an option, consider implementing a cache system where you store previous method calls (store an input and its output) and then you can return output for previouisly called input. You will need a cache system like LRU map. There are readily available 3rd party libraries for that.


Outputting flavor text depending on inputted strings

It seems this could be simplified with a small lookup table and then concatenating strings. Using a table as simple as:

const lookup = {
  blue: 'b',
  green: 'f',
  purple: 'g',
  yellow: 'p'
};

we can then lookup the color values and concatenate them together. Combined with a simple check to make sure the color is valid and the 2 colors aren't the same, and it seems to produce the same result.

Here's the full function:

mixItUp: function() {
  this.mixArray.sort();
  const lookup = {
    blue: 'b',
    green: 'f',
    purple: 'g',
    yellow: 'p'
  };

  let mix;
  const color1 = lookup[this.mixArray[0]];
  const color2 = lookup[this.mixArray[1]];

  if (color1 && color2 && (color1 !== color2)) {
    mix = `${color1}${color2}`;
  } else {
    mix = '??';
  }

  return mix;
}

And here it is in action:

function createMix(color1, color2) {
  return {
    mixArray: [color1, color2],
    mixItUp: function() {
      this.mixArray.sort();
      const lookup = {
        blue: 'b',
        green: 'f',
        purple: 'g',
        yellow: 'p'
      };

      let mix;
      const color1 = lookup[this.mixArray[0]];
      const color2 = lookup[this.mixArray[1]];

      if (color1 && color2 && (color1 !== color2)) {
        mix = `${color1}${color2}`;
      } else {
        mix = '??';
      }

      return mix;
    }
  }
}

// Handle the form
const form = document.getElementById('mixitup');

form.addEventListener('submit', event => {
  event.preventDefault();
  const color1 = document.getElementById('color1').value;
  const color2 = document.getElementById('color2').value;

  const mixedArray = createMix(color1, color2)
  console.log(mixedArray.mixItUp())
})
<form id="mixitup">
  <select id="color1">
    <option value="">Select...</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
    <option value="purple">Purple</option>
    <option value="yellow">Yellow</option>
  </select>
  <select id="color2">
    <option value="">Select...</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
    <option value="purple">Purple</option>
    <option value="yellow">Yellow</option>
  </select>
  <input type="submit" value="Mix it up!">
</form>


Optimizing very simple piece of “Game of Life” code by taking advantage of NumPy's functionality

I'll just be cheeky and post a slightly modified version of my SO answer here.

So first things first, you want to get rid of the loops. They are slow to execute.

The first loop:

for x in range(rows):
        for y in range(cols):
            if Z[x][y] == 1:
                if (N[x][y] < 2) or (N[x][y] > 3):
                    Z[x][y] = 0
            else:
                if (N[x][y] == 3):
                    Z[x][y] = 1

could be replaced by:

set_zero_idxs = (Z==1) & ((N<2) | (N>3))
set_one_idxs = (Z!=1) & (N==3)
Z[set_zero_idxs] = 0
Z[set_one_idxs] = 1

Here you are generating boolean arrays that indicate which values satisfy your criteria and then you are setting those values to either 0 or 1.

Benchmarking this we see a significant improvement in speed (x 180):

# new version without loop
In [49]: %timeit no_loop(z,n)
1000 loops, best of 3: 177 us per loop

# original version with loop
In [50]: %timeit loop(z,n)
10 loops, best of 3: 31.2 ms per loop

The second major loop:

for x in range(rows):
        for y in range(cols):
            Q = [q for q in [x-1, x, x+1] if ((q >= 0) and (q < cols))]
            R = [r for r in [y-1, y, y+1] if ((r >= 0) and (r < rows))]
            S = [Z[q][r] for q in Q for r in R if (q, r) != (x, y)]
            N[x][y] = sum(S)

could be replaced by:

N = np.roll(Z,1,axis=1) + np.roll(Z,-1,axis=1) + np.roll(Z,1,axis=0) + np.roll(Z,-1,axis=0)

[Note: this is actually wrong for the game of life, as the code should check for diagonal neighbours as well. This is simply a refactoring of the original for loop construct.]

Here there is an implicit assumption that the array does not have bounds and that x[-1] is next to x[0]. If this is a problem, you could add a buffer of zeros around your array with:

shape = Z.shape
new_shape = (shape[0]+2,shape[1]+2)
# b_z is a new array which will be our buffer
b_z = np.zeros(new_shape)

# set the middle of the array equal to the original `Z`
b_z[1:-1,1:-1] = Z

# do our rolls on the buffered array so that we don't have boundary isssues
b_n = np.roll(b_z,1,axis=1) + np.roll(b_z,-1,axis=1) + np.roll(b_z,1,axis=0) + np.roll(b_z,-1,axis=0)

# write back the part of the array that is of interest to us
N = b_n[1:-1,1:-1]

and for a benchmark:

# original function with loops
In [4]: %timeit computeNeighbours(z)
10 loops, best of 3: 140 ms per loop

# new function without a buffer
In [5]: %timeit noloop_computeNeighbours(z)
10000 loops, best of 3: 133 us per loop

# new function with a buffer to remove boundary counts
In [6]: %timeit noloop_with_buffer_computeNeighbours(z)
10000 loops, best of 3: 170 us per loop

So just a small improvement of a factor of x 1052. Hooray for Numpy!


Although it's a short function/macro, there are a number of problems here:

__FILE__ and __LINE__ are expanded in the function definition, rather than at the call site.  We need an interface that passes those in, so that the macro is
  #define debug(args...) if (DEBUG) _debug(__FILE__, __LINE__, args);

That's a non-standard variadic macro expansion.  The standard way is to write the parameter as ... and expand it using __VA_ARGS__.

Identifiers in global scope beginning with underscore are reserved for the implementation.  Use a namespace instead (e.g. debugging::debug).

Debug information should go to std::clog, not std::cout.

The macro doesn't play nicely in if/else statements - use the do...while(0) idiom to make it statement-like.

Conventional style is to use all-caps for macros (to indicate their dangers) and nothing else.  We have this exactly backwards here, with debug and DEBUG.

Improved version
#include <iostream>

namespace debugging
{
#ifdef ENABLE_DEBUG
    constexpr bool debug = true;
#else
    constexpr bool debug = false;
#endif

    template <typename... Args>
    void print(const char* file, int line, Args... args) {
        (std::clog << "[" << file << ":" << line << "] "
                  << ... << args) << std::endl;
    }
}

#define DEBUG(...)                                              \
    do {                                                        \
        if (debugging::debug)                                   \
            debugging::print(__FILE__, __LINE__, __VA_ARGS__);  \
    } while (0)

And a quick test (that demonstrates that the arguments are evaluated only when we're debugging):
int main()
{
    DEBUG("Started main");
    int status = 1;
    DEBUG("Leaving main, status=", status=0);
    return status;
}

Addendum
We don't need the debug constant - just change the definition of the macro according to whether or not we're debugging:
#ifndef ENABLE_DEBUG
#define DEBUG(...)  ((void)0)
#else
#include <iostream>

namespace debugging
{
    template<typename... Args>
    void print(const char* file, int line, Args... args) {
        (std::clog << "[" << file << ":" << line << "] "
                  << ... << args) << std::endl;
    }
}

#define DEBUG(...)  debugging::print(__FILE__, __LINE__, __VA_ARGS__)
#endif


Splitting a sequence into equal segments

Functional-first style tends to prefer immutability over mutability, so the fact that you're using ref can sometimes signify that the code could be more idiomatic.

Recursive Solution

But how do you keep track of the state of your program without mutation? The traditional functional solution is to use recursion so that each step of the algorithm is isolated in its own call context. Here is a fairly direct translation of your second example into a recursive function:

let rec chop segmentSize source =
    seq {
            if Seq.isEmpty source then () else
            let segment = source |> Seq.truncate segmentSize
            let rest = source |> Seq.skip (Seq.length segment)
            yield segment
            yield! chop segmentSize rest
    }

Don't be intimidated by my if ... then () else pattern - it's a trick I adopted to avoid needing to indent the rest of function when a precondition is used (I've seen it elsewhere, and it is nice since there's no early return from functions in F#).

Note how I'm using yield! to flatten the sequence from the recursive call into the outer sequence. Also notice that there is no chopSource in this version, because what was chopSource in your example is simply source in the recursive call.

One possible problem with the above solution is that it is not (as far as I know) tail-recursive. I'm not 100% sure how seq works behind the scenes, but I'm assuming that it is not in this case. This may not matter for your problem, but it's still something to consider. It could always be rewritten to use an accumulator argument so that it is tail-recursive and won't overflow the stack.

Another option is to ditch the sequence expression altogether (note that this is still not tail-recursive):

let rec chop segmentSize source =
    if Seq.isEmpty source then Seq.empty else
    let segment = source |> Seq.truncate segmentSize
    let rest = source |> Seq.skip (Seq.length segment)
    Seq.append [segment] (chop segmentSize rest)

Seq.unfold Solution

Although it's nice in this particular case, I'm not a huge fan of recursion because it can sometimes be hard to read and easy to get wrong. I normally use sequence functions as an alternative, as they handle those types of details behind the scenes, and I can worry about the problem at hand. Fortunately, the Seq module provides a nice function, unfold, which does exactly what we are trying to do here - it produces a sequence of values from an evolving state!

The function is called unfold because it is the inverse of fold, which is the equivalent of Enumerable.Aggregate from C#. Here is the documentation:

// Signature:
Seq.unfold : ('State -> 'T * 'State option) -> 'State -> seq<'T>

// Usage:
Seq.unfold generator state

The second argument, state, is the initial value that is going to be used to "seed" the operation (it may seem weird to have this as the second argument, but it is in that order to allow partial application / piping). That initial state value is going to be the first value passed in to our generator function. The generator function optionally returns a tuple containing the current value in the sequence along with the next state value that will be passed back in to generate the next value in the sequence. When the sequence is done,  it returns None.

Enough commentary, here is the implementation:

let chop segmentSize source =
    source
    |> Seq.unfold(fun chopSource ->
        if Seq.isEmpty chopSource then None else
        let segment = chopSource |> Seq.truncate segmentSize
        let rest = chopSource |> Seq.skip (Seq.length segment)
        Some(segment, rest)
    )

So as you can see, we're basically allowing Seq.unfold to call our generator  repetitively as an alternative to recursion. Each iteration returns the segment and the rest of the sequence, which becomes the next state / chopSoure. I'm not actually sure if that is clearer than the recursive version, but it at least won't ever overflow the stack.

As for your naming questions, I think it's somewhat arbitrary. I probably would have called the function segment[ed] (indeed, I think I have). The size argument could go either way. For what it's worth, here's a similar function defined in the Seq module, though it's dealing with a sliding window rather than fixed segments.

Addendum

All these solutions are assuming that it is fine to re-enumerate the sequence, i.e. by truncating once and then skipping. That might be an OK assumption for small, in-memory data-sets, but an IEnumerable doesn't have to allow multiple enumeration, and it can be expensive. As pointed out by Tomas Petricek on that other question, due to the forward-only nature of sequences, whenever you "back up" over a sequence like this it actually has to enumerate the entire thing from the beginning.

But perhaps a sequence isn't the best choice of data types for input into this function. If the data is already in memory, you have a choice of turning it into a list or an array. Arrays are especially nice for this problem due to their support for slicing. Here's a solution that uses arrays instead of sequences:

let segmented (size:int) (source:'t[]) =
    let maxPos = source.Length - 1
    [| for pos in 0 .. size .. maxPos ->
           source.[pos .. min (pos + size - 1) maxPos] |]


List all possible numbers from a given array that sums up to a given number

I think the cleanest solution is to first make one pass through the list, storing the numbers in a data structure.  Then use the data structure to perform the calculation.

Data Structure

You want to know how many times you've seen a particular number.

Because the input numbers repeat you can't use a java.util.Set or java.util.BitSet.

The simplest solution is to use a java.util.Map (like java.util.HashMap) where the key is the number and the value is how many times you've seen it.

It doesn't really matter what data structure you use, as long as you can easily look up whether a number has been seen or not.  (Finding that information in the original array is slow!)

Example

Input = {1, 4, 4, 3}, N=5

Process input 1
store (1->1) in the map.

Process input 4
store (4->1) in the map.

Process input 4
Kick out the old value (4->1), and replace it with (4->2).

Process input 3
Store (3->1) in the map.

Final result: ((1->1), (3->1), (4->2))
The pattern is: you retrieve the old value and if it's not null you add one to it.

Search for Solutions

The cleanest solution is to write something recursive.
One input is your data structure (see above), which tells you what numbers are available.
The other input is what your total number is.

Initial Conditions

Input = {1, 2, 2, 3, 4, 5}, N=5
Data structure = (1->1, 2->2, 3->1, 4->1, 5->1)
This means that 1,3,4,5 have been seen once, and 2 has been seen twice.

Start the search

Data structure = ((1->1), (2->2), (3->1), (4->1), (5->1)), N=5

Case 1: Find 5's

Five has been seen, so it's a valid solution.  Print out 5 and you're done.

Case 2: Find 4's

There is still a four remaining.
Add a four to an internal list.
Make a copy of the data structure. (*)
Decrement the number of 4s from your data structure.
Recursively search for things that add up to 1.  (5-4=1).

Case 3: Find 3's

There is still a three remaining.
Add a three to an internal list.
Make a copy of the data structure. (*)
Decrement the number of 3s from your data structure.
Recursively search for things that add up to 2. (5-3=2)

Case 3: Find 2's

(Same pattern as above.)

Case 4: Find 1's

(Same pattern as above.)

Print the results

When you get to the bottom of your recursion, print the current number plus all the previous numbers.

(*) There's a more efficient way of doing this that doesn't involve making a copy: modify the data structure, make the recursive call, then reset the data structure.  This technique is easy to get wrong, and it's a good place to cut corners unless you really have the time to polish your code.

Functional vs. Object-Oriented Programming

I don't see anything wrong with using functional programming for this assignment.  There's no reason why you need to create multiple classes, and it's only meaningful to talk about object-oriented programming when there is more than one class.

If you want to, you could create multiple classes with clearly defined responsibilities.  One could hold the data, one could perform the search, and a third could supply the initial conditions.


Generate every possible single word of three letters

It is very clear both what your code does and how it does it, this is a good thing. However, right now it is incredibly rigid. If requirements change more code will need to be changed than if you spent a bit more time on making it more generic (more on this later).

You can avoid doing multiple assignments to text by combining the lines with text = chars[i] + chars[x] + chars[j]. This also removes the need to reset text to the empty string after adding the word.
The variables i, x, and j seem to be randomly chosen. Not a big deal for loops this small, but it would be fairly easy to accidentally swap the order around. You might want to consider using a, b, and c instead.

What would you do if you were told to modify this method so that it generates 4 letter words? How about 20 letter words? Or just n letter words? While you could write a ton of for loops, it would be better to handle a more generic case. Whether you use recursion or not is entirely up to you.

To help you decide, here is a comparison.

Recursive, handling n letters.

let flatten = arr => arr.reduce((carry, item) => carry.concat(item), [])

let getAllWords = wordLength => {
    if (typeof wordLength != 'number') throw Error('wordLength must be a number')
    if (wordLength < 0) throw Error('wordLength must be greater than or equal to zero')
    if (wordLength == 0) return []

    let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
    let lengthen = word => alphabet.map(letter => word + letter)
    let addLetters = words => flatten(words.map(lengthen))
    let _getAllWords = (letters, words = alphabet, current = 1) => {
        return letters == current ? words :
            _getAllWords(letters, addLetters(words), current + 1)
    }

    return _getAllWords(wordLength)
}

console.log(getAllWords(2))

Iterative, handling n letters.

let getAllWords = wordLength => {
    if (typeof wordLength != 'number') throw Error('wordLength must be a number.')
    if (wordLength < 0) throw Error('wordLength must be greater than or equal to zero.')

    let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
    let words = []
    if (wordLength != 0) words = alphabet

    for (let i = 1; i < wordLength; i++) {
        let temp = []
        words.forEach(word => {
            alphabet.forEach(letter => temp.push(word + letter))
        })
        words = temp
    }

    return words
}

console.log(getAllWords(2))

It really is somewhat of a matter of opinion which is more clean. I personally would likely use the recursive version with the helper functions pulled out of the function itself to improve readability.


Listing an optional Python dependency in setup.py

A few small comments:

The error message looks wrong to me.

This is what the logic looks like to me:

if (third party package is installed):
    install(in-house package)
else:
    install(in-house package)
    install(in-house variant of third-party package)

but the printed warning tells me that the in-house package isn’t installed. Shouldn’t it tell me the third-party package isn’t installed?
An ImportError doesn’t necessarily mean a module isn’t installed.

It just indicates any error when the module was imported. For example, if I have a file foo.py that contains:

import bar

and no module bar.py, I get an ImportError when trying to import foo, even though the foo file exists:

>>> import foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "foo.py", line 1, in <module>
    import bar
ImportError: No module named bar

You can jump through hoops with import tools, or check the error message of the ImportError. That may or may not be something worth worrying about; just remember that this edge case is there.
Trivial nitpicks.

I’m sure this is just an artefact of posting on CR, and it isn’t actually called in_house_package, but you’ve misspelt it in the error message.
When specifying keyword arguments to a function (such as setup()), it’s common to omit the spaces around the equals sign.


Your code doesn't seem to be the complete module (e.g. get_clean_id() is referred to but not defined or imported, and I don't know what desk_auth.session does), so I won't try and understand the whole thing. I'll stick to comments about the general coding style.

Starting with your imports:

import time
import collections
from desk_auth import BASE_URL, service, session
import MySQLdb
import mysql.connector
from mysql.connector import errorcode
from db_info import uname,pw,host,db
import dateutil.parser

The first thing that comes to mind when I see this is that it doesn't look organised. Different people organise their imports differently, but to me it's a bad sign if there doesn't seem to be any order at all. The PEP-8 (coding standards for Python) suggest the following order:

standard library imports
related third party imports
local application/library specific imports

I generally put a blank line between each of these sections.

Use judgement about when to use import ... and when to use from ... import .... I won't go into the full details here, but in short I avoid this when the imported names are very short or generic. Names like pw or db could easily get confused with variables elsewhere in your code.

   def get_all_cases():
        """
    pages through items,
    returns a dict of dicts of case, cust, date
    #cases[case] = {cust:date}
    """

You have an indentation issue here. It may just be an issue with the StackExchange markup, but if not you should fix it. The function should be declared at the beginning of the line (assuming it's not a class method for which you've cut out the definition of the class).

The name get_all_cases() is not very specific. Whether this is a problem will depend on how the function is going to be called. If it were a class method, then the context might be enough to make it meaningful (e.g. doctor.get_all_cases() is quite clear). In Python, free (non-method) functions are often called by reference to the module they live in, which can make it clear what it means in the same way as an object name would. However, you need to ask yourself whether this is clear enough. My instinct is that this function name needs to be clearer.

i = 1

Avoid single-character variable names for anything but the control variable on a short for loop (e.g. for i in range(10): print x[i]). For something that is used over a large function like this, give it a proper name. It looks like this should be called page.

Generally, I think the get_all_cases() function is too long. Breaking it into smaller functions will make the logic easier to follow.

If I'm reading this right, you have quite a simple flow:

have_next = True
while have_next:
    items, have_next = get_data()
    all_items += items

return items

(this is just a simple sketch; I'm not suggesting you use variable or function names like this).

Moving the API call into one function and the work to create the cases out of the raw API result into another function would make this structure more obvious.

            cases = (case, cust, date, last_update, subj, status, plan, group, assigned_to)
            all_cases.append(cases)

Using tuples to represent entities when you have more than two or three elements quickly gets unmaintainable. If you want to get the status out of this, you have to remember to do case[5], which isn't very clear to read. If you end up wanting to add another field to this, then you have to insert it at the end or risk breaking any piece of code that refers to the case elements.

One alternative to using a tuple is to declare a class type and then use instances of this class type to represent your cases, but this might be unnecessary overhead in this case (it depends how widely you're using these objects). A simpler alternative is to use a namedtuple. That way you can refer to case.subj, case.status etc. in your later code.


Calculating the amount of cubes needed to form a sum

When there's math to be done, always check if some formula exists

$$1^3+2^3 + \dots+n^3 = m = (1+2 + \dots+n)^2$$

in conjunction with some other formula (interesting wikipedia article title)

$$\sum^n_{k=1}k = \frac{n(n+1)}{2}$$

you get some equation for the result

$$\sqrt{m} = 1+2 + \dots+n = \sum^n_{k=1}k = \frac{n(n+1)}{2}$$
and maybe some closed formula

$$
\begin{align}
\sqrt{m} &= \frac{n(n+1)}{2}\\
2\sqrt{m} &= n(n+1)\\
2\sqrt{m} &= n^2+n\\
0&= n^2+n - 2\sqrt{m}
\end{align}
$$

Which has the 2 solutions

$$n_{1,2} = -\frac12 \pm\sqrt{\frac14+2\sqrt{m}}$$

As \$n\$ should be a positive number, only the first solution makes sense.

Return \$ -\frac12 +\sqrt{\frac14+2\sqrt{m}}\$ if it is an integer or \$-1\$ otherwise.

The results are:

$$
\begin{array}{r|r}
m & n\\
\hline
4183059834009 & 2022\\
24723578342962 & -1\\
135440716410000 & 4824\\
40539911473216 & 3568\\
\end{array}
$$

24723578342962 is a very close call, because

$$\sum^{3153}_{k=1}k^3=24723578342961$$

is only 1 off. The floating point result is \$n=3153.00000000003\$. If you don't want to get false positives due to floating point precision (lack thereof), you can do the check by converting the result to some integer type and see if you get the exact number by doing the calculations with that.


Coding style

Overall looks good. I only got some small remarks:

Put {} after each if and else as well. This is mostly to prevent stupid bugs if you (or someone after you) adds an innocent looking line like this:

 for(String key : ransomMap.keySet()){
    if(!magazineMap.containsKey(key))
        System.out.println("Not enough of: " + key);
        return false;  //<- this false is actually outside the if block now.

    if(magazineMap.get(key) < ransomMap.get(key))
        return false;
}

Suddenly it always returns false, even tho we just wanted to print which key wasn't found. Most IDE's can be set up to always place the braces for you.

A minor thing is also the name for magazineMap. I would rename this to magazineFrequencyMap to make it clear that it's a frequency map (like your great method name says to populate the map). But since that might feel a little long later on you'll have to decide for yourself what feels better.

The last thing is that you never close your Scanner. Since this is in your main method and your program ends after execusion it doesn't really matter much, but since we're talking best practices here I couldn't ignore this.

Efficiency

Why store the number of words in a Long if there's at most 30k of them? An Integer should do:

Map<String, Integer> magazineMap = getFrequencyMapFromArray(magazine);

A major change to gain efficiency is to never build the frequency map for the ransom notes. Instead use the following strategy to solve the problem:

Put all the magazine words into a map like you did now.
Try to take each ransom word out of that bag while reading them from the file.
If it's not in the bag (or count is 0) you can stop here and return false

If you are "lucky" and the first ransom word is not present in your magazines you can stop early. This can save "a lot" of time counting the other ransom words. (Note that "a lot" means a couple of miliseconds probably, so it doesn't really matter that much for this problem).

the best way

I would argue that there is no best way to solve a computer problem. Only a better way given certain criterea.

For the given problem I would argue that my "take ransom words out of the existing bag as we go" is better since it's more memory efficient and fails faster.

If, however, we want to expand this problem later to:

  Given a stack of magazines, which of these magazines can be used to write the ransom note?

Then it makes a lot more sense to read the ransom note once and put them into their own frequency map. Because we can use this map to compare with each of the magazine frequency maps like you did in your solution.


Alright, there's a number of simplifications to the Utility Class I'd like to make before I continue:

Your abstraction from arc4random (at least that's what I hope it is), is too expensive to not just use the corresponding C-code directly.  You could even make your own method in C, and use the inline qualifier for faster code than calling out to a singleton 3 times for every color.  Also, it is never good to name an Objective-C method "instance".  Singletons usually use a naming convention that makes sense with their overall implementation (i.e. NSFileManager.defaultManager).  The following will generate a random double for you between 0 and 1.  Not only is it cleaner, but it's cheaper.

#define ARC4RANDOM_MAX      0x100000000
float l_fRandomRedColor = ((double)arc4random() / ARC4RANDOM_MAX);

*As an aside, it's also a good idea to use an alpha value of 1.0f, instead of 255, because alpha is also measured on a 0-1 scale

  Question A)

  My instance variable is released in the dealloc method. Is a the
  correct way to go?

The rule in ObjC is "You own it, you destroy it."  Because mpCurrentPieceColor is an explicitly retain'ed property, you own it.  If you were to not destroy mpCurrentPieceColor in -dealloc, then your class would retain a valid reference to it, and it simply would not go away. (memory leak).

*As an aside, switching to ARC will alleviate all of these headaches.

  Question B)

  Now, let's imagine I have an array, like this:

  UIColor* mBoardColors[WIDTH][HEIGHT];...

So long as you initialize the members of the multi-dimensional array, this is correct, but definitely not optimal.  Objective-C has it's own array objects, which free you from having to make these ridiculous memory management decisions, and a dynamic, expandable multidimensional array is as simple as nesting NS(Mutable)Arrays:

[NSMutableArray arrayWithObjects:[NSArray array],[NSArray array],[NSArray array],[NSArray array],..., nil];

Not only that, but if you were to decide to expand or contract the board at any time, you could add or remove objects at a whim, and, so long as you release any references to the objects you put into the array, when the main array is released, it will release the sub-arrays, and the sub-arrays will release their objects.  It really is quite beautiful.

  Question C)

  What if I want to move a color from a cell to another (moving, not
  copying), is it correct to do it like that?

Another beauty of NSArrays is the ability to swap-out objects into a new index of the array, so long as you don't exceed the array's bounds.  See the "Replacing Objects" section of NSMutableArray's documentation.  Again, as above, memory management is vastly simplified with an NSArray, than dropping down to a multi-dimensional literal.


Functional Game of Life implementation in Ruby

I'm using this as my style guide here.

Don't use parentheses when there aren't parameters. In this case, it applies to new_grid's definition and uses -- rather than new_grid(), it should be just new_grid.

In new_grid, I'd recommend adding two things:

A comment just before the last line to explain why you're not using nested (i.e. 2D) arrays. I suspect it's for memory reasons, but you may well have your own reasons for this somewhat counterintuitive choice.
A hash.default= call to set the default to false (as "not here"), just for consistency with true as "here". Note that this doesn't change anything about how the code actually runs, but it's more consistent to use true/false than true/[falsey value].

In your actual run loop, you should separate the iterations by something, so they don't blend together. In the console (which is how I ran this), this is what it looks like:

It's like this because system('clear') doesn't work on Windows. If you wanted to support Windows, you'd use system('cls') instead. (Before we go arguing about which OS is best, it doesn't matter. This is a code review. I'm finding bugs.)

However, since trying to make console commands work on every system is hard, I'd recommend simply putting some divider between the boards. For example, immediately after your current last line, you could put this:

puts '-' * (max_x - min_x + 1)

which will change the output to something more like this (I forgot where I originally took the picture, so it's not exactly the same area):

Or, alternatively, combine them! Try both clear and cls, and if neither succeed, puts a divider. Just get rid of system('clear') and toss this if before puts result to get that:

if system('clear')
  #Empty intentionally
elsif system('cls')
  #Empty intentionally
else
  puts '-' * (max_x - min_x + 1)
end

It works on my Bash emulator, my Ubuntu server, my Windows 8 laptop, and with some dark magicks I confirmed that if it can't run any of the commands it successfully outputs the dividers.

Testing with RubyMine confirms that RubyMine is weird. cls returns true, but does nothing. This is a (now reported) bug with RubyMine.

Now, while we're nitpicking print, have another: Rather than joining the lines with \n then outputting all at once, which may cause some errors with things that try to autoindent code (cough my stuff that puts spaces in front so it's easier to take pictures cough), replace it with .each { |line| puts line }.

Note: If you use both this and the last tip, you'll have to move the if block(s) up above it.

You've got a couple of magic numbers in will_be_alive, but it's Conway's Game of Life and the function is called will_be_alive, so it's pretty obvious what they are, so that's not that big a deal.

Aside from that, it looks good!

I like how you commented in bag to explain what it does, since it took me a good four minutes to get what product does.

The actual algorithm is good, though it took me a minute to figure out how iterate works when it seems like it should just give 8 every time, at least at first.

I quite like how you pass the grid as an argument to each function, rather than using a global variable or the like.

As I can tell, the majority of the code is good! Well done.


The variable and function names should be lowercase since the types are uppercase.  This would allow for more distinctive naming.
In Point2D, both X and Y should be private.  This applies to all data members.
If you don't need the default constructor for Point2D, leave it out.
There's no need to allocate memory for point; just construct a local object:

Point2D point(x, y);

There should be as little manual memory management in C++ as possible.


I have not thought carefully about all of your code and questions, but here's
one suggested technique for how to handle validation code more simply. In most
contexts, people find it easier to understand affirmative boolean logic rather
than negated logic. My guess is that the bug in is_strong_password() stems
from that phenomenon (the function tells me hi is strong, for example).
You've created 3 variables to be true when something is wrong but then combined
them under the opposite assumption. Here are two alternatives to consider:
# This alternative uses affirmative variables: True means OK. Also notice
# how the variable names are a bit more intuitive because of the
# affirmative framing. When possible, try to name boolean variables to
# convey their nature: is_X, has_X, contains_X, etc. Your current code has
# variables names implying that they each hold an "error" of some kind --
# but they do not. Finally, the usage of bool() here is not strictly
# necessary, but it does convey intent explicitly.

def is_strong_password(password):
    is_long = len(password) >= 8
    has_digit = bool(re.search(r"\d", password))
    has_upper = bool(re.search(r"[A-Z]", password))
    return is_long and has_digit and has_upper

# This alternative illustrates a handy code-layout technique
# that often works well when doing validation. This version
# is shorter (sometimes nice) but less explicit. In this
# case, I would tend to favor the short version, because the
# checks are so simple. If the complexity were higher, I would
# prefer the approach that names every check to increase clarity

def is_strong_password(password):
    return (
        len(password) >= 8 and
        re.search(r"\d", password) and
        re.search(r"[A-Z]", password)
    )

The is_email_formated_correctly() can be simplified by doing things more
directly. In addition, if validate_email() returns True/False you could
simplify further by just returning its return value.
def is_email_formated_correctly(email):
    try:
        validate_email(email)
        return True
    except EmailNotValidError:
        return False


First Python program: Tic-Tac-Toe (Followup)

You now have two methods of setting up the board.  The first is direct initialization:

board = [0, 1, 2,
         3, 4, 5,
         6, 7, 8]

and the second is a resetting an already existing board:

def clear_board():
    for i in range(9):
        board[i] = i

I hate that there are two.  It would be easy to make a mistake and change one (for example, changing to a 4x4 grid) but not the other.

board_layout() is an odd name for the function that prints the board.  It is not laying out the board.  I might call it print_board().

I dislike seeing the same thing over and over.  In board_layout(), you have board[ ] appear 9 times in the format string.  If you wanted to change the name of the game board, you'd have to edit the code in 9 places in this one function.  You can eliminate these duplicates using the .format() command, instead of using a f-string.  I know, seems like going backwards; f-strings are supposed to be an improvement!

'''
*************
* {} | {} | {} *
*-----------*
* {} | {} | {} *
*-----------*
* {} | {} | {} *
*************
'''.format(*board)

*board takes the board list, takes the individual elements and "splats" them all as the arguments to the .format() call.  Each argument, in turn, is substituted into the next {} format code.

Jumping ahead.

        winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],
                        [board[6], board[7], board[8]], [board[0], board[4], board[8]],
                        [board[2], board[4], board[6]],
                        [board[0], board[3], board[6]], [board[1], board[4], board[7]],
                        [board[2], board[5], board[8]]]

Again, here we have board[ ] repeated 24 times!  There has got to be a better way.  And there is.  First, create as a global constant, a list of list of winning indices.  Since these will never be modified, I've used tuples instead of lists.

WINNING_ROWS = ((0, 1, 2), (3, 4, 5), (6, 7, 8),  # Rows
                (0, 3, 6), (1, 4, 7), (2, 5, 8),  # Columns
                (0, 4, 8), (2, 4, 6))             # Diagonals

Now we just need to use these indices to check for a win condition.  We can even use chained comparisons to make the test more concise:

    for i, j, k in WINNING_ROWS:
        if board[i] == board[j] == board[k] == 'x':
            print('X wins')

That tests board[i] == board[j] AND board[j] == board[k] AND board[k] == 'x', but we haven't repeated any of the terms in the test.

        elif board[i] == board[j] == board[k] == 'o':
            print('O wins')

And now we have.

Whenever you repeat code, you should think "maybe a loop" or "maybe a function".  A loop doesn't seem right here.  Let's use a function:

def has_won(player):
    for i, j, k in WINNING_ROWS:
        if board[i] == board[j] == board[k] == player:
            return True
    return False

Now you can use if has_won('x'): to check in the 'x' player has won after they have made their move, and if has_won('o'): to check if the 'o' player has won after they have made theirs.

We can condense this function.  The all() function will test each of its arguments, and return True only if all of the arguments are true.  We can use list comprehension to extract each index in turn from the row tuples:

def has_won(player):
    for row in WINNING_ROWS:
        if all(board[idx] == player for idx in row):
            return True
    return False

Like the all() function, there is an any() function, which returns True if any of its arguments are true.  Again, we'll use list comprehension to loop over each row in WINNING_ROWS:

def has_won(player):
    return any(all(board[idx] == player for idx in row) for row in WINNING_ROWS)

For any of the winning rows, if all of the board locations contain the player's symbol, True is returned.  Pretty darn concise, if you want to use it.

Checking for a valid spot:

if board[player_move] != 'x' and board[player_move] != 'o':

if board[npc] != 'o' and board[npc] != 'x':

Effectively the same test, repeated twice.  And board[pos] referenced twice in each test.  Don't Repeat Yourself.  DRY.  As opposed to Write Everything Twice, or WET.  You want DRY code, not WET code.  The in operator will test if the item on the left of in is contained in the container on the right.

def is_valid_move(move):
    return board[move] not in ('x', 'o')

Not bad.  But is 12 a valid move?  How about -1?  Note that -1 will not cause an IndexError, it will just return the last element of the list (board[8]).

def is_valid_move(move):
    return move in range(9) and board[move] not in ('x', 'o')

Elephant in the room.

You play the game, win, play again, loose, play again, tie, play again.  What is the stack trace at this point?

main() -> check_winner() -> end() -> main() -> check_winner() -> end() -> main() -> check_winner() -> end() -> main() -> check_winner() -> end() ...

If you make a mistake and enter invalid input in the end() method, you could even have end() -> end() repeats in that stack trace.

Do not use recursion as a substitute for looping!

Here is a possible implementation, which doesn't use recursion.  Note that there are no global variables, other than the constant WINNING_ROWS.  Since board is no longer global, it can be created brand new each time a game is started.

import random

WINNING_ROWS = ((0, 1, 2), (3, 4, 5), (6, 7, 8),
                (0, 3, 6), (1, 4, 7), (2, 5, 8),
                (0, 4, 8), (2, 4, 6))

def print_board(board):
    row  = "  {} | {} | {}\n"
    line = " ---+---+---\n"
    print(((row + line) * 2 + row).format(*board))

def has_won(player, board):
    return any(all(board[idx] == player for idx in row) for row in WINNING_ROWS)

def is_valid_move(move, board):
    return move in range(9) and board[move] not in ('x', 'o')

def player_move(board):
    print_board(board)
    while True:
        try:
            move = int(input('Please select as spot: '))
            if is_valid_move(move, board):
                return move
        except ValueError:
            pass
        print('Invalid input.', end='  ')

def npc_move(board):
    while True:
        move = random.randint(0, 8)
        if is_valid_move(move, board):
            return move

def play_game():

    board = list(range(9))
    player = 'x'

    for _ in range(9):
        if player == 'x':
            move = player_move(board)
        else:
            move = npc_move(board)

        board[move] = player

        if has_won(player, board):
            print_board(board)
            print(f"{player.upper()} wins!")
            return

        player = 'o' if player == 'x' else 'x'

    print("Tie game")

def main():
    answer = 'y'

    while answer == 'y':
        play_game()

        answer = ''
        while answer not in ('y', 'n'):
            answer = input('Play again? (Y/N): ').lower()

if __name__ == '__main__':
    main()


Speeding up nested for-loop analysis code

Try the following:

mat0 <- tep[, c(TRUE, FALSE, FALSE)]
mat1 <- tep[, c(FALSE, TRUE, FALSE)]
mat2 <- tep[, c(FALSE, FALSE, TRUE)]

denominator <- mat0 + mat1 + mat2
numerator   <- mat0 * (mat - 1) * (mat - 2) / (0 - 1) / (0 - 2) +
               mat1 * (mat - 0) * (mat - 2) / (1 - 0) / (1 - 2) +
               mat2 * (mat - 0) * (mat - 1) / (2 - 0) / (2 - 1)

A <- numerator / denominator


The key difference between the two approaches is essentially these lines,
counting the words in text:

text ? text.match(/\b\S+\b/g).length : "0"
// ... versus ...
text.split(/\b\S+\b/).length - 1

First of all, the first expression will crash for a non-empty text without words, for example :!@#$. Because a non-empty text is "true", but the .match will return null, so you'll get a null pointer exception in .length.

Secondly, I suggest a simpler and more intuitive regular expression to match words:

/\w+/g

That is, match a non-empty sequence of word characters.

You could use this as text.match(/\w+/g) (notice the "g" flag) or as text.split(/\w+/). When using match, you need to check if the result is null or not, as you already did.

As for which way is better, using match or split,
I would argue for match:

It's more intuitive: it matches the character sequences you're interested in, and then count the occurrences.
It's probably more efficient: splitting implies creating an array of the results, but if you only need the size of the array (the count of elements), then it sounds like a waste.


Multiply a square matrix with only the diagonal and antidiagonal elements different from zero in vector

I believe your issue is that you're altering your matrix (the multiplicand) as you are performing the multiplication. This is why part of the result is correct while the other part is incorrect. For example, the top-right cell (which should be 25) is evaluated from \$ 41*5+5*4=225\$ where the 41 (which should be 1) is used because you've prematurely set that cell from an earlier iteration.
A simple way to fix this could be to use an intermediary matrix or buffer during the calculation. However, if your xmatrix class represents a matrix that can only be diagonal, anti-diagonal, or both, then you can use the properties of diagonal matrices to optimize and simplify your class.
If this is indeed the case, then you can simply represent the entire matrix by its diagonal and anti-diagonal components:
vector<int> diagonal;
vector<int> antidiag;

For the anti-diagonal component, I'll refer to your example and use a top-right to bottom-left orientation (so the top-right cell will be first and the bottom-left cell will be last).
We can now optimize the multiplication operation by noting a few properties of diagonal matrices. Consider a diagonal matrix \$ A_x \$ and an anti-diagonal matrix \$ A_y \$, both of size \$ n \$. Let these be the anti-diagonal and diagonal components of an \$ n*n \$ matrix \$ A \$. We can then represent \$ A \$ such that \$ A = A_x+A_y \$. However, this representation requires special care when \$ n \$ is odd because of the common middle element. When such a case occurs, we'll absorb the middle element into the diagonal component and zero out the middle element in the anti-diagonal component. So now we have our multiplicand matrix \$ A \$, we use a similar notation to represent the multiplier matrix \$ B \$ such that \$ B = B_x+B_y \$. Using a few properties of matrices, we can show that the multiplication of these matrices is a sum of diagonal and anti-diagonal components:
$$
AB=(A_x+A_y)(B_x+B_y)=A_xB_x+A_xB_y+A_yB_x+A_yB_y\\=(A_xB_x+A_yB_y)+(A_xB_y+A_yB_x)\\=(\text{[diagonal]})+(\text{[anti-diagonal]})
$$
Now that we've worked through the math, we can use this result to implement an optimized multiplication algorithm with a time complexity of \$ O(n) \$.
#include <iostream>
#include <vector>

class XMatrix
{
public:
    XMatrix(const std::vector<int>& diagonal, const std::vector<int>& antidiag)
     : diagonal(diagonal), antidiag(antidiag), size(diagonal.size())
    {
        if (diagonal.size() != antidiag.size())
            throw;

        if (this->size % 2 != 0) {
            this->antidiag[this->size / 2] = 0;
        }
    }
/*
...
*/

    XMatrix operator*(const XMatrix& m)
    {
        if (this->size != m.size)
            throw;

        std::vector<int> result_diagonal(this->size);
        std::vector<int> result_antidiag(this->size);

        for (int i = 0; i < this->size; ++i) {
            result_diagonal[i]
             = this->diagonal[i] * m.diagonal[i] +
               this->antidiag[i] * m.antidiag[m.size-i-1];
            result_antidiag[i]
             = this->diagonal[i] * m.antidiag[i] +
               this->antidiag[i] * m.diagonal[m.size-i-1];
        }

        return XMatrix(result_diagonal, result_antidiag);
    }

    void print() const
    {
        for (int row = 0; row < this->size; ++row) {
            for (int col = 0; col < this->size; ++col) {
                std::cout << '\t';
                if (row == col)
                    std::cout << this->diagonal[row];
                else if (row == (this->size - col - 1))
                    std::cout << this->antidiag[row];
                else
                    std::cout << '0';
            }
            std::cout << '\n';
        }
    }

private:
    int size;
    std::vector<int> diagonal;
    std::vector<int> antidiag;
};

int main(int argc, char *argv[])
{
    XMatrix matrix_A({1,2,3,4},{5,6,7,8});
    XMatrix matrix_B = matrix_A * matrix_A;
    matrix_B.print();

    return 0;
}

I've altered some things compared to your original code for the purpose of illustrating everything within this response. This may be a bit more than you were asking for regarding why your matrix multiplication was only half working (if that's all you were concerned about then feel free to disregard everything after the first two paragraphs), but in any case I hope I was able to help.


Merging directories and keep files that have more lines

Use More Quotes™.
Use a shebang line (disclosure: I wrote that answer).
Don't use single character variables. Maintainability is the most important feature of code.
Rather than echo cp1 etc., simply use cp -v to print every copy command verbatim.
You don't need to count the number of lines that diff returns, you can simply do if diff foo bar, or the safer option:

diff foo bar
exit_code=$?
if [ "$exit_code" -eq 0 ]
then
    [no difference]
elif [ "$exit_code" -eq 1 ]
then
    [difference]
else
    exit "$exit_code" # WTF
fi

Some people love mixing languages. I think cut -d' ' -f1 is much nicer than even a short awk script.
If you pass the file to wc on standard input, it doesn't print the filename, and so you don't need to process the output at all: wc -l < /path
You can use if cp --no-clobber source destination to try copying the file instead of checking whether the target exists.
I'm not sure I understand why you're copying rather than moving files (unless this is a one-off script, which you're not going to test, and it's only going to take a few seconds anyway).
Be wary of using cd in scripts. It changes the context in a significant way, and makes it harder to reason about what the script will do. Instead, simply do `for path in "$directory"/*.
I can definitely recommend set -o errexit -o noclobber -o nounset -o pipefail. You could also use -o xtrace to make all those logging commands obsolete.
A common convention to get used to is to never end paths with a slash. Firstly because cp a b/ and cp a b and the same as long as b is a directory, and secondly because it makes it more natural to concatenate paths without ending up with double slashes.


Run an external program and extract a pattern match along with the result file

Not looking bad for as far as I can see. If the example file is accurate for the lengths of the input files, then I don't forsee any real problems, though others may of course disagree.

Naming:

cmdline is quite a... short name for a function. I'd think cmd_line for snake_case convention. However, what it does is create what's basically a text file in a bytes buffer by means of running a program. While you could call that a command line execution if you're working from a terminal, I'd name it after the invoked program, or something more generic like get_input_data. Since generic is always survivable at best, I'd pick something like get_needle_results or something like that.

For a module like subprocess which you can guess does creative things dependent on what platform you're on, it's always advisable to grab the docs:

  args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

And your platform matters - a lot. If you never switch platform or needle implementation, then you can do what you're doing, but if not you're risking a collossal headache with potentially giving it wrong arguments. Therefore, you might want to restructure it to a list of arguments.

And if you don't, use f-strings, the best invention since the list comprehension:

cmd = 'needle -datafile EBLOSUM62 -auto Y' + ' -asequence ' + file1 +' -bsequence ' + file2 +  ' -sprotein1 Y -sprotein2 Y ' + ' -auto -stdout'
# Becomes:
cmd = f'needle -datafile EBLOSUM62 -auto Y -asequence {file1} -bsequence {file2} -sprotein1 Y -sprotein2 Y  -auto -stdout'

Which is shorter and more readable.

        results = cmdline(cmd)

        results = results.decode("utf-8")

These can be combined:

        results = cmdline(cmd).decode("utf-8")

So can these:

        identity = re.search(r"\d{1,3}\.\d*\%", results)
        identity = identity.group()
        identity = identity.replace('%', '')
# New:
        identity = re.search(r"\d{1,3}\.\d*\%", results).group().replace('%', '')

if blast_two_sequences(file1, file2) is not None:
    identity, result = blast_two_sequences(file1, file2)

And ouch... you're actually running your entire program twice. If your needle executions are counted, you might have noticed this. You should refactor this to:

output = blast_two_sequences(file1, file2)
if output is not None:
    identity, result = output
# Or if you work with Python 3.8+
if output := blast_two_sequences(file1, file2) is not None:
    identity, result = output

You should also put a guard around the actual execution, so that a later scripter can import your functions and use them without executing your script on import:

if __name__ == "__main__":
    file1 = "/Users/catuf/Desktop/file1.txt"
    file2 = "/Users/catuf/Desktop/file2.txt"
    if output := blast_two_sequences(file1, file2) is not None:
        identity, result = output

Exceptions:

There's a small issue you have - you have a bare except in your code. That means that if weird stuff happens, your program will just ignore it and return none. In your case, I would recommend removing the try: statement completely, and you'll be informed about any problems that arise. If you're watching out for specific Exceptions, narrow your except: to those, and preferably restrict your try/except to directly around the origin lines of these Exceptions.

This will obsolete your None check on the outside. Exceptions showing up on your screen is a good thing - it means you'll be notified when the unexpected happens and you have some unknown error - because now you can go fix it.


Bisect Insertion Container for Calculating Running Median

This

var values = new[] { bound.ToString() }.Concat(..).ToArray();
RunBiSect(values);

plus this

public void RunBiSect(string[] args)

plus this

var count = Convert.ToInt32(args.First());
var valus = args.Skip(1).Select(s => Convert.ToInt32(s)).ToArray();

is a super weird way of passing arguments from method to another. I'm not sure if you know it but methods can take more then one parameter ;-)

var valus = ..;
var sortd = ..;

Where is the e? Don't you like it? You should not use abbreviations unless they are well known like html or xml etc.

public class MedianList

Nested classes should not be public. Then this class is not a list and should be called like that. MedialCalculator sounds much better. Shouldn't the InsertForMedian API be named CalcMedian?

public float IterationsPer { get { return _iters / Math.Max(1, _count); } }

Here is something missing: IterationsPer what?


Extracting the longest line from standard input

I see some things that may help you improve your code.

Eliminate unused variables

Unused variables are a sign of poor quality code, and you don't want to write poor quality code. In this code, line and longest are unused -- their values are set but then never referenced again.  Your compiler is smart enough to tell you about this if you ask it nicely.

Think carefully about variable use

After the first line is read, the variable i isn't really needed.  The way it is now, it could instead simply increment max directly.

Think carefully about the task

If you need to save the longest line, you can't overwrite it every time.  The difference between yours and the K&R version is that yours prints multiple times and only the last time it prints is actually the longest line.

Check for unusual inputs

What happens if the file consists of a single long line?   The existing code will fail because the code that reads the first line fails to stop at the end of the file.  Also none of the code checks for lines that are too long.

Break up the code into smaller functions

The main() function does a series of identifiable steps.  Rather than having everything in one long function, it would be easier to read and maintain if each discrete step were its own function.

Don't repeat yourself

There's really no need to handle the first line any differently than any other line.  Instead, you could simply run the main loop.

Minimize work

There's no reason to clear the entire line array.  Instead of the memset, your code could simply do this:

help[0] = '\0';

Choose better variable names

The name help is not at all appropriate to its actual function.  I'd recommend using line for everywhere that help is currently used.

Use modern syntax

The old K&R style was to declare all variables at the top of the function, but that's not any longer either required or desired.  Instead, current practice is to declare variables near their first use and to keep their scope small.

Use modern C idioms

Right now the code contains these lines:

help[j]=ch;
++j;

However, that's more idiomatically written like this:

help[j++] = ch;

Fix your formatting

There are inconsistent spaces in variable declarations, and inconsistent indentation. Being consistent helps others read and understand your code.

Use more whitespace

Instead of writing a line like this:

while ((ch=getchar())!=EOF){

use a bit more whitespace and write it like this:

while ((ch = getchar()) != EOF) {

Doing so will make it easier to read and understand your program.

Eliminate return 0 at the end of main

Since C99, the compiler automatically generates the code corresponding to return 0 at the end of main so there is no need to explicitly write it.


CLRS implementation (opportunity to sort subarray) of merge sort in golang

I'm reading "Introduction to Algorithms" by CLRS and I can't find an
  implementation of the pseudo code from the book in golang.

Here is my Go implementation of the pseudocode from the book.

package main

import (
    "fmt"
    "math"
)

// Introduction to Algorithms
// Third Edition
// Cormen, Leiserson, Rivest, Stein

func merge(a []float64, p, q, r int) {
    nLeft := q - p + 1
    nRight := r - q
    t := make([]float64, (nLeft+1)+(nRight+1))
    left := t[:nLeft+1]
    right := t[nLeft+1:]
    copy(left[:nLeft], a[p:])
    copy(right[:nRight], a[q+1:])
    left[nLeft] = math.Inf(0)
    right[nRight] = math.Inf(0)

    i, j := 0, 0
    for k := p; k <= r; k++ {
        if left[i] <= right[j] {
            a[k] = left[i]
            i++
        } else {
            a[k] = right[j]
            j++
        }
    }
}

// MergeSort sorts the slice a[p:r+1] in nondecreasing order.
func MergeSort(a []float64, p, r int) {
    if p < r {
        q := (p + r) / 2
        MergeSort(a, p, q)
        MergeSort(a, q+1, r)
        merge(a, p, q, r)
    }
}

func main() {
    a := []float64{9: 2, 4, 5, 7, 1, 2, 3, 6}
    fmt.Println(a)
    MergeSort(a, 9, 16)
    fmt.Println(a)
}

This is a real-world code review: Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.

Your code is not readable. Your code does not closely follow the pseudocode. For example, you deleted the n1 and n2 pseudocode variables:

n1 = q - p + 1
n2 = r - q

As a result, your code is very inefficient. Your code is off-by-one.

  The Go Programming Language
  Specification

  Appending to and copying
  slices

  The variadic function append appends zero or more values x to s of
  type S, which must be a slice type, and returns the resulting slice,
  also of type S. ... If the capacity of s is not large enough to fit
  the additional values, append allocates a new, sufficiently large
  underlying array that fits both the existing slice elements and the
  additional values. Otherwise, append re-uses the underlying array.

For left and right subarrays, you allocate slice with a capacity equal to the number of elements, then you immediately append a sentinel value. This allocates a new slice and copies the old values from the old slice to the new slice.

In my code, I renamed n1 and n2 to a more readable nLeft and nRight. In my code, I minimized the number and size of allocations.

A benchmark (1000 random elements) for my code

$ go test msort.go msort_test.go -bench=. -benchmem
BenchmarkMSort-4  18720   64849 ns/op   98048 B/op   999 allocs/op

versus a benchmark (1000 random elements) for your code

$ go test msort.go msort_test.go -bench=. -benchmem
BenchmarkMSort-4   6996  150493 ns/op  242880 B/op  3996 allocs/op


A few comments:

you use signed/unsigned types inconsistently. Your width and height are
unsigned, while all other integers are signed.  If you are using unsigned
types because the values can never be negative, then the same applies to all
integers in the function and, by that reasoning, they should all be unsigned
(size_t is a common type used for sizes).  There are arithmetic errors that
can occur with mixed signed and unsigned arithmetic, so you should turn on
conversion warnings (eg -Wconversion for gcc).
your naming is inconsistent.  The function and the variable rowIndex use
"camel-case", while the other variables don't.
the return from malloc should not be cast in C (C++ requires casting).
source_offset and target_offset should be defined at the point of first
use (ie. within the loop).  There is no performance penalty for defining a
variable within a loop in C.
there is no check for success from malloc

Here is a slightly simplified version of the function

void flip_vertically(unsigned char *pixels, const size_t width, const size_t height, const size_t bytes_per_pixel)
{
    const size_t stride = width * bytes_per_pixel;
    unsigned char *row = malloc(stride);
    unsigned char *low = pixels;
    unsigned char *high = &pixels[(height - 1) * stride];

    for (; low < high; low += stride, high -= stride) {
        memcpy(row, low, stride);
        memcpy(low, high, stride);
        memcpy(high, row, stride);
    }
    free(row);
}

You can see that I have changed some types, shortened variable names (it is a
short function so short names are appropriate) and simplified the way buffer
offsets are calculated to just addition/subtraction.


Design:

I still think that a DateOfBirth class is too narrow. It should be the name of a property, not a separate class. If you must create a class, create a reusable Date class instead. Enforcing this sort of restrictions at the type level isn't worth the extra work and maintenance cost (in C#). That's my opinion, of course, but judging by your many questions it really is a lot of work, isn't it? ;)
I expect a DateOfBirth.IsValid method to check whether the given input is a valid birth-date. That is, I expect it to reject nonsense input like '-5 45 2018'. However, your implementation enforces a business rule instead. There are several problems with that:

It's confusing: it's basically telling me that '7 februari 2018' is not a valid birthdate.
It's inflexible: what if some logic applies to people above 21, but other logic only to people below 18?

Again, why expose Value directly? As I mentioned before, a date does not have a time component, but by exposing a DateTime property you make it look like it does. Of course, you may want to convert between dates and date-times, but that's what conversion operators are for. A Year, Month and Day property are far more in line with what a date actually is. Look at DateTime, for example: it uses a timestamp as internal storage, but it provides meaningful properties like Year, Month, Day, Hour, Minute, Second, and so on, which results in a much more natural and practically useful interface.
Where did the comparison operators go? Are they superseded by the IsValid method? Or are you planning to use Value for that? If so, why create a separate class in the first place?

Implementation:

No need for == true: IsValid already returns a boolean.
The constructors do not throw if validation fails: they fall back to a 'default' value instead. That's very surprising behavior, in a bad way. It's also inconsistent, because some input does produce an exception. (EDIT: Excuse me, they do throw, because IsValid throws - so that underlines the point below! ThrowIfInvalid would be a more appropriate method name.)
Why does IsValid throw an exception? Its signature suggests that it will only return true/false. Such unexpected behavior makes code more difficult to work with.
The value property can be written more succinctly as public DateTime Value => _value;, but you could also use a get-only property instead.
You may want to mention which version of C# you're using. I mentioned the a is null improvement from C#7, but I don't see that applied here
so I guess you're still stuck with an older version?

Finally, the == operator can be simplified:

if (ReferenceEquals(a, null) != ReferenceEquals(b, null))
{
    return false;       // One is null, the other is not
}
else if (ReferenceEquals(a, null))
{
    return true;        // Both are null
}
else
{
    return a.Equals(b); // Both are not null
}


Serialization/Deserialization with Generics in Java

SerializationUtil should work on T extends Serializable instead of T. This makes misuse harder.
Prefixing serializable to a data-holder is unnecessary for almost all intents and purposes.
You may be interested in operating on Path instead of String when Serializing and deSerializing
Your Util does not provide a way to serialize multiple instances of the same class :/


A few comments:

typedef your structs:

typedef struct Cell
{
    int val;
    struct Cell *next;
} Cell;

typedef means you no longer have to write struct all over the place:

Cell *cons(int val, Cell *rest)
{
    Cell *cell = malloc(sizeof(Cell));
    cell->val = val;
    cell->next = rest;
    return cell;
}

That not only saves keystrokes, it also can make the code cleaner since it provides a bit more abstraction.

I would check if the pointer is NULL rather than if it isn't (related question):

int length(struct Cell *list)
{
    if (!list) return NULL; // or something else like -1
    return 1 + length(rest(list));
}

Set the pointer to NULL after freeing it.

void destroy(struct Cell *list)
{
    if (list)
    {
        destroy(rest(list));
        free(list);
        list = NULL;
    }
}

Re-using a freed pointer can be a subtle error. Your code keeps right on working, and then crashes for no clear reason because some seemingly unrelated code wrote in the memory that the re-used pointer happens to be pointing at.  This is to prevent that.