This is quite fine. I have a few tips though.

Don't repeat yourself

The base path "/tmp/$USER-license-" appears many times.
This is error prone,
and it makes it difficult to change later.
It would be better to put this in a variable and reuse it everywhere.

here-document instead of printf

Instead of the printf statements to generate the headers,
here-documents would be simpler and better, for example:

cat <EOF >"$BASEPATH"-go
// $lineone
// $linetwo
// $linethree

EOF

Tabulation

Aligning things vertically like this may look nice at first:

case "$f" in
    *.go             ) typ="go"      ;;
    *.gohtml         ) typ="gohtml"  ;;
    @(*.bash|*.conf) ) typ="shell"   ;;
    *                ) continue      ;;
esac

The problem with this is if you want to change something later.
For example, I don't really see the purpose of the @(...) there,
so I would like to simplify:

case "$f" in
    *.go             ) typ="go"      ;;
    *.gohtml         ) typ="gohtml"  ;;
    *.bash|*.conf ) typ="shell"   ;;
    *                ) continue      ;;
esac

But that broke the formatting. What do I do now?
Add padding to line up the ) that is now out of line?
Or update the other lines?
The second option is not great, because I have to change many lines just because I changed one.
Just thinking about this is actually a waste of time.

Considering possible future changes,
I suggest to avoid this kind of writing style,
and stick to good old simple:

case "$f" in
    *.go) typ="go" ;;
    *.gohtml) typ="gohtml" ;;
    *.bash|*.conf) typ="shell" ;;
    *) continue ;;
esac

Alternative to sponge

I didn't know about sponge and moreutils,
I'm really glad your has question lead me to discover these gems.

On the other hand, unfortunately sponge is not a standard command,
and may not be readily available. Here's an alternative using GNU sed:

license="$BASEPATH"-$typ
sed -i -e "1r$license" -e '1{h;d}' -e '2{x;G}' "$f"


It seems to me that you are trying to retrieve the ID of a specific blockHash in the database, and if the entry does not exist, you want to create a new entry. This is where INSERT ... ON DUPLICATE KEY UPDATE comes in handy.

INSERT INTO `index_blocks` (`hash`) VALUES (?)
  ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
SELECT LAST_INSERT_ID();

Here's what you can do:

func createIndexBlock(blockHash string) int64 {
    result, err := db.Exec(`INSERT INTO index_blocks (hash) VALUES (?)
        ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`, blockHash)
    if err != nil {
        panic(err.Error())
    }

    id, err := result.LastInsertId()
    if err != nil {
        panic(err.Error())
    }
    return id
}

Alternatively, you can look into INSERT IGNORE, followed by a SELECT. That will work too.


The parameter does not need to be a ref, since there is no assignment to the variable a in the SelectionSort method.
There are too few tests.
The current test data looks entirely random, as if you had no idea what the interesting cases were.
The tests should at least cover some interesting edge cases, like:

An empty array
An array with only 1 element
An array with 2 elements
An array with 10 equal elements
An array that is sorted ascendingly
An array that is sorted descendingly
An array that is random
An array containing int.MinValue, 0, int.MaxValue
An array of 5 elements, in which every permutation is tested whether it sorts to the same results

The test code should be presented in the question as real test methods, not just a code snippet.


There is one relatively simple optimization you can do, for a start, and it will likely make a big difference...

If you analyze the equation:

n² + an + b, where |a| < 1000 and |b| < 1000

you need to solve it for where n² + an + b is prime.

The first n value to use is 0. 0² +a0 +b is b, thus, in order to process any values, it is clear that b needs to be a prime number (and not negative either...).

Thus, you should rearrange your loops, and your outer loop should be on the first k prime numbers in your set, where the k'th prime is < 1000.

There are 168 primes less than 1000, so that will reduce your loops from 2000 'b' loops to just 168.

Similarly, when you loop on only those 168 primes, you are guaranteed that the n == 0 result is prime, and you only need to test on the n > 0 condition.

Further, when n is 1,  the equation becomes:

1 + a + b = prime

or, since you have primes already from your sieve, you can significantly restrict the data-set by doing:

a = prime - b - 1

for primes in the range of b - 998 through to b + 1000 (which will keep a within the limits of -999 to +999). Note that there are no primes less than 2, and only a few hundred primes less than the 'worst case' (b ==999) + 1000

Only if you satisfy those two conditions would I consider even calling the prime function f(a,b,n++)


Straight forward. Easy to follow. But this is clearly some kind of fold.

randoms' = unfoldr (Just . random)

works nicely.


Making repeated ADODB queries from Excel-SQL Server

can I set up an ADODB connection as a global variable and reuse the same connection?

That would be the single worst thing to do. First because you would be making a critical resource globally scoped, and therefore you would lose control over its lifetime.

Second, because ADODB does connection pooling for you anyway, so the "cost" of opening a connection isn't really a thing; if a connection exists in the connection pool and is free to use, that's the connection ADODB will give you - it's there already.

From code perspective, a database connection should always be as short-lived as possible: open, fetch/execute, close.

This is interesting:

Dim rs As ADODB.Recordset

If Not (rs Is Nothing) Then
    If (rs.State And adStateOpen) = adStateOpen Then rs.Close
    Set rs = Nothing
End If

That whole block is never going to execute. You just declared rs and haven't assigned it yet: it's always going to be Nothing.

If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing

If no error occurred, your connection is always going to be opened here. And if an error occurred, your code isn't even running anymore. Make the conn.Close unconditional, and get rid of the redundant assignments to Nothing; the objects are going out of scope at End Sub, they're being destroyed anyway.

Actually, that Set rs = Nothing is potentially extending the lifetime of the rs object: without it, there's no in-scope reference to rs beyond rs.Close, and (assuming the VBA runtime can destroy objects while inside a procedure scope) VBA can destroy the object. But because of that Set rs = Nothing, you're keeping a reference around, and VBA cannot destroy the object until it passes that instruction.

If Not (rs Is Nothing) Then

The parentheses are redundant here: If Not rs Is Nothing evaluates to the same thing. Not (rs Is Nothing) simply forces rs Is Nothing to be evaluated to a value before Not processes (inverts) it, ...but that's exactly what happens either way, because of operator precedence rules.

If CBool(conn.State And adStateOpen) Then

The explicit conversion to Boolean is redundant here. That And is actually a bitwise operator here; it's not clear how the bitwise operation correctly converts to a Boolean - I'd suggest having a little helper function for this:

Private Function HasFlag(ByVal value As Long, ByVal flag As Long) As Boolean
    HasFlag = (value And flag) = flag
End Function

That way you can do If HasFlag(conn.State, adStateOpen) Then and have crystal-clear intentions.

I said earlier:

  And if an error occurred, your code isn't even running anymore.

That's quite a problem. You need to handle runtime errors. Database connections drop, a syntax error in strSqlQuery is likely (you're taking it as a parameter - who knows if it's legal SQL?), the rngToPrint could be in another workbook - so many things can go wrong!

First thing to fix is this:

Sheets(rngToPrint.Worksheet.Name).Cells(...)

The Sheets collection contains charts and other non-worksheet objects. Use the Worksheets collection when you want worksheets. But the biggest issue is that it's implicitly referring to the ActiveWorkbook. Yet nothing says rngToPrint comes from that workbook: if the active workbook has worksheets "Sheet1", "Sheet2" and "Sheet3" and rngToPrint is in another workbook and its Worksheet.Name is "DATA", your code blows up right here.

Why retrieve the worksheet from the Sheets/Worksheets collection, by its name, when you already have a reference to it?

rngToPrint.Worksheet.Cells(...)

Now, handle runtime errors:

Public Sub DoSomething()
    On Error GoTo CleanFail

    'code

CleanExit:
    'cleanup code
    Exit Sub
CleanFail:
    'error handling/recovering code
    Resume CleanExit
End If

With this pattern you close the recordset and connection under the CleanExit label, and because it runs whether or not an error has occurred then you make the clean-up conditional to the state of your object references (e.g. if rs Is Nothing don't try to close it) and/or your connection.

Your parameters are all passed ByRef implicitly, and they could all passed ByVal instead. The name ConnectServer doesn't convey what the procedure is doing at all (it's doing much more than just connecting to a server), and it's implicitly Public as well; making it explicitly Public would be good, or make it Private if it's not meant to be used beyond the scope of the module it's written in.

Hungarian Notation prefixes are superfluous, and misleading:

iCols - you're looking at a Long, not an "Integer".
sConnString - the name says "string", what's the s for?
rngToPrint - a better name would be simply destination.
FileName - no prefix? Parameter isn't used, remove it.

Whenever you feel the need to comment "this chunk of code does X", like here:

'Add headers

...you're looking a a chunk of code that actually belongs elsewhere. In this case, iCols belongs in the scope of a helper procedure that iterates a given recordset's fields, and writes the names of the fields in the first row of a given Range - add an explicit reference to the ADOR (Microsoft ActiveX Data Objects Recordset 6.0 Library) library too, so you can early-bind the Fields and Field object types:

Private Sub WriteColumnHeader(ByVal target As Worksheet, ByVal source As ADOR.Fields, Optional ByVal headerRow As Long = 1)
    Dim current As Long
    Dim fld As ADOR.Field
    For Each fld In source
        current = current + 1
        target.Cells(headerRow, current).Value = fld.Name
    Next
End Sub

Note that iterating a collection of objects is faster with a For Each loop; keep For loops for iterating arrays.

I find it a bit weird that you're writing the column names in row rngToPrint.Row - 1: that means I can't pass "A1" to your function as a destination, because you'll be attempting to write to row 0 and blow up. I would assume the first row of the destination range is the row where the column headers belong.

MsgBox "Error: No records returned.", vbCritical

"no records" isn't necessarily an error. It depends on the query! If I give your procedure a query that lists all reports for employee injuries in the past week, I'll be happy to see no records returned.

I wouldn't bother interpreting the results like this in this procedure - it's beyond its purpose: you don't know whether the client code is expecting records or not.

You could, however, be informative about it:

MsgBox "Query was executed, but no records were returned.", vbInformation

And keep vbCritical for actual errors, like if there's a syntax error in the query, or if the connection times out or otherwise can't be made to the server for whatever reason.


You didn't implement any error handling. Before doing something with the api response body, you should check if an error occured. Also the callback function of your read method should use the error first pattern. Here is a very short explanation: http://www.codingdefined.com/2015/10/what-are-error-first-callbacks-in-nodejs.html

Further, JSON.parse can throw an error if your api doesn't respond with a valid json string. So you might want to handle this error, too. Just add a try-catch block.


You may start making your model simpler:

public sealed class AlertifyMessageModel
{
    public string Message { get; set; }
    public string Callback { get; set; }
}

Note that you do not need all those ugly ctor parameters:

public ActionResult Test()
{
    return RedirectToAction("Details", "Notes",
        new AlertifyMessageModel { Message = "Lorem ipsum" });
}

You may also want to use nameof(Notes.Details) instead of hard-coded "Details" string. Usually I also have an helper method GetControllerName(nameof(NotesController)) or a static field NotesController.Name but it's verbose and not everyone likes it.

Now let's go to your View. We need to add a property to the model to hold the type of notification:

public sealed class AlertifyMessageModel
{
    public string Message { get; set; }
    public string Callback { get; set; }
    public string Type { get; set; } = "log"
}

Then we can simply write:

if (Model.Alertify.Message != null)
{
    @:@Html.Alertify(Model.Alertify.Type, Model.Alertify.Message, Model.Alertify.Callback)
}

Next step is to change Type to enum:

public NotificationType Type { get; set; } = NotificationType.Log;

For your URL problem you should change something more, you may serialize the whole object as JSON and post it in the request body instead of in the URL. I don't see code around that then I can't really suggest a nice method. Note that you may also override ToString() to return a parseable representation of AlertifyMessageModel (think about type converters).


You can combine your two methods in just one method, making the whole process much easier to understand due to less "jumping around".

static <T> List<List<T>> getSublists(List<T> list) {
    if (list.isEmpty()) {
        // if empty, return just that empty list
        return Collections.singletonList(list);
    } else {
        List<List<T>> sublists = new ArrayList<List<T>>();
        T first = list.get(0);
        // for each sublist starting at second element...
        for (List<T> sublist : getSublists(list.subList(1, list.size()))) {
            //... add that sublist with and without the first element
            // (two lines more, but this preserves the original order)
            List<T> sublistWithFirst= new ArrayList<T>();
            sublistWithFirst.add(first);
            sublistWithFirst.addAll(sublist);
            sublists.add(sublist);
            sublists.add(sublistWithFirst);
        }
        return sublists;
    }
}

Some more points:

I'd recommend using the more generic List whenever possible.
Also, no need to restrict the method to lists of integers.
That code definitely deserves some comments.
You are actually returning sub-lists; name your methods accordingly.
Note that by calling remove on the input list, you are modifying the original list!


Try this:

struct MyListener
{
    virtual void on_data(int value) = 0;    // same function name
    virtual void on_data(string value) = 0; // same function name
    ...
};

template<typename T>
void MyClass::trigger_data_event(T&& value) // pass by universal reference
{
    auto iter = _listeners.begin(); // consider using auto where appropriate

    while (iter != _listeners.end())
    {
        // don't use expired here: it involves concurrency issues if the pointer
        // is invalidated between calling expired and lock

        // instead, just lock() and check the result:

        if(auto p = iter->lock())
        {
            p->on_data(std::forward<T>(value)); // works with both callbacks
            ++iter;
        }
        else
            iter = _listeners.erase(iter);
    }
}

I renamed the APIs you used from callback1/2 to on_data (same name) and unified the implementations of fireCallback1 and fireCallback2.


Bisection method for finding the root of a function

It is customary to use eps instead of e.
A ((b-c) / c) <=e condition doesn't look right (try \$f(x) = x\$ on the \$(-1, 1)\$ interval and observe a division by 0).
You seem to assume that b > a (otherwise the loop breaks immediately). Make sure to swap a and b if it is not so. Making sure that eps is positive also helps.
The code produces wrong results for a non-continuous \$f\$. I recommend to test that the function value at a suspected root is close enough to \$0\$.
Avoid break. while (b - a > eps) is much cleaner.


String manipulations (reverse a string by characters, permutation)

There's a problem with the algorithm for arePermutuations. For instance, arePermutations("aab", "bba") will return true.


Spring configuration without XML is this reality?

You definitely want to look into Spring Boot. It can significantly reduce Spring configuration + has a lot of features that help to with deployment to production. Think about it as "convention over configuration" wrapper for Spring framework.

If you would follow Spring Boot conventions, you may need to shift some resources to different folders, but I believe you would be able to eliminate your spring configuration rapidly/completely.

If you decide not to use Spring Boot:

You may want to use AbstractAnnotationConfigDispatcherServletInitializer instead of WebApplicationInitializer, because I don't observe any unusual servet configuration. It may look like this:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{ApplicationConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}


Prefer standard integer types

Instead of:

using uint = unsigned int;

Prefer

#include <cstdint>
//use the std::uint32_t in code (or whichever width)

Don't use namespace std

Common advice which will help guard against namespace collisions. In your case I think you could get away with just:

using std::vector;

Quicksort Algorithm

A common optimization to remove average case comparisons is to more intelligently select your pivot. One approach which strengthens the asymptotic runtime of the algorithm is the 'median of fives' approach. In this approach you select your pivot to be the median of 'the median of each of the n/5 sublists of length 5'. In practise, however, this could increase the number of comparisons. It's hard to recommend a strategy without knowing the size and characteristics of your input.


Implementing numerical integration in Python

I have this Python code that implements a rectangular numerical integration.

In what sense "rectangular"? Or is that as opposed to contour integration?

  It evaluates the (K-1)-dimensional integral for arbitrary integer \$K \geq 1\$

  $$\int_{u_K = 0}^{\gamma}\int_{u_{K-1} = 0}^{\gamma-u_K}\cdots\int_{u_2}^{\gamma-u_K-\cdots-u_3}F_U(\gamma-\sum_{k=2}^Ku_k)f_U(u_2)\cdots f_U(u_K)\,du_2\cdots du_K$$

  where \$F_U\$ corresponds to the cdf function in the code, and \$f_U\$
  to the pdf.

It would probably help to rewrite it in fully symmetric form: $$\underset{\substack{u_i \ge 0 \\ u_1 + \cdots + u_K \le \gamma}}{\int \cdots \int} f_U(u_1)\cdots f_U(u_K) \textrm{d}u_1 \cdots \textrm{d}u_K$$

Then you can exploit the symmetry to divide the polytope of interest into equivalent chunks and only integrate each chunk once.

  I implemented it using recursion as follows:

    #************************** Import necessary libraries******************************************
import numpy as np
import matplotlib.pyplot as plt
import time
#******************************Set the constant scalars and vectors***************************
start_time = time.time()

So far I understand.

KU = 3
eta_dB = 3
eta = 10**(eta_dB/10)
ExpanF = 50

tdB = np.arange(-5,11,4)
tVec = 10**(tdB/10)
thVec = (tVec/eta)*(ExpanF-eta*(KU-1))

What do any of those mean? "constant scalars and vectors" is not an adequate description.

N = 10000 # For simulation

du = 0.01

#******************************Define functions to be used***************************************
#Define the CDF of U
def CDF(u):
      return 1-1/(u+1)

#Define the PDF of U
def pdf(u):
     return 1/((1+u))**2

If \$f_U\$ is that simple, it might make more sense to tackle it with symbolic integration rather than quadrature.

def FK(h, k):
    #print(f'h is {h}, and k is {k}')
    if k == 1:
        res = CDF(h)
    else:
        #n_iter = int(h/du)
        res =  0
        u = 0
        while u < h:
            res += FK(h-u, k-1)*pdf(u)*du
            u += du
    return res

This could use some comments. It seems to be first order quadrature. If you use a higher order, maybe a larger step size will give you equally accurate results much faster.

#*******************Find the numerical and simulation values of the integral******************
ResultNum = []
ResultSim = []

if (ExpanF-eta*(KU-1)) > 0:
    for t in thVec:
    # Numerical
        ResultNum.append(1-FK(t, KU))
    # Simulation
        count = 0
        for n in range(0, N):
            if np.sum(np.random.exponential(1, (1, KU))/np.random.exponential(1, (1, KU))) <= t:
                count += 1
        ResultSim.append(1-count/N)

I'm missing a lot of context here.


Reconstructing Matrix scattered over many MPI ranks

Note: I've written a matrix multiplication benchmark program in C and MPI:https://github.com/thefangbear/matrix-mpi. It uses a row-major format to store the two matrices in 1D arrays for better cache coherency. It also supports both synchronous and asynchronous send/receive modes, tunable via a preprocessor macro, so you can take a look.

With that being said, let's turn to a few improvable parts in your code:

You don't have to use an array of pointers to represent the matrix format. You can use an 1D array with row-major/column-major format. If you use a "2D array" (array of pointers), each row/colum slice of your matrix are not guaranteed to be stored in consecutive locations.
Isend/Irecv lead to degraded performance. You can verify this via benchmarking. MPI sends/receives extra messages when asynchronous mode is used, which makes basic operations more expensive. And since you have blocking anyways somewhere in your code, ISend/IRecv do not make a huge difference.
It is common for worker nodes to send back processed slices of data to be merged and outputted in the master node. You can technically just invoke printf in a loop on each worker node to output its own slice of data (since mpirun redirects all stdout streams on each node to your terminal screen), but MPI does not guarantee the order of output.
If you want a more elegant semantics, you should checkout MPI_Scatterv/MPI_Gatherv scatter/gather functions: https://www.mpich.org/static/docs/v3.1/www3/MPI_Scatterv.html. (But I don't think you'll get significant performance gains by using them)


I've reviewed your code and I can make the following remarks. I'm only going to review the Graph class for now so lets start:

class Graph:
    """class graph"""

Here the comment is redundant. We know its a Graph and we know its a class. Also note for completeness I like to write class Graph(object)

def __init__(self, v_in):
    """constructor -  takes number of vertices and creates a graph
    with no edges (E = 0) and an empty adjacent lists of vertices"""
    self.V = v_in
    self.E = 0
    self.adj = []
    for i in range(v_in):
        self.adj.append([])

Again the comment is redundant We know its a constructor and what it initializes. However as you may notice the real problem here is not the comment but what it describes. Those V, E, v_in parameters are too short and do not mean anything. If I  were to read the method body and not the class name I wouldn't be able to understand that they denote Vertices and Edges. So a better name for them would be vertices, edges and input_vertices. Note that we use lowercase names for class properties.

def V(self):
    """returns number of vertices"""
    return self.V

def E(self):
    """returns number of edges"""
    return self.E

More redundant notes as we know they return something. However the method names are wrong. Why V and E? And why do they return a number? I would suspect to return a list or an Object that I can query. A better name would be again vertices and edges.

def add_edge(self, v, w):
    """void, adds an edge to the graph"""
    self.adj[v].append(w)
    self.adj[w].append(v)
    self.E += 1

def adj_list(self, v):
    """returns the adjacency lists of the vertex v"""
    return self.adj[v]

That's not too bad although I would remove the void remark and add a better explanation about the input assumptions. For example what happens if  do add_edge(set((1,2,3)), frozenset((4,5,6)))? Traceback error. So its better to specify that it assumes the input is integers.

def __str__(self):
    """to string method, prints the graph"""
    s = str(self.V) + " vertices, " + str(self.E) + " edges\n"
    for v in range(self.V):
        s += str(v) + ": "
        for w in self.adj[v]:
            s += str(w) + " "
        s += "\n"
    return s

Ok nothing wrong here. I would only rename s to output or response so that I understand the meaning.

In general I would say to try to keep the names consistent and meaningful so a reader will not have to guess whats going on.


Modeling a pair of dice using composition in C++

Some miscellaneous remarks unrelated to object-oriented design:

Die face numbering: Your die face values are 0, 1, 2, 3, 4, 5.  That's not how most people expect a six-sided die to be labeled.  It also makes an exceptionally weird definition of rolling snake eyes!
Biased die: Since 6 is not a power of 2, if you just do rand() % 6 then you have a slightly biased die.
Roll miscount: You aren't rolling a pair of dice 1000 times.  You're rolling a pair of dice until you get 1000 results other than 2 or 6.  You could probably have avoided this bug if you had used a for-loop instead of a while-loop, since for-loops impose a standard structure on your code.
Variable declaration: In main(), the variable total is only used within the while-loop, so it should be declared at the point of use: int total = dice.roll();
Seeding: You didn't actually call srand().
Portability: system("pause") is unportable.
ostream support: Consider implementing std::ostream &operator<<(std::ostream &out, ...) for printing.


Your function is nice but has a few issues, the main one being that it
  should not call srand.  srand should be called elsewhere (eg in main)
  just once.  This seeds the random number generator, which need only be done
  once.

A minor issue is that string is badly named - charset might be better.
  It should be const and you then need not call strlen to find its length
  sizeof charset -1 is enough.  For me, randomString is an unnecessarily
  long name.

On failing to allocate memory for the string, I would prefer to see a NULL
  return than an exit.  If you want an error message, use perror, but
  perhaps in the caller, not here.  I would be inclined to avoid the
  possibility of such an error but passing in the buffer and its length
  instead of allocating.

Some minor points: sizeof(char) is 1 by definition and using short for
  key is pointless - just use int.  Also key should be defined where it
  is used and I would leave a space after the ; in the for loop definition.

Note also that using rand() % n assumes that the modulo division
  is random - that is not what rand promises.

Here is how I might do it:

static char *rand_string(char *str, size_t size)
{
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK...";
    if (size) {
        --size;
        for (size_t n = 0; n < size; n++) {
            int key = rand() % (int) (sizeof charset - 1);
            str[n] = charset[key];
        }
        str[size] = '\0';
    }
    return str;
}

Edit July 31 23:07UTC

Why would I write the function to take a buffer instead of allocating the
string inside the function?

Returning dynamically allocated strings works fine.  And if the memory is
later freed there is no problem.  But writing this sort of function is a great
way to leak memory, for example if the caller doesn't know the memory must be
freed or forgets to free memory, or even if he frees it in the main path but
forgets to free it in other paths etc.

Memory leaks in a desktop applications might not be fatal, but leaks in an
embedded system will lead eventually to failure.  This can be serious,
depending upon the system involved.  In many embedded systems, dynamic
allocation is often not allowed or is at least best avoided.

Although it certainly is common not to know the size of strings or buffers
at compile time, the opposite is also often true.  It is often possible to
write code with fixed buffer sizes.  I always prefer this option if possible
so I would be reluctant to use your allocating function.  Perhaps it is better
to add a wrapper to a non-allocating function for those cases where you really
must allocate dynamically (for example when the random string has to outlive the calling context):

char* rand_string_alloc(size_t size)
{
     char *s = malloc(size + 1);
     if (s) {
         rand_string(s, size);
     }
     return s;
}


Fill a collection from a database with all values filled

Have you considered linq? Something like:

        var j = from i in new[] {1, 2}
                from s in new[] {"a", "b"}
                select new {i, s};

or in method syntax:

        var j = new[] {1, 2}.SelectMany(i => new[] {"a", "b"}, (i, s) => new {i, s});


Depth analysis

A bit of tweaking of your code leads to results about the maximum function call depth:

def problem_31_a(money, coin_index, depth=1):
    global glob_depth
    glob_depth = max(glob_depth, depth)
    count = 0
    if coin_index <= 0:
        return 1
    m = money
    if memoiz_list[m][coin_index] > 0:
        return memoiz_list[m][coin_index]
    while money >= 0:
        count += problem_31_a(money, coin_index - 1, depth=depth+1)
        money -= coin_list[coin_index]
    memoiz_list[m][coin_index] = count
    return count

def problem_31_b(money, coin_index, depth=1):
    global glob_depth
    glob_depth = max(glob_depth, depth)
    if coin_index < 0:
        return 0
    if coin_index == 0 or money == 0:
        return 1
    if memoiz_list[money][coin_index] > 0:
        return memoiz_list[money][coin_index]
    if coin_list[coin_index] > money:
        return problem_31_b(money, coin_index - 1, depth=depth+1)
    memoiz_list[money][coin_index] = problem_31_b(money, coin_index-1, depth=depth+1)+ \
                                     problem_31_b(money-coin_list[coin_index],coin_index, depth=depth+1)
    return memoiz_list[money][coin_index]

coin_list = [1,2,5,10,20,50,100,200]

for func in [problem_31_a, problem_31_b]:
    glob_depth = 0
    start = time.time()
    memoiz_list = [[0,0,0,0,0,0,0,0] for i in range(201)]
    print(func(200,7))
    elapsed = time.time() - start
    print("Result found in %f seconds - depth:%d" % (elapsed, glob_depth))

And indeed, we get:

73682
Result found in 0.003184 seconds - depth:8
73682
Result found in 0.000919 seconds - depth:107

Your code appears to be faster but also goes much deeper in the function calls. If you exceed the system limits, you could update sys.setrecursionlimit. However, it could be a good idea to try to fix your code.

You could write a solution that doesn't perform any recursive calls: instead of trying to solve your problems by solving smaller and smaller problems and saving the solution as you go, you could simply update all the problems from the smallest to the biggest you need.

For instance, you could write:

def problem_31_c(money, unused):
    nb_ways = [1] + [0] * money
    for c in coin_list:
        for v in range(money + 1 - c):
            nb_ways[v + c] += nb_ways[v]
    return nb_ways[-1]

Actual code review

For both functions, it could be a good idea to make it obvious that we have the following pattern:

if value_from_memoiz_list:
    return value_from_memoiz_list
compute_value
store_value_in_memoiz_list
return value

In problem_31 for instance, we can see that a situation leads to a result being computed and returned without being store in the memoized list. Also, that case could be handled with less duplicated logic:

count = problem_31_b(money, coin_index-1)
coin_value = coin_list[coin_index]
if coin_value <= money:
    count += problem_31_b(money-coin_value,coin_index)

Finally, your strategy reusing computed value assumes that 0 is a non-existing result. You could use None for this. In your case it doesn't make a difference because no expensive computation leads to 0 but it makes the intent of your code clearer.

def problem_31_a(money, coin_index):
    if coin_index <= 0:
        return 1
    money_rem = money
    memo_value = memoiz_list[money][coin_index]
    if memo_value is not None:
        return memo_value
    count = 0
    while money_rem >= 0:
        count += problem_31_a(money_rem, coin_index - 1)
        money_rem -= coin_list[coin_index]
    memoiz_list[money][coin_index] = count
    return count

def problem_31_b(money, coin_index):
    if coin_index < 0:
        return 0
    if coin_index == 0 or money == 0:
        return 1
    memo_value = memoiz_list[money][coin_index]
    if memo_value is not None:
        return memo_value
    count = problem_31_b(money, coin_index-1)
    coin_value = coin_list[coin_index]
    if coin_value <= money:
        count += problem_31_b(money-coin_value,coin_index)
    memoiz_list[money][coin_index] = count
    return count

Also, you could use a decorator to implement your memoization strategy.

Reusing a generic decorator from https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize , you could write:

coin_list = [1,2,5,10,20,50,100,200]

class memoized(object):
   '''Decorator. Caches a function's return value each time it is called.
   If called later with the same arguments, the cached value is returned
   (not reevaluated).
   '''
   def __init__(self, func):
      self.func = func
      self.memoiz_list = [[None]*len(coin_list) for i in range(201)]
   def __call__(self, money, coin_index):
      try:
          memo_value = self.memoiz_list[money][coin_index]
          if memo_value is not None:
              return memo_value
      except IndexError:
          pass
      ret = self.func(money, coin_index)
      try:
          self.memoiz_list[money][coin_index] = ret
      except IndexError:
          pass
      return ret
   def __repr__(self):
      '''Return the function's docstring.'''
      return self.func.__doc__
   def __get__(self, obj, objtype):
      '''Support instance methods.'''
      return functools.partial(self.__call__, obj)

@memoized
def problem_31_a(money, coin_index):
    if coin_index <= 0:
        return 1
    money_rem = money
    count = 0
    while money_rem >= 0:
        count += problem_31_a(money_rem, coin_index - 1)
        money_rem -= coin_list[coin_index]
    return count

@memoized
def problem_31_b(money, coin_index):
    if coin_index < 0:
        return 0
    if coin_index == 0 or money == 0:
        return 1
    count = problem_31_b(money, coin_index-1)
    coin_value = coin_list[coin_index]
    if coin_value <= money:
        count += problem_31_b(money-coin_value,coin_index)
    return count


Change SQL Query may help you in someway, like this,

SELECT reg_id, tra_type, GROUP_CONCAT(pro_id SEPARATOR ',') AS pro_ids
FROM exp
WHERE pro_id in ($implode_mas)
AND tra_type = '1'
GROUP BY reg_id;

Result will be like this

reg_id    tra_type    pro_ids
1         1           2,6,10
4         1           10

Then you can split it to array


Your code is secure against SQL injection but it's largely inefficient. And this army of bindParams's takes the largest part in it. All you need is just to send an array you already have directly into execute():

$stmt->execute($data);

Registration

On the other hand, your use of try and catch operator for insert is proper, which is a rare sight. The only objection is error messages that shouldn't be bluntly echoed out. Better to collect them and show nicely along with a form. So I would make the whole registration code as

$error = '';
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
try {
    $stmt = $dbh->prepare("INSERT INTO `accounts` (`account_id`, `firstname`, `lastname`, `username`, `password`, `email`, `city`, `postalcode`, `adress`, `country`, `role`)
      VALUES (NULL, :firstname, :lastname, :username, :password, :email, :city, :postalcode, :adress, :country, 0) ");
    $stmt->execute($data);
} catch (PDOException $e) {
    if (strpos($e->getMessage(), "for key 'login'")) {
        $error =  'Duplicate login entry';
    } elseif (strpos($e->getMessage(), "for key 'email'")) {
        $error = 'Duplicate e-mail entry';
    } else {
        throw $e;
    }
}
if ($error) {
    echo $error;
} else {
    header("Location: ...");
    exit;
}

Login

The login code could be improved as well. I've got a ready made example, Authenticating a user using PDO and password_verify(), you may check it out for the actual code. Here I will just comment on some parts

} catch (PDOException $e) {
    throw $e;
}

I fancy you just copy-pasted this part from the insert example. But if you think on it, it will become clear that this code will behave exactly the same without try, catch and throw operators! So they should be simple taken out.

$rows = $stmt->rowCount();

is essentially useless, as you have the fetch result that can be used instead.

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

fetchAll() doesn't seem to be a wise choice, as it adds unnecessary dimension to the resulting array. fetch() should be used instead.


Converting from POS tagged word-tokens to POS tagged Phrases

Apart from choosing more optimal functions (xrange, in), this looks okay I think; a bit more nesting can be removed by inverting the conditions and use continue instead; it also looks like the last return statement could be faster if the intermediate results from the inner loops were collected in a separate result, but I may read that wrong.

from nltk.corpus import wordnet as wn

def get_tagged_phrases(tagged_sent, max_phrase_length):
    tagged_sent = list(tagged_sent)

    for phrase_len in xrange(max_phrase_length, 1, -1): #Go from largest to smallest to keep information
        for indexes in n_wise(phrase_len, xrange(len(tagged_sent))):
            tagged_words = [tagged_sent[index] for index in indexes]

            if None in tagged_words:
                continue

            words, tags = zip(*tagged_words)
            possible_phrase = "_".join(words)

            if not wn.synsets(possible_phrase): #If there are any, then it is a phrase
                continue

            for index in indexes:
                tagged_sent[index] = None #Blank them out with Nones which we will remove later

            pos = tags[-1] #Use final tag, it will be the one we need for handling plurals
            tagged_sent[indexes[0]] = (possible_phrase, pos)

    return [tagged_phrase for tagged_phrase in tagged_sent if not tagged_phrase is None]


Collecting 3 years of data and building a string

I'll focus on the C# part of the code, but please run the output HTML through a validator because at first glance I count no fewer than five HTML tags that are mismatched, misplaced, or simply broken.

Outer loop

You're not using the loop variable x anywhere. This suggests that the loop should be refactored around the thing that you're actually iterating over, which seems to be a range of years.

Each year is just an integer; you can get a range of integers using Enumerable.Range. You want the most recent totalYearCount years (inclusive of this year), so start the range at nowYear - totalYearCount + 1. You want this year first, so reverse the sequence too.

foreach (var year in Enumerable
    .Range(aDate.Year - totalYearCount + 1, totalYearCount)
    .Reverse())
{
    var list = ms.GetListOfMeetingBygroupId(groupId, year);
    // ...
}

You can replace aDate.ToString("yyyy") accordingly.

Naming

When using camelCase and PascalCase, each distinct word should start with a capital letter. GetListOfMeetingByGroupId, GetListOfPresentationsByMeetingId, meetingStartDate, meetingEndDate, and so on.

Type prefixes like sb don't help much, especially when abbreviated. Rename that variable to better reflect what it actually is: it's a builder for the output, so maybe outputBuilder instead of sbMeeting.

list is a really generic name for something we know to be a collection of meetings, so call it meetings or meetingList.

Code we haven't seen

It's advised to post or link to all supporting code. It's at least relevant because of this here:

Convert.ToDateTime(meeting.MeetingDateList.Select(c => c.StartDate).Max());

What's the type of c.StartDate? You're converting it to a DateTime after getting the maximum date -- so it's probably not a DateTime already -- which begs the question how are you sorting the dates? I suspect you might've wanted the order switched:

meeting.MeetingDateList.Max(c => Convert.ToDateTime(c.StartDate));

Note that I've used the overload for Max that takes a selector so that I can avoid the unnecessary Select.

General readability

Your spacing is inconsistent. Consistent spacing would make for better readability, so I offer these suggestions:

Use exactly one indent per {} block -- your inner foreach loop is double-indented.
Avoid empty lines of padding within {} blocks -- see your for loop and the else block.
Parameters should be separated by a comma and one space -- see your first sbMeeting.AppendFormat(...).

All of those hard-coded HTML strings should be refactored out into some kind of template. They have no business being encoded inline in the method like that.


Calculating the percentage on Python 2.7

I take it from your code the game works like this:

Each player enters their names. The names can't be blank nor the same with each other.
A coin is tossed to determine the turn order.
The turn player decides the amount of damage (M) he wants to deal against the other player. The chance of dealing damage is calculated by (100 - M).

With that, I have this code:

player1, player2 = input_player_names()
print("Welcome to the game {} and {}".format(player1, player2))
print("Tossing coin... Heads for {}; tails for {}".format(player1, player2))
turn_order = determine_turn_order([player1, player2])
print(turn_order[0], "plays first")
play(turn_order)

And the respective implementations:

def input_player_names():
    player1 = ""
    player2 = ""
    while player1 == "":
        player1 = input("Player 1, please enter your name.")
    while player2 == "" or player2 == player1:
        player2 = input("Player 2, please enter your name.")
    return player1, player2

def determine_turn_order(player_list):
    turn_order = []
    toss = random.randint(0, 1)
    turn_order.append(player_list[toss])
    turn_order.append(player_list[toss + 1 % 2])
    return turn_order

def play(turn_order):
    player_health_points_list = [50, 50]
    turn_number = 0
    while there_are_no_winners_yet(player_health_points_list):
        turn_player = turn_order[turn_number % 2]
        player_is_sure = False
        chance = 100
        damage_to_deal = 0
        while not player_is_sure:
            damage_to_deal = input(turn_player + " enter damage you want to deal: ")
            damage_to_deal = int(damage_to_deal)
            chance = chance - damage_to_deal
            if chance < 50:
                player_is_sure = bool(input("You have only a {}% chance of dealing damage. Are you sure you want to push through? Input 1 for yes; 0  for no.".format(chance)))
            else:
                player_is_sure = True

        # Here's how I'd calculate determine whether the attack hits or not
        if chance > random.randint(1, 100):
            player_health_points_list[(turn_number + 1) % 2] -= damage_to_deal
        turn_number = turn_number + 1
        print(turn_order[0], '|' * player_health_points_list[0])
        print(turn_order[1], '|' * player_health_points_list[1])
    declare_winner(turn_order, player_health_points_list)

def there_are_no_winners_yet(player_health_points_list):
    return player_health_points_list[0] > 0 and player_health_points_list[1] > 0

def declare_winner(turn_order, player_health_points_list):
    print("The winner is {}".format(turn_order[0] if player_health_points_list[0] > player_health_points_list[1] else turn_order[1]))


hash is poorly named, I think, but that's a minor detail.

Your solution is inefficient because you are doing it all with sequences.  Have you considered that zipWithIndex is also duplication?  You've already worked through the input stream once - each time you calculated the current sum, you could (had you wanted) have been aware of your position in the list?  You're duplicating work.

More efficient solution (in that there will only be one traversal) is to fold, not scan and to build a map (for quick extraction of results).

Fold over the input stream, with a seed of (0, 0, Map[Int, List[Int]]).  The first value is an index accumulator, the second is a sum accumulator and the nature of the map will become obvious shortly.  The function you apply to each fold iteration should

Add the current stream item to twice the accumulated sum.
If the resulting number is not a key in the map, insert `list(index-accumulator-value)' into the map with that newly-calculated number as a key
If the resulting number is already a key, add index-accumulator-value to the list stored under that key (important: cons it to the list, do not append).
Increment the index accumulator by one.
Add the current stream item to the accumulated sum.
Return (index-accumulator, sum-accumulator, map)

Once the fold has completed, you will have

The size of the stream (which you don't need)
The sum of the stream (which you do)
A map.

If the map contains a key which is equal to the sum of the stream, the value associated with that key will be a list of all equilibrium indices, sorted in reverse order.  If there is no such key, there were no equilibrium indices.

Minimal traversal
No filtering necessary
Rapid access to final result because Map

Done.

Annoyed that the final result is in reverse order?  Reversing one final list is cheap compared to appending to each list in the map, every time.

Note that you can dispense with having to manage the index-accumulator by folding over in.zipWithIndex


Parsing strings with escaped characters using Parsec

Some suggestions:

Replace fst and snd with a pattern match or explicit function arguments.
Extract the common char '\\' parser. You can then avoid the try.
Strings with lots of escaped characters are hard to read and it's hard to visually
verify that the escape codes are correctly matched with their replacements. Consider
spelling them out and aligning them to make this easy to see.

Here's what I came up with:

escaped = char '\\' >> choice (zipWith escapedChar codes replacements)
escapedChar code replacement = char code >> return replacement
codes        = ['b',  'n',  'f',  'r',  't',  '\\', '\"', '/']
replacements = ['\b', '\n', '\f', '\r', '\t', '\\', '\"', '/']


Bug in your code
Here you are accessing the levelMap by 'Y' then 'X'
        int tile = levelMap[indexY][indexX];

In all other places you are accessing the levelMap by 'X' then 'Y'
if(levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1) //Right collision

So it looks like you are running around a maze that has been printed incorrectly on the screen. and thus it looks like collision detection is not working (it probably is) but the detection does not match the visual cues.
Reviewing your code:
These expressions
if(levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1) //Right collision
{
    colR = true;
}else colR = false;

Can be simplifies too:
colR = (levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1); //Right collision

While these
if (GetAsyncKeyState(VK_RIGHT) && colR == false){pacmanPosX += 2;}

can be simplified to:
if (GetAsyncKeyState(VK_RIGHT) && !colR)
{    pacmanPosX += 2;
}

Putting the statement on the same line as the test makes it harder to debug (when stepping through with the debugger) as you can not see when then the statements are executed. By putting it on its own line stepping through with the de-bugger does become easier as you will see it skip the statement when the condition fails.
Global state is the easy way to do things.
int pacmanPosX = 32;
int pacmanPosY = 32;
int indexX;
int indexY;

bool colR;
bool colL;
bool colU;
bool colD;

But in the long run makes your code more brittle and harder to update. Pass things as parameters to make it easier to maintain and extend your code (or create an object that wraps the information).
Also it looks like some of these properties would be better held in arrays rather than individual variables.
Edit base on comments:
This only detects a collision if the top right corner hits a wall.
colR = (levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1); //Right collision

Change too:
colR =    (levelMap[(pacmanPosX+33)/32][(pacmanPosY+00)/32] == 1)  // Top right
       || (levelMap[(pacmanPosY+33)/32][(pacmanPosY+31)/32] == 1); // bottom right

// Use +33 because moving left you use -2
// When you move right +32 puts you in the first pixel of the next block
//                     +33 puts you in the second pixel just like move left detection

// Use +31 on the Y access because this is still inside the current sprite.

Note If you have a hole in the wall that is exactly one block wide you need to hit it dead center to pass through the gap. To give you some wiggle room you can move the corners in slightly.
colR =    (levelMap[(pacmanPosX+33)/32][(pacmanPosY+02)/32] == 1)  // Top right
       || (levelMap[(pacmanPosY+33)/32][(pacmanPosY+29)/32] == 1); // bottom right

Here you do not need to hit the whole in the wall dead center and you get some wiggle room passing through.


Get result from UI thread to non-UI thread when using await Task.Run

You're scheduling a new non-UI operation that immediately goes back and schedules an operation to run in the UI thread, which then does some work.

Just avoid all of that, and do the work that you want to do right from the start, since you're in the UI thread:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var mySettings = new MetroDialogSettings()
    {
        AffirmativeButtonText = "YES",
        NegativeButtonText = "NO",
        ColorScheme = MetroDialogColorScheme.Accented
    };

    var response = await this.ShowMessageAsync("Hello!", "message", MessageDialogStyle.AffirmativeAndNegative, mySettings);

    if(response == MessageDialogResult.Negative)
        return;
}


Will this test to check if an element has an attribute work?

To check if an HTML element has an attribute, you should use hasAttribute. If you have to support IE6 and IE7, check its existence using [name].

Given that, the implementation of hasAttr would be something like this:

hasAttr = function(tag, attrName) {
    return tag.hasAttribute ? tag.hasAttribute(attrName)
                            : tag[attrName] !== undefined;
}


I didn’t review or see your old code when it was posted, but this is noticeably improved. However, I can still make a few suggestions:

num and nums are not great variable names. Characters are cheap; just write out the word number in full. I would also suggest giving numbers a slightly different/longer name to make it easier to read the line where you define slide.

Likewise pair/pairs could be a little easier to read, I think.
A few comments on the different branches to explain why you’re behaving in a particular way would be useful – to somebody unfamiliar with the rules of 2048, it might not be immediately obvious why it behaves the way it does.
A description of the doctest doesn’t belong in the function docstring, it probably belongs in a comment on the main() function. If I import your function into another file and then inspect merge.__doc__, the mention of a doctest “below” could be confusing.
Having “no output” mean success could be a problem, because there’s no way for me to distinguish between a success and the test not running. It should be totally clear whether your test passed, failed, or didn’t run. Anything else can hide problems.


Checking locked users using Identity 2.0

Only focusing on this part

var user = UserManager.Users.Where(u => u.UserName == model.Email).SingleOrDefault();
if (user != null)
{
    if (user.Locked)
    {
        return View("Lockout");
    }
}
else
{
    ModelState.AddModelError("", "Invalid login attempt.");
    return View(model);
}

Are you aware that if the Users contains more than one user with the same Email the call to SingleOrDefault will throw an InvalidOperationException ? If you are 100 percent sure that this won't ever happen then there won't be a problem.

In its current state this linq query will for each user query the model for the Email property. If you store it in a variable the access will be much faster.

Checking first if the user == null will make it more obvious what is happening. As I first looked over this code I thought hey, how should the code after the if..else ever be reached.

Applying this will lead to

    string email = model.Email;
    var user = UserManager.Users.Where(u => u.UserName == email).SingleOrDefault();
    if (user == null)
    {
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
    }

    if (user.Locked)
    {
        return View("Lockout");
    }

This looks far better IMO and is more readable.

Usually a username isn't checked in a case sensitive way so instead of u.UserName == email you should use the string.equals() method.

This method takes as the third parameter a StringComparison enum which defines how the comparison will take place. The best one for all cultures, for instance using a turkish locale can make problems (does-your-code-pass-turkey-test), will be to use StringComparison.OrdinalIgnoreCase.

Applying this will lead to

    string email = model.Email;
    var user = UserManager.Users.Where(u => string.Equals(u.UserName, email, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
    if (user == null)
    {
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
    }

    if (user.Locked)
    {
        return View("Lockout");
    }


To be able to create a parameter-less constructor add the following code into your constructor. It will use reflection to set entityClass. This way you don't even need to worry about passing in a class type, you can extend out your generic DAO and its type will be set by parameterisation.

public GenericDaoImpl() {
    Type e = getClass().getGenericSuperclass();
    ParameterizedType pt = (ParameterizedType) e;
    entityClass = (Class<E>) pt.getActualTypeArguments()[0];
}

This removes the need for having constructors in subclasses of your GenericDAOImpl.

Why don't you combine your create and update methods? It makes for easier service calls.

@Override
public void saveOrUpdate(E e){
    getCurrentSession().saveOrUpdate(e);
}

Hibernate will automatically make the determination whether a save or update call is appropriate. If your ID field is set, then perform an update, otherwise perform a save.

Also, I would remove getCurrentSession() from your interface and change the method to private. You shouldn't be accessing the Hibernate session from anywhere outside the DAO so there is no reason to expose out your getCurrentSession() method.


Best way to retrieve parameters from associative array in javascript?

I would say

var target = functionobject.target || $('#page_links');

How did I arrive at that?  The important point to get across is that no matter what happens, you want to assign something to target.  One first attempt to express that would be to use the ternary operator

var target = functionobject.target ? functionobject.target : $('#page_links');

However, the repetition of functionobject.target is ugly.  It would be better to use the short-circuit evaluation feature of the a || b operator.  If a is true, then evaluation stops, and the value of the expression is just a.  Otherwise, the value of the expression is b.


Hamming distance between numbers in JavaScript

A few things could be changed here, non of which I mention are optimisation however. Your solution is almost identical to the example on the wiki page where you can see hardware optimisations if supported, though the example does not apply to JavaScript.

Naming

The Str in resultStr seems to imply that it's a string but that's not the case. result may be better suited, or val which is a common choice for this.

While count is perfectly fine, distance might make it's purpose more obvious (especially since "distance" is in the function name).

Parentheses

There's a bunch of parentheses that aren't needed, adding spacing around operators makes it easier to follow.

Shorthand operators/spacing

You can take advantage of shorthand operators:

resultStr = resultStr & resultStr - 1 can be simplified to resultStr &= resultStr - 1

Another added benefit is that in this example we don't have to worry about operator precedence.

ES6

Since you're using ES6 features such as let you can take advantage additional features such as const and => (arrow functions).

ES6 - const/let

Favour let and const over var. You are already declaring count with let so it would make sense to do the same for resultStr.

If we declare const hammingDistance = ... it means that if we later try and reassign hammingDistance = ... we will get a TypeError.

I recommend using const whenever you don't need to reassign a variable. Note this does not mean the variable is immutable, just that it cannot be reassigned.

ES6 - arrow functions

I've opted to use arrow function notation over traditional syntax here. Your example does not benefit from any of the advantages such as lexical this so feel free to change back to function(x, y) as this is a personal choice.

Solution

Here's your code with the suggested changes:

const hammingDistance = (x, y) => {
  let val = x ^ y;
  let distance = 0;

  while (val > 0) {
    val &= val - 1;
    distance++;
  }

  return distance;
};

For loop solution

If you wanted, you could replace the while loop with a for loop as follows:

const hammingDistance = (x, y) => {
  let val = x ^ y;

  let distance;
  for (distance = 0; val > 0; distance++) {
    val &= val - 1;
  }

  return distance;
};


Unit Test case to check if localstorage is empty once I logout of the Web app

If you are using any I/O (in this case, local storage), you must have fallen into an integration test.

A unit test could be that when logout is executed, the call to
clearing the local storage is made (using an spy on localStorage).
An integration test could be that you have data in the local storage and after you have logged out, you don't.


Version of lexical_cast that doesn't use exceptions

Since you have an already working lexical cast. Why not just wrap that?

namespace MyStuff
{
    template<typename T1, typename T2>
    T1 lexical_cast(T2 const& value, T1 const& defaultValue = T1{})
    {
        try
        {
            return boost::lexical_cast<T1,T2>(value);
        }
        catch(...) // Ignore all exceptions and use default.
        {
            return defaultValue;
        }
    }
}

The reason I would not advocate writing your own is the actually complicity of all the edge cases. Though your code embodies what is happening the actual code has not reflected this in a long time (you have basically written the deprecated version of boost::lexical cast).

Also the boost version has a whole bunch of special case optimizations.


Well, for purpose of what you are trying to do I would say just CSS could do it.

Using the :focus selector and combining with a span element like this:

input:focus + span:after {
    content: 'Focused!';
}

/* just polishing the looks from here on */
button {
 display: block;
}
span {
  margin: 0 10px;
}

    <input type="text">
    <button type="submit">Submit</button>

About your JavaScript optimization question two things strikes me:

don't define functions inside loops if you don't need to.
I don't see why to use the setTimeout. Is there any browser mixing up the order of the events?

So a suggestion, without the function declaration inside the loop, using a closure and .toggle() instead of a ternary for add/remove:

const rootElement = document.getElementById('my-root-element');
((rootElement, children) => {
    const update = () => {
        rootElement.classList.toggle('focused', children.indexOf(document.activeElement) !== -1);
    };
    children.forEach(el => {
        ['focus', 'blur'].forEach((eventName) => {
            el.addEventListener(eventName, update);
        });
    });
})(rootElement, [...rootElement.children]);


Arabic to Greek numeral converter, 1 - 10

Reviewing your current structure: your return ""; could be improved: it should / could be inside the switch statement as a default case.

It's better to use an object here, as later you can extend it without having to spend pointless LoCs on cases and breaking.

function arabicToGreek(input) {
    'use strict';
    var greek = {
        1: "α",
        2: "β",
        3: "γ",
        4: "δ",
        5: "ε",
        6: "ϝ",
        7: "ζ",
        8: "η",
        9: "θ",
        10: "ι"
    };
    //
}

Then, add greek.hasOwnProperty to check that your string is a valid object property, in which case that it isn't, you can throw an error.

if (!greek.hasOwnProperty(input)){
    throw new Error("input not a valid integer representing a character");
}

This also means you can store the greek characters and potentially other languages in an external JSON document.


Automated batch and python skeleton script file creation

This is rather good code: no blatant style issues, doctrings for functions and some comments (albeit some are unnecessary). Well done.

Now for the critics:

traditional shebang would rather look like #!/usr/bin/python3 or #!/usr/bin/env python3;
the comments you put between the shebang and the imports should be the module docstring instead;
use 4 spaces per indentation level rather than tabs;
since you are creating files in the current working directory, you can check for file existence with the filename only; thus you can do it early and generate an argparse error instead of "rolling your own" ;
you could make the path to idle an optional parameter of the CLI instead of hardcoding your path to it;
I like to use the file argument of the print function to visualize the layout of the output file better. But for the python template, using a multiline string should be an improvement:

#!/usr/bin/env python3

"""Takes a command line filename and creates a batch file and .py file
named "filename" in the cwd. The python file contains a basic script
framework. In additon, the python file will be automatically opened.
"""

import argparse
import os
import subprocess

PYTHON_TEMPLATE = '''\
#!/usr/bin/env python3

"""DOCSTRING"""

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s")

def main():
    pass

if __name__ == "__main__" :
    main()'''

def handle_input():
    """Parses user commandline input"""

    parser = argparse.ArgumentParser()
    parser.add_argument(
            'filename',
            help='The name of the files to '
                 'create minus any extensions.')
    parser.add_argument(
            '-i', '--idle-path',
            help='The path to the IDLE executable',
            default=r'C:\Users\Dave\AppData\Local\Programs'
                    r'\Python\Python35-32\Lib\idlelib\idle.bat')
    args = parser.parse_args()

    filename = args.filename
    # ensure an existing python file is not overwritten
    if os.path.exists(filename+'.py'):
        parser.error('file already exist: {}.py'.format(filename))
    return filename, args.idle_path

def make_batch(filename: str, cwd: str):
    """Makes a batch file name "filename" in "cwd"""

    filepath = os.path.join(cwd, filename + ".bat")
    with open(filepath, "w") as f:
        print('@py.exe', os.path.join(cwd, filename+'.py'), '%*', file=f)
        print('@pause', file=f)
    print('Created batch file:', filepath)

def make_py(filepath: str):
    """Makes a .py file in cwd written with a basic skelton script"""

    # *****I realize it's a simpler task to copy a template from a .
    # py file created for the purpose and write that to the new .py*****

    with open(filepath, "w") as f:
        print(PYTHON_TEMPLATE, file=f)
    print('Created .py file:', filepath)

def open_py_idle(filename: str, idle_path: str):
    """Opens a .py file in IDLE using subprocess"""

    subprocess.run([idle_path, filename], shell=True)

def main():
    """Creates .bat and .py file in cwd. Auto opens .py file"""

    filename, idle_path = handle_input()
    cwd = os.getcwd()
    python_file = os.path.join(cwd, filename + '.py')

    make_batch(filename, cwd)
    make_py(python_file)
    open_py_idle(python_file, idle_path)

    print('\n*****Done*****\n')

if __name__ == "__main__":
    main()


In Python, the standard approach is EAFP: it's Easier to Ask Forgiveness than Permission. So this:

response = raw_input(question)
try:
    return int(response)
except ValueError:
    print("\nInvalid input! Input must be an integer")

is definitely the way to go.

We can even go one step further. Regardless of which python version it is, we're running the same logic. The only difference is which input function to use. So let's just extract that logic outside of the loop so we don't have duplication of effort:

def valid_int(question):
    """Creates a loop until an integer is entered"""
    input_func = input if find_version() == 3 else raw_input

    while True:
        response = input_func(question)
        try:
            return int(response)
        except ValueError:
            print("\nInvalid input! Input must be an integer")


Simple implementation of LRU caching in PHP

This implementation is quite simple. I compared it with some others in PHP as well as other languages like C++, Java and JavaScript. Some use a node class to store a key and value separately (e.g. this PHP implementation) but for a simple implementation your approach seems fine.

I noticed that the method isFull() only explicitly returns a value when true is returned. While it works because the conditional that calls that method would this implicitly evaluate the empty return to a false-y  value, some would argue that methods that return a value should do so in every case, for the sake of readability. That could be achieved by simply returning the conditional:

private function isFull()
{
    return count($this->cache) >= $this->size);
}

And one other simplification would be to set the property/instance variable $cache to an empty array when it is declared, since it can be evaluated at compile time and does not depend on any run-time information to be evaluated, instead of inside the constructor:

private $cache = [];


struct.unpack on a bytearray that works under Python 2.6.6, 2.7 and 3.3?

Why not just call bytes?

number = struct.unpack('<I', bytes(buf))[0]

In Python 2.6:

Python 2.6.8 (unknown, Aug 13 2012, 22:19:05)
...
>>> import struct
>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))
(1145258561,)

In Python 3.3:

Python 3.3.2 (default, May 21 2013, 11:50:47)
...
>>> import struct
>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))
(1145258561,)


Python list comparison: Can this code run faster?

So it seems you primarily want to use your callback functions to pull the value to compare out of an object, if you don't mind simplifying how compared items are returned, a faster and simpler approach would be:

def simple_compare(li1, li2, value_func1=None, value_func2=None):
        s1, s2 = set(map(value_func1, li1)), set(map(value_func2, li2))
        common = s1.intersection(s2)
        s1_diff, s2_diff = s1.difference(s2), s2.difference(s1)
        return common, s1_diff, s2_diff

>>> simple_compare(li1, li2, value_func1=f)
<<< (set([1, 3]), set([2]), set([5]))

>>> compare_lists(li1, li2, value_func1=f)
<<< (([{'v': 1}, {'v': 3}], [1, 3]), [{'v': 2}], [5])

Which depending on actual use case, might be something you could live with. It's definitely a lot faster:

>>> timeit x = simple_compare(xrange(10000), xrange(10000))
100 loops, best of 3: 2.3 ms per loop

>>> timeit x = compare_lists(xrange(10000), xrange(10000))
10 loops, best of 3: 53.1 ms per loop


Your code is repeating a little bit. For example,

ax[0].plot(x, sine)
ax[0].set_title('Sine wave')

ax[1].plot(x, cosine)
ax[1].set_title('Cosine wave')

ax[2].plot(x, superposition)
ax[2].set_title('Bichromatic wave')

This can be rewritten using a helper function (or alternatively a for-loop), which may look something like this:

def plot_subroutine(axis, xdata, ydata, title):
    axis.plot(xdata, ydata)
    axis.set_title(title)

y1 = ... # sine
y2 = ... # cosine
y3 = ... # bichromatic
yn = (y1, y2, y3)

title1 = 'Sine Wave'
title2 = 'Cosine Wave'
title3 = 'Bichromatic Wave'
titles = (title1, title2, title3)

fig, ax = plt.subplots(3,1)

Then instead of calling each plot subroutine individually (as below)

plot_subroutine(ax[0], x, yn[0])
plot_subroutine(ax[1], x, yn[1])
plot_subroutine(ax[2], x, yn[2])

You can instead do something like

if len(ax) == len(yn):
    for i in range(len(ax)):
        plot_subroutine(ax[i], x, yn[i])
plt.show()

The for-loop has the advantage that you can later change the number of output plots without changing too much of your original code (if say, you wanted to output 2 or 4 plots, or perhaps change the ydata to something entirely different).

This may or may not be relevant, but it may be nice to associate each individual plot with a specific legend label, marker style, and/or color, all of which can be handled using matplotlib. This can be especially useful for overlayed plots (especially considering that your data consists of sin(x) and cos(x) over the same x-interval.


$(function() {

    var togglePlusMin = function(clicker, img) {
        $(clicker).toggle(function() {
            $(img).attr("src", "minus.png");
        }, function() {
            $(img).attr("src", "plus.png");
        });
    };

    // can be used by
    togglePlusMin('#togglemass', '#plusmass');

    // BONUS: this will also work:
    var star = $('#togglestar'),
        starIcon = $('img.plusstar');

    togglePlusMin(star, starIcon);
})

As a comment, its generally a bad idea to use ids without a second context parameter


3.x Compatibility

If you want to make this compatible with Python 3.x, you'd have to do a few things. First off, in Python 3.x, Tkinter has been renamed to tkinter, so at the top of your file you might want to do something like this:

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

You should also use parentheses in print, like this:

print( ... )

Style and other nitpicks

Generally, you shouldn't be using wildcard imports like this:

from Tkinter import *

If you don't like prefixing everything with Tkinter, you can just do this:

import Tkinter as tk

Rather than importing multiple modules on the same line, like this:

import sys, os

It's better to import them all on separate lines, like this:

import sys
import os

It's also very bad practice to have a bare except clause, like this:

try:
    ...
except:
    ...

Any program error that you don't want to catch will go un-noticed . This is not good. You should be doing something like this instead:

try:
    ...
except TheErrorYouWantToCatch:
    ...

You should also have two blank lines between functions, not one, like this:

def a():
    ...

def b():
    ...

On the note of functions, you should also have docstrings describing the purpose of your functions. A typical docstring looks something like this:

def my_function( ... ):
    """Brief description.

    More detailed description.

    Description of arguments.
    """
    ...

Your naming is also, not the greatest. For example, I'd rename the following variables:

file_input to input_file_path.
_FILE_ to file_contents.


This is not O(n log n) algorithm, because this part is quadratic:

  for (var i = 0; i < firstArray.length; i++) {
    for (var j = 0; j < secondArray.length; j++) {
      if (firstArray[i] + secondArray[j] == k) {
        count += 2
      }
    }
  }

Denoting n = input.length, this has roughly (n/2)^2 = n^2/4 steps, which is O(n^2).

The rest of this answer is a result of a misread and is not directly related to the question. I'll leave it as a comment of a possibly extended exercise.

However, I'm not sure that O(n log n) algorithm does exist. Consider

a = [ 1, 2, 4, 8, ..., 2^n ] (for some n)

and k is a sum of all elements in a. Since you can repeat the numbers, and a[k] = 2*a[k-1] for all positive k, you'd have exponential number of sums, so no O(n log n) algorithm will solve this.

It is easy to show that the number of solutions is strictly bigger than 2^n. Just note that

k = (sum of ANY elements in a except a[0] = 1) + (sum of the remaining elements in a) * 1.

The first sum can be chosen in 2^n ways. Of course, there are other sums as well, but this is enough to show that you can have an exponential number of solutions, which is enough to show that no sub-exponential algorithm can find them all.

Of course, there may be a mathematical trick to compute only how many such solutions there are, but I don't know it.


Yes, there are some issues.

With process (clk, divfactor) you're making it difficult for the synthesis software to generate a nice clocked process. So you should separate the clocked process from the clock multiplexer.

A bigger problem is the clock multiplexer. divfactor is — even if it is synchronous — a 16-bit value, for which all bits have to be checked for 0. This introduces quite some logic, which will always be glitchy... and you're putting it directly into your clock output. danger! danger! A glitchy clock results in undefined behavior... it can even lock your FSMs to an unresolvable state.

Instead check the condition in a clocked process and set a single synchronous output based on its value.

This is how I would write something like this:

library ieee;
use ieee.std_logic_1164.all;

entity config_clk_div is
    port (
        clk : in std_logic;
        divfactor : in std_logic_vector (15 downto 0); -- Note this is actually not a factor!
        clkout : out std_logic);
end entity;

architecture rtl of config_clk_div is
    use ieee.numeric_std.all;
    signal clk_counter : unsigned(15 downto 0) := (others => '0');
    signal div_clk : std_logic := '1';

    signal divider_disabled : std_logic := '0';
begin
    process (clk)
    begin
        if rising_edge(clk) then
            if divfactor = x"0000" then
                divider_disabled <= '1';
            else
                divider_disabled <= '0';
                if clk_counter = 0 then
                    clk_counter <= unsigned(divfactor) - 1;
                    div_clk <= not div_clk;
                else
                    clk_counter <= clk_counter - 1;
                end if;
            end if;
        end if;
    end process;

    clkout <= clk when divider_disabled = '1' else div_clk;
end architecture;

Note: counting down on a counter makes the compare (to 0) a bit easier. Although this makes more of a difference when designing ASICs.


Textual representation of a C++ function

I would clean this up by bringing what you can to the top level (hiding it using a module export list if need be) as new functions. There are also some sectioning/alias changes that I think would make it more readable.

toLowerIfPolymorphic :: [(Concept, Identifier)] -> Identifier -> Identifier
toLowerIfPolymorphic templateArgs argName
    | lcArg `elem` (snd $ unzip templateArgs) = lcArg
    | otherwise                               = argName
  where
    lcArg = strToLower argName

I often prefer guards to if _ then _ else _, it helps cut down on word soup (and I still don't understand why we don't have boolCase :: Bool -> a -> a -> a in the Prelude). Consider how snd . unzip more specifically captures your intent than using a more powerful but generic higher-order function like map.

The bit with ["Any", "typename", "class"] should work out better with some reordering. Instead of applying a partial transformation with a sentinel value (i.e. filter (not . null) with occasional "" values), drop the junk and then transform the good stuff.

showConstraints :: [(Concept, Identifier)] -> [String]
showConstraints templateArgs = map display . filter valid $ templateArgs
  where
    display (concept, ident) = concept ++ " " ++ strToLower ident
    valid (concept, _) = concept `notElem` ["Any", "typename", "class"]

Then your Show instance ends up looking something like this.

instance Show Function where
  show (Function templateArgs returnT fName fArgs)
     = fName
    ++ " :: ("
    ++ intercalate ", " (showConstraints templateArgs)
    ++ ") => "
    ++ intercalate " -> " (map (toLowerIfPolymorphic templateArgs . show . fst) $ fArgs)
    ++ (if null fArgs then "" else " -> ")
    ++ toLowerIfPolymorphic templateArgs (show returnT)

I'd probably take this one step further though to handle not having any constraints (in which case you don't want "() =>" to show up, presumably) and write one more helper function.

wrap :: String -> String -> String -> String
wrap _     ""      _   = ""
wrap start content end = start ++ content ++ end

Giving—

instance Show Function where
  show (Function templateArgs returnT fName fArgs)
      =  fName
      ++ " :: "
      ++ wrap "(" (intercalate ", "   $ showConstraints templateArgs)       ") => "
      ++ wrap ""  (intercalate " -> " $ map (lowerPoly . show . fst) fArgs) " -> "
      ++ lowerPoly (show returnT)
    where
      lowerPoly = toLowerIfPolymorphic templateArgs


Bash script to encode images in base64 and generate a CSS file from them

cd "${BASH_SOURCE%/*}"

: > "$css_path"

What happens if  cd fails?  Nothing good.  Make a habit of always, always testing the result of cd (and synonyms like pushd) for failure.   Bash's -e switch will promote all error exits to fatal script errors; a less extreme approach is simply:

cd … || exit 1

if [[ -z "$unsupported" && -z "$invalid_class_name" ]]

This is testing the first elements of these two arrays for zero length.  You want to test the lengths of the arrays instead.

When testing for zero, the use of arithmetic (( … )) is a nice touch: it returns truth for non-zero and false for zero.

When a conditional includes an else block, avoid negating the condition.  In other words: prefer if x then yes else no  over if not x then no else yes.

 if (( ${#unsupported[@]} || ${#invalid_class_name[@]} ))

filename="$(name_ext="${file##*/}"; echo "${name_ext%.*}")"
ext="${file##*.}"

This is awkward.  Most of the fault rests with Bash itself.  A regular expression is a little cleaner:

[[ $file =~ ([^/]*)\.([^.]*)$ ]] && filename=${BASH_REMATCH[1]} ext=${BASH_REMATCH[2]}

if [[ "$mime" = "unsupported" ]]; then

Quotes aren't needed around variables (or literal strings that lack whitespace) inside [[ … ]].

  printf ".%s::before { background-image: url(data:%s;base64,%s); }\n" \
  "$filename" "$mime" "$base64str" \
  >> "$css_path"

It's good practice to indent continuations.  In the specific case of printf, it can be helpful to align variables with their format-string placeholders.

unsupported+=("$file")

invalid_class_name+=("$file")

If these exist in the shell that invokes your script, their initial values will persist and muck things up.  Make a habit of zeroing variables you intend to append to (or increment, etc.).  At the same time, improve readability by expressly declaring your arrays as such:

declare -a unsupported=() invalid_class_name=()

: > "$css_path"

This could be annoying if the script fails.  Consider taking a backup of the output file before zeroing it, and restoring the backup on error exit.


Your entities have a dependency to a connection object that's somehow available to them. If this is one instance you may experience technical impediments when reading entities and their nested entities in one statement. But that's not the most important thing.

The most important objection is that these "active" navigation properties will always give rise to the n + 1 problem: for each item you pull from the database by 1 query, you will trigger n queries to get their related data. That will certainly affect performance and it depends on the amount of data whether that's serious.

This effect is aggravated by the fact that the data aren't stored into the parent entities: each time a navigation property is accessed the query is executed.

There are more things to consider when it comes to reproducing Entity-Framework's (EF) behavior regarding navigation properties. EF loads entities into a context, which implements Identity Map: i.e. each database record will be represented by exactly one C# object. The benefits of this are hard to reproduce:

If one entity is modified, the changes are reflected wherever the entity is referenced. Also, changes are unambiguous: there are no "equal" entities around having old values. (You're probably getting read-only data, so this may not affect you).
Ability to perform operations that are based on referential equality. For example, in your case, grouping Resources by Language will produce groups having 1 item, because the language object aren't equal (sure, can be evaded by using LanguageId, but still, it's a gotcha).
EF can perform relationship fixup when it loads entities: loading Resources and Languages separately into one context will auto-populate the navigation properties. Your code won't ever do that.

Side note: Dapper's Multi Mapping Feature won't alleviate the first two points because it also creates separate object instances for "equal" entities.

So all in all, I wouldn't do this. I would get the data separately and perform some sort of "relationship fixup" manually.


I wrote the modified version of your findpath function using recursion:

(defn- dfs
  [graph goal]
  (fn search
    [path visited]
    (let [current (peek path)]
      (if (= goal current)
        [path]
        (->> current graph keys
             (remove visited)
             (mapcat #(search (conj path %) (conj visited %))))))))

(defn findpath
  "Returns a lazy sequence of all directed paths from start to goal
  within graph."
  [graph start goal]
  ((dfs graph goal) [start] #{start}))

Instead of using your hasloop? function,
my search function keeps track of visited nodes
in order to avoid visiting the same node twice.
It seems to work for your settings:

user> (def graph
  {:s {:a 3 :d 4}
   :a {:s 3 :d 5 :b 4}
   :b {:a 4 :e 5 :c 4}
   :c {:b 4}
   :d {:s 4 :a 5 :e 2}
   :e {:d 2 :b 5 :f 4}
   :f {:e 4 :g 1}})
user> (findpath graph :s :g)
([:s :a :b :e :f :g] [:s :a :d :e :f :g] [:s :d :a :b :e :f :g] [:s :d :e :f :g])


As you say, the requirements are, let's say, unconventional.  But in some ways, that's good preparation for crazy requirements you'll get in working life!  Except that as a student, you might not get to ask the "five whys" to determine whether the requirements are actually grounded, and to get them changed.
There are still some clarifications of the requirements:

Should only regular files be archived, or should we include directories and devices, too?
Should the archive contain full pathnames of the contained files, or relative names, or just basenames?  If only basenames, then how should we deal with conflicts?
Should the destination directory be created if it doesn't already exist?

As this is a homework assignment, you may not be in a position to ask these questions - in that case, you should assume a position and state it clearly in your answer.  If possible, localise the effects of a wrong assumption, to make it easy to change when you get more information (again, that's a good reflection of working life).

Working through the code from the beginning:
list_begin=1 # where the filetype arguments begins
list_end=$ # where the filetype arguments end

target_directory=$(pwd)
destination_directory=$(pwd)

It looks like you can save two invocations of pwd by using . as the default directory name - you never need an absolute path.
A more common approach is to remove option arguments using shift as they are parsed; then all of $* are your inputs.  I'm assuming $  there is a typo for $#?
Here's the outline:
while test -n "${1+:}"
do
    case "$1" in
        -t|--target)
            target="$2"
            shift 2
            ;;
        -d|--destination)
            destination="$2"
            shift 2
            ;;
        *)
            process_file "$1"
            shift
            ;;
    esac
done

I've included long-name alternatives just to show how it's done, not because that's a requirement.  This approach allows the user to specify -t and -d more than once, to change those settings during a run.  It's not clear whether you are required to enforce the ordering constraints you were given, or if that's just limiting the problem space to make it easier.  If the former, you can just process them in turn:
if [ "-t" = "$1" ]
then
    target="$2"
    shift 2
fi
if [ "-d" = "$1" ]
then
    destination="$2"
    shift 2
fi

and so on.
I've also fixed the quoting above - you'll find that if you miss it out, then people will want at target or destination with whitespace in the name!

# confirm directories are real
if [[ ! -d "${target_directory}" ]]; then # invalid -t
    echo "backup: \"${target_directory}\" is not valid"
    exit
elif [[ ! -d "${destination_directory}" ]]; then # invalid -d
    echo "backup: \"${destination_directory}\" is not valid"
    exit
fi

You don't need to use Bash [[ here - it's more portable to stick to plain old [ (aka test).  You'll want your error messages to go to the error stream (>&2), and you'll want to exit with a non-zero value, so that anything executing your program will know it didn't succeed.  I like to define a small function to do that:
die() {
    echo "$@" >&2
    exit 1
}

Then I can write:
test -d "$target_directory" || die "$0: $target_directory is not a directory"
test -r "$target_directory" && test -x "$target_directory" || die "$0: $target_directory cannot be read"
test -d "$destination_directory" || die "$0: $destination_directory is not a directory"
test -w "$destination_directory" || die "$0: $destination_directory is not writable"

declare -a filetypes # array to store filetypes

for ((i=${list_begin}, j=0; i<=${list_end}; i++, j++)); do # fetch all filetype arguments and add to array
    eval dir=\${$i}
    filetypes[${j}]=${dir}
done

I don't think it's necessary to do all this copying.  You can simply process each argument as you come to it.

for i in "${filetypes[@]}"; do # for each filetype
    f_list="${target_directory}/*.${i}" # directory to iterate through

You shouldn't be quoting the * there, because you want the shell to expand it.  If you expand it later, you may well end up splitting $i.

My version
#!/bin/sh
set -e

die() {
    echo "$@" >&2
    exit 1
}

process_suffix() {
    for file in "${source-.}"/*."$1"
    do
        # Warning: may overwrite existing archive
        test -e "$file" \
             && tar cfz "${destination:-.}/${file##*/}.tar.gz" -C "${source-.}" -- "${file#${source-.}/}"
    done
    echo "$0: finished *.$1 files"
}

while test -n "${1+:}"
do
    case "$1" in
        -t|--source)
            test -d "$2" || die "$0: $2 is not a directory"
            test -r "$2" && test -x "$2" || die "$0: $2 cannot be read"
            source="$2"
            shift 2
            ;;
        -d|--destination)
            test -d "$2" || die "$0: $2 is not a directory"
            test -w "$2" || die "$0: $2 is not writable"
            destination="$2"
            shift 2
            ;;
        *)
            process_suffix "$1"
            shift
            ;;
    esac
done

echo "$0: files saved to $destination"

Additional notes:

Everything is now POSIX shell, so we can use /bin/sh which may be faster, more available, etc (bash, ksh, dash etc. are all sufficiently POSIX-compliant).
I've given -- to tar to indicate that subsequent arguments are filenames, even if they begin with -.
I default uninitialised source and destination directories - see the Parameter Expansion section of the shell man page.
Archive filenames are all relative to the source directory.
I use "$0" in messages to show the actual name the program was invoked as.
Test cases should include file and directory names containing spaces or beginning with - (that's a good general rule for testing shell scripts).
Remember that (by default) a non-matching glob is treated literally.  So if there are no matching files, we'll want to ignore *.suffix when archiving (but still archive a file that really does have * in the name).


Count the number of cyclic words in an input

There's one trick which you can use to get a reduction in memory usage which is very worthwhile if the strings are long. String.substring returns a new String object but wrapping the same underlying char[] as the original. So your code:

        for (int i = 0; i < s.length(); i++) {
            permutation = s.substring(1) + s.substring(0, 1);
            s = permutation;
            hashSet.add(s);
        }

could be replaced with

        String dbl = s + s;
        for (int i = 0; i < s.length(); i++) {
            hashSet.add(dbl.substring(i, i + s.length()));
        }

and will contain the same strings but only store 2 * s.length() characters rather than s.length() * s.length().

The next trick to consider using would be a CharSequence implementation which wraps the original string and an offset for the starting character.

Finally, you could consider normalising each cyclic word. Given the s.length() possible rotations, choose the lexicographically smallest and insert only that one into the set. Whether this gives an efficiency improvement will depend on the statistics of the strings, but if they're random and of a length comparable to the size of the alphabet then a naïve algorithm for finding the smallest will be essentially linear, and you gain two things: firstly, the set becomes smaller (less memory usage, faster lookups); and secondly, you can drop count because the number of cyclic words will be just the size of the set.


In all the test that could be an error. Do you really want to continue if there is an error?
Seems counterproductive to generate an error message and continue running. That will just generate more spurious errors.

if(hSerial==INVALID_HANDLE_VALUE)
{
    throw std::runtime_error("Insert error message");
}

Then just wrap your code in a try catch block:

try
{
    ... Code here
}
catch(std::exception const& e)
{
    std::cerr << "Exception: " << e.what() << "\n";
    throw; // re-throw so the OS can provide help if available.
}
catch(...)
{
    std::cerr << "Exception: Unknown ...\n";
    throw;
}


C++11 class similar to .Net's ManualResetEvent, but without the ability to "reset"

Looks good.

The only thing I would change is:

volatile bool _state;

into

 std::atomic<bool>  _state;

The issue with volatile is that it does not universally provide that guarantee that updates are visible to all threads (which std::atomic does).

Could simplify the wait() call.

    while (!_state) {
        _underlying.wait(lock);
    }

    // could be:
    _underlying.wait(lock,[&state](){return state;});

Personally I don't like prefix '_' on identifiers. The rules for using '_' as a prefix are complicated. Even if you know the rules not everybody that reads your code will.


Transforming a stl vector according to its neighbors

What you have is probably good enough. If you want to try something crazy, you could always do:

boost::range::transform(boost::irange(0, N), block.begin(), [&](const int i){
    int pre = i-1 >= 0 ? state[i-1] : 1;
    int post = i+1 < N ? state[i+1] : 1;
    return pre * state[i] * post;
});

Not sure I prefer that to the simple loop that you have, but just throwing it out as a potential alternative.


I don't see any reason to use Base and Derived classes in your case. At least with the context you've provided.

public class TimerTask
{
    private readonly Timer _taskTimer;

    public TimerTask(Action action, int interval = 10000)
    {
        _taskTimer = new Timer { AutoReset = true, Interval = interval };
        _taskTimer.Elapsed += (_, __) => action();
    }

    public void Start() { _taskTimer.Start(); }

    public void Stop() { _taskTimer.Stop(); }
}

Usage:

void Main()
{
    var t1 = new TimerTask(() => Console.WriteLine("t1"), 100);
    t1.Start();
    Thread.Sleep(1000);
    t1.Stop();
}

System.Timers.Timer is thread-safe, but you have to make sure that your code is thread-safe.


Include what you use

We use std::abs and std::vector but the code lacks the necessary includes:

#include <cmath>
#include <vector>

Perform a single task well

Why do we perform the Gaussian blur?  What if the input is already sufficiently blurred, or if it needs a bigger kernel?

If we make the caller responsible for this preparation step, we give it more control, and we can focus on a single responsibility in this function.

Fix the memory leak

This allocation is never released:

dirImg = new unsigned char[grey.cols*grey.rows];

In fact, this entire (global) array seems only to be assigned to, and never used, so we could remove it entirely.

Simplified indexing

It might be easier to use index throughout, and add rows or columns directly with ±grey.cols and ±1:

      const int index = i*grey.cols + j;
      int com1 = smoothImg[index + grey.cols + 1] - smoothImg[index - grey.cols - 1];
      int com2 = smoothImg[index - grey.cols + 1] - smoothImg[index + grey.cols - 1];
      int gx = std::abs(com1 + com2
                        + smoothImg[index + 1] - smoothImg[index + 1]);
      int gy = std::abs(com1 - com2
                        + smoothImg[index + grey.cols] - smoothImg[index - grey.cols]);

Use the standard library

There's no need to (badly) re-write std::hypot() for the computation of sum (also, drop the if (0) - that's always false).

      const int sum = std::hypot(gx, gy);

Saturate, don't overflow

The std::hypot() value could conceivably be larger than the range of int, or of gradImg[] (depending on the relative sizes of the target's integer types) - in such cases, we should std::clamp the value to the possible range, rather than suffering Undefined Behaviour.

Spelling

Prefer standard spelling: gradient, not gradiant.