This problem intrigued me, and it has aspects which relate to a real-world problem I am working on. Performance is a significant concern of mine, and reviewing your code, and the current answer by wassgren (+1), I suspect there's a better way to do it.

In both of your cases, you break the title down to words, and then build up the words in ways to see if they match tags. This creates a challenge which scales badly (I believe the solutions are about \$O(n t^2)\$ (n the size of the title, t the number of tags), and will have poor performance for reasonably sized titles, or tag sets.

A better way would be to only 'split' the title on the tag boundaries... locate each tag inside the title, and, if it is there, identify that location, then look in the next spots.

Still, this requires matching many tags, against many places in the title, which then becomes an order of \$O(nt)\$

Regular expressions, though, are able to significantly improve that by using Automata to match the text. A single regular expression on the title will approach \$O(n)\$ performance, and not significantly depend on the number of tags.

Thus, by building a complex regular expression, you can reduce the algorithmic complexity substantially. So, a regular expression like china man|beijing bell will match the first of those tags in the title.

Regular expressions can also work on word-boundaries, and be case insensitive. Thus, there is no need to do any splitting of the input, and conversion to lower-case....

Because regular expressions have structured orders of evaluation, we can build up a regex that encompasses all the required tags.

There are thus two parts... given a regular expression that matches all the tags, your code becomes simply:

    List<String> result = new ArrayList<>();
    Matcher mat = **SOME_PATTERN**.matcher(text);
    int lastPos = 0;
    while (mat.find()) {
        addNotEmpty(text, lastPos, mat.start(), result);
        result.add(mat.group());
        lastPos = mat.end();
    }
    addNotEmpty(text, lastPos, text.length(), result);

    return result.toArray(new String[result.size()]);

The code to build the regular expression is just a clever way of "orring" the tags:

    List<String> quoted = sources.stream().map(tag -> "\\b" + Pattern.quote(tag) + "\\b")
            .collect(Collectors.toList());
    String pat = String.join("|", quoted);

    return new CompiledTagSet(Pattern.compile(pat, Pattern.CASE_INSENSITIVE), sources.toString());

Note, you look for word boundaries on the tag, and 'quote' it so that any tags containing special regex characters are not going to break things.... Then you concatenate them with the regex 'or' character |.

Finally, you compile it to be case-insensitive.

Putting this all together, you can have a system like:

package tagger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class TagSplitter {

    public static final class CompiledTagSet {
        private final Pattern pattern;
        private final String sources;

        private CompiledTagSet(Pattern pattern, String sources) {
            this.pattern = pattern;
            this.sources = sources;
        }

        private Pattern getPatterns() {
            return pattern;
        }

        @Override
        public String toString() {
            return sources;
        }

    }

    public static final CompiledTagSet compileTags(Collection<String> tags) {
        // strip out duplicate, empty, and null tags.
        List<String> sources = tags.stream()
                .filter(tag -> tag != null)
                .map(tag -> tag.trim())
                .filter(tag -> !tag.isEmpty())
                .distinct()
                .collect(Collectors.toList());

        // THIS IS CRITICAL
        /*
         * Sort the 'tags' in reverse order alphabetically. The reason is as follows:
         * If one tag is a prefix of another, like "bobby" and "bobby tables", then we
         * want our regex to match "bobby tables" if it exists, and not just "bobby".
         * Add another tag "tables", and we have three: "bobby", "bobby tables" and
         * "tables". If we were to match the text:
         *     I am bobby tables
         * we want the match to be "bobby tables", and not "bobby" and "tables"
         * Java regular expressions are "alternate ordered" which means, if you have
         * OR conditions in the regex, the first one (left most) that matches, wins.
         * So, if we have the regular expression "bobby|bobby tables|tables" and match
         * that against "I am bobby tables", it will match "bobby" first.
         *
         *  The regular expression "bobby tables|bobby|tables", on the other hand, will
         *  match "bobby tables" first.
         *
         *  By sorting the tags in reverse order, longer tags will happen first.
         *
         *  I believe this will also make track-back mechanisms faster in the automaton
         *  if closely related tags are closer together.
         */
        sources.sort(Comparator.reverseOrder());

        List<String> quoted = sources.stream().map(tag -> "\\b" + Pattern.quote(tag) + "\\b").collect(Collectors.toList());
        String pat = String.join("|", quoted);

        return new CompiledTagSet(Pattern.compile(pat, Pattern.CASE_INSENSITIVE), sources.toString());
    }

    private static final void addNotEmpty(String text, int left, int right, List<String> target) {
        if (right <= left) {
            return;
        }
        String candidate = text.substring(left, right).trim();
        if (candidate.isEmpty()) {
            return;
        }
        target.add(candidate);
    }

    public static String[] splitByTags(final String text, final CompiledTagSet tags) {

        List<String> result = new ArrayList<>();
        Matcher mat = tags.getPatterns().matcher(text);
        int lastPos = 0;
        while (mat.find()) {
            addNotEmpty(text, lastPos, mat.start(), result);
            result.add(mat.group());
            lastPos = mat.end();
        }
        addNotEmpty(text, lastPos, text.length(), result);

        return result.toArray(new String[result.size()]);

    }

    public static String[] splitByTags(final String text, String...tags) {
        // filter and process the tags.
        // remove null values, duplicates, empty strings, etc.
        return splitByTags(text, compileTags(Arrays.asList(tags)));
    }

    public static void main(String[] args) {
        String[][] tagSets = {
                {"china man", "beijing bell", "man eater"}

        };
        String[] inputs = {"China man eater Japan Beijing bell"};

        List<CompiledTagSet> compiled = Arrays.stream(tagSets).map(tags -> compileTags(Arrays.asList(tags))).collect(Collectors.toList());

        for (String input : inputs) {
            for (CompiledTagSet ts : compiled) {
                System.out.printf("Split: %s%nUsing: %s%nMatch: %s",
                        input, ts, Arrays.toString(splitByTags(input, ts)));
            }
        }

    }
}

Note that there is special handling for situations where one tag is a prefix of another tag.

The above code produces the output:

Split: China man eater Japan Beijing bell
Using: [man eater, china man, beijing bell]
Match: [China man, eater Japan, Beijing bell]


The Ackermann function is not designed to be efficient... ;-) It is designed to be a counter-proof to a theoretical construct.

But, the reality is that the BigInteger is required. The conditions are required.

About the only things I can suggest are:

use better names
return-early logic
the ans variable is unnecessary
always use braces for conditional blocks.
BigInteger.ONE is already defined, you have used it in some places already, no need for BigInteger.valueOf(1)
call it ackermann not ack

I would have:

public static BigInteger ackermann(BigInteger a, BigInteger b) {
    if (a.equals(BigInteger.ZERO)) {
        return b.add(BigInteger.ONE);
    }
    if (b.equals(BigInteger.ZERO)) {
        return ackermann(a.subtract(BigInteger.ONE),BigInteger.ONE);
    }
    return ackermann(a.subtract(BigInteger.ONE), ackermann(a, b.subtract(BigInteger.ONE)));
}


Pandas iteration over rows for features calculation

Just some stylistic suggestions

Constants

Constants in your program should be UPPERCASE. (PEP 8)

bins -> BINS
short_window -> SHORT_WINDOW
long_window -> LONG_WINDOW
price -> PRICE

Docstrings

You can add docstrings to your functions to allow more description about the function and
about the parameters it accepts and the value(s) it returns, if any. (PEP 8)

def vap(row, df, short_window, long_window, bins):
    """
    Description Here

    :param row: Description Here
    :param df: Description Here
    :param short_window: Description Here
    :param long_window: Description Here
    :param bins: Description Here

    :return: Description Here
    """

Type Hints

You can add type hints to your functions to show what types of parameters are accepted, and what
types are returned.

You can also use typing's NewVar to create custom types to return.

from typing import List

PandasTimeStamp = NewType("PandasTimeStamp", pd._libs.tslibs.timestamps.Timestamp)

def vap(row: int, df: pd.DataFrame, short_window: int, long_window: int, bins: int) -> List, PandasTimeStamp:
    ...


tmp.update({k:v}) is an unusual way to perform tmp[k] = v
Take advantage of the max builtin:

max_len = max(len(v) for v in dic.values() if isinstance(v, list))

To make the code easier to follow, you could first transform the dictionary to give it a consistent structure like this

{'k1': ['v1', 'v1', 'v1', 'v1'],
 'k2': ['v2', 'v2', 'v2', 'v2'],
 'k3a': [21, 23],
 'k3b': [22, 24],
 'k4': [1, 2, 3, 4]}

using code like this

mapped = collections.OrderedDict()
for key, value in dic.items():
    if key in mapping:
        for sublist in value:
            for subkey, subvalue in sublist:
                mapped.setdefault(subkey, []).append(subvalue)
    elif isinstance(value, list):
        mapped[key] = value
    else:
        mapped[key] = max_len * [value]

Then you can take advantage of itertools.zip_longest to produce the output:

with open("out.csv", "w", newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(list(mapped.keys()))
    writer.writerows(itertools.zip_longest(*mapped.values(), fillvalue=''))


Unique letter counter for string in Python

Is the global variable necessary?

No. Global variables are almost never necessary, and rarely the best solution. Consider this:

def merge_count(s, com_dict):
    if len(s) == 1:
        if s[0] in com_dict:
            com_dict[s[0]] += 1
        else:
            com_dict[s[0]] = 1
    else:
        merge_count(s[:int(len(s)/2)], com_dict)
        merge_count(s[int(len(s)/2):], com_dict)

def main():
    s = "Hello there this is the string"

    new_s = ""
    for i in s:
        if i != " ":
            new_s += i
    new_s = new_s.lower()

    com_dict = {}
    merge_count(new_s, com_dict)
    for i in com_dict:
        print i, com_dict[i]

main()

In this, you pass a dictionary to merge into into to the function.

You do

new_s = ""
for i in s:
    if i != " ":
        new_s += i

Addition of strings in loops is always almost bad, because it may reallocate the string on every addition. Instead, one should do a join:

new_s = "".join(i for i in s if i != " ")

However, in this case you might as well just do

new_s = s.replace(" ", "")

Recursively splitting in merge_count is pointless. Just do

def merge_count(s, com_dict):
    for i in s:
        if s in com_dict:
            com_dict[s[0]] += 1
        else:
            com_dict[s[0]] = 1

which affords the better interface of

def merge_count(s):
    com_dict = {}

    for i in s:
        if s in com_dict:
            com_dict[i] += 1
        else:
            com_dict[i] = 1

    return com_dict

One can simplify things with defaultdict:

from collections import defaultdict

def merge_count(s):
    com_dict = defaultdict(int)

    for i in s:
        com_dict[i] += 1

    return com_dict

Or even further with Counter:

from collections import Counter

def merge_count(s):
    return Counter(s)

Instead of

for i in com_dict:
    print i, com_dict[i]

One should do

for i, v in com_dict.iteritems():
    print i, v

Then one fixes up the naming

from collections import Counter

def main():
    string = "Hello there this is the string"

    lower_chars = string.replace(" ", "").lower()
    char_counts = Counter(lower_chars)

    for char, count in char_counts.items():
        print(char, count)

main()


Priority in pair inside priority_queue on basis of both elements

This test is wrong:

return a.first > b.first && a.second<b.second;

Try:

return a.first > b.first || (a.first == b.first && a.second < b.second)

Some other things

This is not a legal header

#include<bits/stdc++.h>

Remove this immediately your code is invalid with it there.

Never do this:

using namespace std;

Its a bad habit that will cause you problems in real code. Always pre-fix things from the standard library with std:: (Its short for a reason).

see: https://stackoverflow.com/q/1452721/14065

Use menaingful variable names.

Names like i n m have no meaning. Also when you have longer code searching the source for them will turn up a lot of false negatives thus making it harder to keep your code working.

Prefer prefix ++ over the postfix version.

    for(int i=0;i<n;i++)

    for(int loop = 0; loop < inputElementCount; ++loop)

A bit of white space makes things easier to read.

        cin>>a>>b;

        // Why not
        std::cin >> value1 >> value2;

When poping from a queue you should check its not empty not assume it has a particular size:

for(;!queue.empty(); queue.pop())
{
    auto const& item = queue.top();
    std::cout << item.first << " " << item.second << "\n";
}


This caught my eye:

    if (!IsInitialized)
        throw new NotImplementedException("Config data has not get been implemented.");

A NotImplementedException is usually a kind of "meta" exception that you typically find in unimplemented method stubs, e.g.

public string GetConfigElement(string key)
{
    throw new NotImplementedException();
}

It's basically ilke a "todo" marker that [intentionally] blows up at runtime:

  You might choose to throw a NotImplementedException exception in properties or methods in your own types when the that member is still in development and will only later be implemented in production code. In other words, a NotImplementedException exception should be synonymous with "still in development."

  MSDN

Throwing that exception as part of the implementation of a method is confusing; in this case the goal is to tell the caller that the current state of the object does not allow using this method yet.

In other words it should be an InvalidOperationException:

  The exception that is thrown when a method call is invalid for the object's current state.

See the remarks section on MSDN for more guidelines on throwing that specific exception.

I find the constructor is doing too many things:

var foo = new ConfigManager(path);

With this single instruction, I've just hit the file system, read the contents of some file, and cached a number of configuration settings in an encapsulated dictionary.

The problem is, if I wanted to write a unit test to document how the GetConfigElement works (and then another to document how it fails), I couldn't, because my test would depend on file I/O.

I'd suggest moving that logic out of the constructor, and delay doing that work.

It would be nice to include an indexer, so client code could do this:

var foo = new ConfigManager(path);
var port = foo["port"];

That said you're reinventing the wheel here, if this is production code you should probably be using the framework-provided XML configuration, using the System.Configuration namespace; you could store your connection strings in a dedicated <ConnectionStrings> section.


DRY code for sending email with SendGrid

Since the code that actually sends the email is the same and only the objects are different, then you can abstract out the sendgrid.send() into a function say sendEmail() that accepts an Object as a parameter since that's what the abstract code does, that's for readability.  In the callback function in sendgrid.send() ... you already have a return so anything after that doesn't get executed so don't need the else.

Declare the object for both alert and confirmation first. req.body is repeated in 3 places to declare that too.

Finally, invoke the function sendEmail with twice with each of the objects declared.

var body = req.body,
    alertObject = {
        to: "my@email.com",
        from: "myother@email.com",
        subject: "[ALERT] " + body.eventDate,
        html: "SOME HTML"
    },
    confirmationObject = {
        to: body.email,
        from: "my@email.com",
        subject: "[CONFIRM] register" + body.eventDate,
        html: "SOME HTML"
    };

function sendEmail (emailObject) {
    if (emailObject) {
        sendgrid.send(emailObject, function (err, json) {
            if (err) {
                return console.error(err);
            }
            next();
        });
    }
}

sendEmail(alertObject);
sendEmail(confirmationObject);


Applying a JOIN sounds pretty easy

SELECT article1, article2, size, order_date, SUM(quantity)
FROM orders
INNER JOIN customers ON orders.order_no = customers.order_no
WHERE customers.customer_no = '1027'
GROUP BY article1, article2, size, order_date, SUM(quantity)

You should note that nested SELECT statements in a WHERE clause almost always lead to bad performance.

Also that kind of unnormalized data model looks weird, but there may be good reasons why to keep order_no and customer_no pairs in a single association table. May be its just bad naming, something like customers_orders might probably have been a better choice.


At the end of the day I used pandas.
df = pandas.read_sql_query("""My join query""")

This all just solved my problem.


General

Your code style is neat. I like that you are using System.out.printf instead of concatenating strings. You should consider using %n instead of \nin the format because it is platform independent.
Math.abs() - Math.abs() is a core function that you should use instead of doing it yourself.
Growing the tStevil array - you do this manually, and you increase and decrease the size often. This can be inefficient. It may be better to keep a big-enough version, and have a separate int tStevillength variable to keep track of how much is actually populated.
This code here:

    for (int i = 0; i < tStevil.length - 1; i = i+2){
        if (i == 0){
            System.out.printf("(%.2f, %.2f)",tStevil[i],tStevil[i+1]);
        }
        else{
            System.out.printf(", (%.2f, %.2f)",tStevil[i],tStevil[i+1]);
        }
    }

would be better done with less code repeated:

for (int i = 0; i < tStevil.length - 1; i = i+2){
    if (i > 0){
        System.out.print(", ");
    }
    System.out.printf("(%.2f, %.2f)",tStevil[i],tStevil[i+1]);
}

Algorithm.

Your algorithm is close to what I would have done. The only difference is that I would keep an array of indexes of the first member of a temperature pair....

Also, sometimes it is easier to loop from i = 1, instead of looping to i < length - 1

My code would look something like:

int pairlen = 0;
int[] pairs = new int[stevila.length];
double maxdiff = Double.MIN_VALUE;
for (int i = 1; i < stevila.length; i++) {
    double diff = Math.abs(stevila[i] - stevila[i - 1]);
    if (diff > maxdiff) {
        maxdiff = diff;
        pairlen = 0;
    }
    if (diff == maxdiff) {
        pairs[pairlen++] = [i - 1];
    }
}

This way, at the end of the loop, you have the index to the first pair of pairlen indexes for values with the largest diff.

You can then loop through that list using for (i = 0; i < pairlen; i++) { .... } and pull the actual values back from the stevila array.

This is not actually very different fdrom the way you have done it, but it is a bit neater.

Nice job.


A simple encryption program using Python

I think it's a nice project. I would say that the main things for you to work on is getting further acquainted with Python's standard library and with standard practices, which is what most of my advice will be surrounding.

Minor improvements

For your alphabet, you could use ascii_lowercase from string, i.e.:

from string import ascii_lowercase
alphabet = [character for character in ascii_lowercase]

Unless I'm misreading, your function position() looks like an attempt at recreating list.index(value) (or in your case source.index(tofind)).

"Unneeded" variables can sometimes make sense if they improve readability, but your function:

def converttolist(text):
    size = len(text)
    l = []
    for i in range(0,size,1):
        l.append(text[i])
    return l

would be just as readable if written as:

def converttolist(text):
    l = []
    for i in range(0,len(text),1):
        l.append(text[i])
    return l

and while we're on that particular function, I would strongly recommend having a look at list comprehension---it's both faster and cleaner. Your function would then become:

def convert_to_list(text: str) -> list:
    return [text[i] for i in range(len(txt)]

but I should add that, for cases like this, even better is to just use in-line built-ins like str.split() or [character for character in text].

You don't need to write str(input(<whatever>)) since input already returns a string.

The function range() defaults to step-size 1, so writing range(start, end, 1) is unnecessary.

I would also recommend using a main function for your main loop. You could move all of the stuff in the bottom into a if __name__ == "__main__":, which also would allow you to load in this python script into other programs.

Naming

Remember that Readability counts. The standard in python is to use snake_case for variable names, but more importantly ensure that your names make the variables' purpose clear; avoid names like x and sizea.


Thread-safety and delegates with generated numbers

There is no synchronisation here and so all access to the thread's state is subject to data races. It is comprehensively not threadsafe.

From what I can tell all you need is to implement a producer/consumer pattern. Do this with a blocking queue. Please don't use busy loops. They burn CPU cycles and are horribly non-performant.


Fill a vector with uniformly distributed random complex numbers

The problem with this is that it leaks memory, although not in the traditional sense of leaking.

Function static variables live till the end of the program. So while generator and distribution are only created when this code is first run, they only get destroyed at the end of your program even though you never use them later. This eats up memory the entire time.

On the other hand, the amount of memory it eats up is pretty small and constant, so for almost all purposes, it shouldn't make too big of a difference. Even if you repeatedly called a function that had this code in it, the static variable would live and not be recreated. Just don't use this in a way that generates the lambda 100s of times, such as in intense template metaprogramming.

In C++17, if you were using this to initialize a big enough vector, you could make use of execution policies to parallelize this like so:

std::generate(std::execution::par_unseq, inputData.begin(), inputData.end(), []()-> Complex {
    thread_local std::default_random_engine generator; // thread_local so we don't have to do any locking
    thread_local std::normal_distribution<double> distribution(0.0, 0.5); // mean = 0.0, stddev = 0.5
    return Complex(distribution(generator), distribution(generator));
});

This has the added benefit that these variables will be destructed when the threads used finish, although when that happens is mostly unclear.


Overall, pretty good code.  There are a couple things I would personally change though.

1 - I'd start by qualifying the references to Cells and Range even if it's assumed that everything is done with the same sheet - I'd grab a reference to ActiveSheet right at the start and use that throughout. Using a Worksheet reference inside a With block is much faster than using the global objects. Outside of the performance, it's generally a good habit to get into as it avoids using an implicit reference.

2 - The call to calculate the size of the array is a bit of overkill - there really isn't a need for a function call with:

size = WorksheetFunction.Count(Range(Cells(2, 2), Cells(lastRow, lastColumn)))

You already have all the information you need to calculate it with a simple multiplication:

size = (lastRow - 1) * (lastColumn - 1)

Excel is almost certainly doing more work to count it, because a Range object doesn't have to be rectangular.

3 - You write your array by setting the .Value of the target Range to the array, but your reads are still done inside of a loop.  Not only that, but you read the same value (Cells(i, j)) from the worksheet twice here:

If Not IsEmpty(Cells(i, j)) Then
arrayOfBids(counter, 1) = Cells(i, j)

Remember, Cells(r, c) is a function call (2 actually - see #1) so you should be caching the result if the return value isn't going to change between the calls. I'd read the source Range into an array also and then iterate over that.

4 - While I'm on that section of code, the block enclosed by...

If Not IsEmpty(Cells(i, j)) Then
'...
End If

...should be indented another level.

5 - IsEmpty probably isn't the best choice (see this review) - you really just need to test that the cell isn't equal to vbNullString. Or if a zero bid is invalid, test that the cell isn't equal to 0.

6 - temporaryArray is basically being used as a tuple to store the swap values in your BubbleSort implementation.  However, when you store them in an array you carry a bunch of SafeArray overhead along with it, especially since it's curiously a two dimensional array with the first dimension fixed at 1 element. A one dimensional array would be better (the runtime performs a multiply internally every time you address a cell in a 2D array). Even better would be to create a simple type to store them in:

Private Type Tuple
    ItemOne As Variant
    ItemTwo As Variant
End Type

7 - One small advantage that a bubble sort has is that it sorts the array in place.  But..., your implementation takes the array ByVal and then just returns a copy of the sorted array when it's done. This is a huge performance hit that negates the advantage of an in-place sort. Think of it in terms of memory copies.  The call sortedBids = BubbleSort(arrayOfBids) creates a copy of sortedBids in memory and then passes it to BubbleSort. The BubbleSort function then sorts the copy in place. But the copy is just a locally scoped variable, so finally you call BubbleSort = arrayOfBids which copies it again and puts it on the stack as the return value.  Take advantage of possible the sole benefit of your algorithm and convert BubbleSort to a Sub that takes the array ByRef.

8 - Your counter i should be declared as a Long in BubbleSort.  I'd actually consider this a bug, because the variables you use to size the array you pass it are Long. Speaking of which, you also need overflow protection in GetBids(). WorksheetFunction.Count returns a Double which it has to because the total number of possible cells in a Range is 17,179,869,184 (the maximum possible return value in your code is 17,178,804,225). This will easily overflow a Long.  Granted, you won't be able to write the results if it overflows (and I shudder to think of the execution time for a bubble sort with 1,048,575 elements), but a graceful exit would be nicer than an unhandled exception.

9 - The return value of UBound(arrayOfBids) will never change inside your Do loop in BubbleSort. This value should also be cached outside of the loop - there isn't a need for repeated function calls to determine what is essentially a static value.

10 - You should swap the order of your data collection loops. Based on the sample data, the values on each row should always be increasing from left to right. This indicates that the final placement of an element in the sorted output is more strongly correlated by which column it's in instead of which row it's in. But when you're building the arrayOfBids that is eventually going to be sorted, you're building it in row order then column order.  While this doesn't make as much of a difference with a bubble sort as it would with other sort algorithms, you are basically ensuring that your input to the sort will be closer to the worst case than it will to the best case.  If you switch the loop order to this...

For j = 2 To lastColumn
    For i = 2 To lastRow
    Next
Next

...you are using this characteristic of your typical data set to make sure your sort input is closer to best case.


Optimizing "complex" iteration over Map with auxiliary maps

Just some points:

I don't see the initialization of choiceCaseAliases,casePaths, or entry. If they are class variables, that's fine, as long as it is meant to be a class variable. If they are outside the method just so that another method can set the values and have the current method run, then it is not okay. If they are class variable just for the method, have them as method arguments.
Here:

    for (String casePath: casePaths) {

and here:

            for (String pathKey: paths.keySet()) {

You don't follow Java conventions. There should be a space before and after the ::

    for (String casePath : casePaths) {

and:

            for (String pathKey : paths.keySet()) {

I wouldn't create a new temporary map for each loop. Instead, I would create one outside the loop, and dump the contents of the temporary map into the map at the end:

private Map<String, String> resolveChoicePaths() {
    String path;
    Map<String, String> tmp = new LinkedHashMap<>();
    for (String casePath : casePaths) {
        String choiceCase = casePath.replaceFirst(".*/([^/]+/)", "$1") + "/";
        boolean mapModified = false;
        for (Iterator entries = choiceCaseAliases.entrySet().iterator(); entries.hasNext();) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries.next();
            if (entry.getKey().contains(choiceCase)) {
                path = entry.getKey().replace(choiceCase, StringUtils.EMPTY);
                tmp.put(path, entry.getValue());
                entries.remove();
                mapModified = true;
            }
        }
        if (!mapModified) {
            for (String pathKey : paths.keySet()) {
                if (pathKey.contains(choiceCase)) {
                    path = pathKey.replace(choiceCase, StringUtils.EMPTY);
                    tmp.put(path, pathKey);
                }
            }
        }
    }
    choiceCaseAliases.putAll(tmp);
    return choiceCaseAliases;
}


Building a chain of responsibility in Ruby to apply transformators on an object

I'm concerned by the interplay between the two middlewares. Why is PlusOneMiddleware.apply responsible for calling the next middleware?

It breaks the sequence implicit in the stack being a stack. In effect, the payload passes through DummyMiddleware before PlusOneMiddleware although they've been stacked in the opposite order.

It also requires PlusOneMiddleware to know that there is a "next" middleware. But why should it know or care?

I'd expect the stack to be responsible to for calling the middlewares in sequence, and the middlewares being ignorant of each other. E.g.

class MiddlewareStack
  def self.apply payload
    middlewares.reduce(payload) do |payload, middleware|
      middleware.apply(payload, self)
    end
  end
end

Your tests are misleading too. You have a spec that says

  MiddlewareStack: When we apply the middleware stack it call [sic] all the middlewares

But "it" - the middleware stack - doesn't actually do that. It only happens because the PlusOneMiddleware calls .next on the stack. Which, again, shouldn't be its responsibility. If you reverse the order of middlewares, only one gets called. If you only add the PlusOneMiddleware you get NoMethodError: undefined method ‘apply’ for nil:NilClass because @middlewares.shift returns nil.

In other words, you specs will break if you do this:

class PlusOneStack < MiddlewareStack
  stack ::DummyMiddleware
  stack ::PlusOneMiddleware # doesn't get called
end

or this:

class PlusOneStack < MiddlewareStack
  stack ::PlusOneMiddleware # raises NoMethodError on nil
end

which sort of negates the entire idea of a flexible stack of arbitrary middlewares.

Similarly, I should be able to do this:

class PlusOneStack < MiddlewareStack
  stack ::PlusOneMiddleware
  stack ::DummyMiddleware
  stack ::AnotherMiddleware
end

But AnotherMiddleware will never be called, which doesn't really make sense: It's in the stack, right?

There's also the use of shift in MiddleWareStack. Especially as the stack's not an instance, it's strange to see the @middlewares array being manipulated when the stack is "run". Doubly so since .next can be called from the middlewares themselves.

Other small stuff:

You set a default value for @middlewares in .stack, but you should probably be doing that in your .middlewares accessor method. And you should then use said accessor in your other methods. For instance, if you never add any middleware at all, .apply will fail, since @middlewares is nil.
However, you may not want to expose a @middlewares accessor to the world, as anyone can then mess with it. So beware.
Take a cue from Rack, and name the main middleware method call. That way, you can use plain procs and lambdas as middleware in addition to custom classes and objects. And you may want to check for that with respond_to? when stacking middlewares.

A brutally simple implementation might simply look like:

class MiddlewareStack
  class << self
    def use middleware # same method name as Rack
      raise ArgumentError unless middleware.respond_to?(:call)
      stack << middleware
    end

    def apply payload
      stack.reduce(payload) do |payload, middleware|
        middleware.call payload
      end
    end

    private

    def stack
      @stack ||= []
    end
  end
end

Edit: After the reading the comments, something like this might be a more fitting solution. Where a stack/middleware construction would require an agreed-upon API between stack and middlewares, this is more of a linked-list construction, where there no central "stack", and the agreed-upon API is instead between the members of the linked-list. Note that this is just a quickly-written example

class ExampleLinkedHandler
  def initialize(name)
    @name = name
  end

  def append(handler)
    if @next
      @next.append(handler)
    else
      @next = handler
    end
  end

  def call(level = 0)
    if @next
      "#{@name} (level #{level}) <- #{@next.call(level + 1)}"
    else
      "#{@name} (level #{level})"
    end
  end
end

chain = ExampleLinkedHandler.new("head")

chain.append(ExampleLinkedHandler.new("1st"))
chain.append(ExampleLinkedHandler.new("2nd"))
chain.append(ExampleLinkedHandler.new("tail"))

puts chain.call(0) # prints "head (level 0) <- 1st (level 1) <- 2nd (level 2) <- tail (level 3)"

You can of course have any kind of derived or duck-typed classes/objects as longs as they respond to append and call in a similar manner.


First step - make your current code better

Instead of a char array you might prefer to use a String.
This would make the declaration easier:

String text = "EmyiythTribbianni";

I would say that most of us generally recommend that you shouldn't omit brackets.
You should also follow a consistent bracket pattern.

I recommend for every statment to be in a different line from your brackets.
This means that things like {break;} are not really that good.

Closing brackets should also be matching the same identation of the statment they were open.
By this I mean

ìf(condition){
    //code goes here
    for(declaration; evaluation; increment){
        //code goes here
    }//closing bracket with the same indentation as the previous for statmeent
    //code goes here
}//closing bracket with the same indentation as the previous if statement

You should also follow a consistent spacing and let prefer more space than less.

This int count =0; becomes int count = 0;
This for(int i=0;i<length;i++) becomes for(int i = 0; i < length; i++)
This if(j>=length) becomes if(j >= length)

I think you get the ideia. Every time you find a comparison, assignment, +, -, or ; (on for) you space it.

Your code would then become something like this

String text = "EmyiythTribbianni";
int count = 0;
int length = text.length;
int icnt = 0;
for(int i = 0; i < length; i++){
    if(i == 0){
        System.out.println(text[0]);
    }else{
        if(count + 1 >= length){
            break;
        }else{
            for(int j = count + 1; j < i + 2 + count; j++){
                icnt++;
                if(j >= length){
                    break;
                }else{
                    System.out.print(text[j]);
                }
            }
            count = count + icnt;
            icnt = 0;
        }
        System.out.println();
    }
}

Second step - taking a different approach

It seems that you want to put according to the number of character that you had printed so far.
I reckon that the arithmetic progression sum formula n(a1 + an) / 2 would be useful here.

The first time you print 1 character making the first term a1 = 1. Then you print a space.
The second time you print 2 characters a2 = 2, the total of characters print to this time is 2 * (1 + 2) / 2 = 3.
And so on.

By applying this idea you would get something along this lines:

String text = "EmyiythTribbianni";
int n = 1;

for(int i = 0; i < length; i++){
    int sum = n  * (1 + n) / 2;
    if(i != sum){
        System.out.print(text[i]);
    }else{
        System.out.print(" ");
        System.out.print(text[i]);
        ++n;
    }
}


Comment on the style of this C++ class for a 2D Vector

This looks pretty good! I don't think you need to change much, but there are some things missing that you will likely need:

normalize() or normal() method to either normalize a vector or return a normalized version of the vector. If you're doing physics, you'll need normalized vectors for lots of operations, probably.
Scalar multiply (operator*(const T)). You'll likely need to scale vectors frequently and will do that by multiplying by a scalar.
operator==() and/or operator!=(). You should define one in terms of the other.
Possibly a squared magnitude. Sometimes taking the square root in the Magnitude() function is a bottleneck and you don't need it (for example to see if a point is within a given radius of another point). It can be faster to get the squared magnitude of the vector between the two points if that's something you do a lot.


You can also use Array.prototype.reduce to generate the fixed size 2d array.

const input = [{
  id: 123, quantity: 4, value: "x1xxx"
}, {
  id: 234, quantity: 11, value: "x2xxx"
}, {
  id: 345, quantity: 1, value: "x3xxx"
}];

function getNewRecords(rowSize = 4) {
  return input.reduce((records, current) => {
    let items = [];
    Array.from({
      length: current.quantity + 1 // +1 for header column
    }).forEach((_, index) => {
      const record = {
        header: index === 0,
        id: current.id,
        quantity: current.quantity,
        value: current.value
      }

      if (items.length === rowSize) {
        records.push({ items, rowSize });

        items = [];
      }

      items.push(record);
    });

    if (items.length < rowSize) {
      items.push(...Array(rowSize - items.length).fill(null));
    }

    records.push({ items, rowSize });

    return records;

  }, []);
}

console.log(getNewRecords());


Don't do this yourself. Instead use java.net.URLEncoder or another library implementation of url encoding. You'll also get support for other characters as well besides space.


The relation hasMany required a correspondent field in the target table.

I guess in your case you want manyToMany relationship, you are currently using oneToMany.

Be careful about the grammar, an Article belongsToMany Tags, not an Article hasMany Tags.

After re-coding your relationships with belongsToMany method you can simply bind your articles and tags within a pivot table that contains both the article_id and tag_id.

As an example I would recommend having a look at a package in GitHub.
You should also have a look at this for raw information about Many to Many relationships in Laravel.

When it comes to the query you send via Laravel's Query\Builder;

You can start trying it with an Eloquent\Builder

Article::join('tags', 'articles.id', '=', 'tags.article_id')
    ->where('articles.lang', '=', 'ru')
    ->where('tags.category', '=', $category)
    ->get([
        'articles.*',
        'tags.category'
    ]);

If the select at the end confuses you, you can also use the select method on the Query\Builder to specify the columns you want.

Article::select([
        'articles.*',
        'tags.category'
    ])
    // You could also give each element of this array
    // as a parameter to the `select` method
    // It would look like this:
    //      select('articles.*', 'tags.category')
    ->join('tags', 'articles.id', '=', 'tags.article_id')
    ->where('articles.lang', '=', 'ru')
    ->where('tags.category', '=', $category)
    ->get();


Parallel processing in different directories in Perl

I'll do a first pass where I point out syntax and Perl conventions, mostly line by line. I will then talk about alternative strategies to make it more efficient and maintainable.

Syntax

use strict; use warnings; use Cwd;

You have use strict and use warnings. Well done!

You would typically have one use or require statement per line. That way, it's easier to read them.

You import getcwd from Cwd. It's a good practice to never have default imports, but to either specifically import the stuff you want, or not to import any names at all. This way, you don't pollute your namespace (even though you are in main implicitly), and later you know where functions in your code came from.

use strict;
use warnings;
use Cwd 'getcwd';

open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";

You are using three-argument open and lexical filehandles. That's great. Those tutorials are paying off.

die "$message\n";

If you include a trailing newline "\n" in your message to die, it will not tell you what line it died on. You are mixing both versions. I think you should stick with the line numbers. Get rid of those newline, and remember that it's important to be consistent in programming.

sub run_parallel {
    my $command_array_reference = shift;

I guess you read somewhere that variable names should be speaking. Or maybe you don't want to get confused about the kind of data this variable holds. Speaking names are great. But you don't really need to name your variable foo_array_reference. The fact that its sigil is a $ already tells you it's a scalar, and thus likely a reference. A better name would be $commands, where the plural indicates it's a list of some kind. If you want to write down that it's an array, write a comment or some POD over the function.

=head2 run_parallel

Takes an array reference of commands, spawns four workers to work through
all the commands in parallel and returns the return
value of C<$manager->wait_all_children>.

=cut

sub run_parallel {
    my $commands = shift;

As you can see from my documentation, we have another issue coming up.

unless ((ref $command_array_reference) =~ m/ARRAY/) {
    print "run_parallel requires an array reference as input.\n";
    die;
}

There is a bit too much stuff here. You don't need a regular expression match to check the ref. It will return "ARRAY", so you could say:

ref $commands eq 'ARRAY'

However, that will give a use of unitialized value warning if we pass a string or a number, or something else that is not a reference. If you really want to check this, and don't want to write

unless ( ref $commands and ref $commands eq 'ARRAY') { ... }

you should take a look at Ref::Util, which provides a lot of useful functions to check this kind of thing in a very fast way, as it's written in XS. In your case, you could use is_arrayref.

If you insist on dieing, then do it properly. Don't print to STDOUT and then die without a message, so that it just says Died at line ... to STDERR. die can take an error message, but shouldn't have the newline \n, or it will not report the line number.

You can then use a nice post-fix unless.

use strict;
# ...
use Ref::Util 'is_arrayref';

sub run_parallel {
    # ...

    die 'run_parallel requires an array reference as input'
        unless is_array($commands);

use Parallel::ForkManager;
my $manager = new Parallel::ForkManager(4);

When Perl executes your program, there are two phases. It first reads the whole thing and compiles it. This phase is called compile time. Then it actually runs the program, which is called run time. use statements are resolved during compile time. That means it doesn't matter if they are inside a sub, or an if. They will always be found and executed. Conditional use statements are a code smell. Put the use at the top with the others.

The old-fashioned new Module(@args) form (called indirect object notation) has been out of date for a long time. Instead, you should use the more modern version, which will take care of inheritance properly.

my $manager = Parallel::ForkManager(4);

my $START_DIRECTORY = getcwd();

ALL_CAPS variable names usually indicate constants in Perl. Your variable is lexical. Name it $start_directory instead.

You don't have to do the parenthesis after a function call if Perl knows it's a function (it was imported from Cwd, so it knows that). It's ok to do them, but it's important to be consistent if you do, and have them all the time. You do that, so this is fine.

foreach my $command (0..scalar @{ $command_array_reference }-1) {
    # ...
    my ($dir, $cmd) = @{ $command_array_reference->[$command] };
    # ...
}

You are making your life harder than you have to here. Using a range and foreach is bettern than a C-style for loop, but it's not the easiest choice in this situation.

I would iterate the array reference directly. Instead of calling it in scalar context, just walk over its elements. The dereferencing operator @{} returns a list of all of them if you put it directly into the parens. This will make it easier to grab the two elements and might have saved you the question over on Stack Overflow.

foreach my $command (@{ $commands }) {
    # ...
    my ($dir, $cmd) = @{ $command };
    # ...
}

By the way, if you have a Perl that's at least version 5.24 you can use the post-fix dereferencing operator. It's easier to read because you can go left to right all the way, but if you're used to the old stuff (like me) it's hard to get used to it. Also, my commercial Perl IDE doesn't highlight it yet.

foreach my $command ( $commands->@* ) {
    my ($dir, $cmd) = $command->@*;
}

my @commands;

$commands[0][0] = 'tmp1';#directory
$commands[0][1] = 'echo "ave Maria" > aveMaria.txt';#command

$commands[1][0] = 'tmp2';#directory
$commands[1][1] = 'echo "IN HOC SIGNO VINCES" > xp.txt';#command

You can write these kinds of structures the same way Data::Dumper outputs them. That makes it easier to read.

my @commands = (
    [
        'tmp1', # directory
        'echo "ave Maria" > aveMaria.txt', # command
    ],
    [
        'tmp2', # directory
        'echo "IN HOC SIGNO VINCES" > xp.txt', # command
    ],
);

Also note that there is a convention to have space in front and after the # for comments, as that makes it easier to read.

In general, I prefer to use references directly when I know I'll take a reference of the variable. Especially for configuration. And since you never actually do anything else with @commands, there is no need to create it in the first place.

run_parallel(
    [
        [
            'tmp1',                               # directory
            'echo "ave Maria" > aveMaria.txt',    #command
        ],
        [
            'tmp2',                                   # directory
            'echo "IN HOC SIGNO VINCES" > xp.txt',    #command
        ],
    ]
);

Maintainability

You have some code duplication in the signal handler and execute. Opening and writing the file is implemented twice, with only the same error message being different. It would be nicer to write a function that does all of that, and pass it the message. You can then use that function in the signal handler as well as execute.

There is also no need to explicitly close, as $fh is lexical and will be cleaned up automatically when it goes out of scope, or in this case, the program ends.

sub log_error_and_die {
    my $error = shift;

    my $fail_filename = "$TOP_DIRECTORY/$0.FAIL";
    open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";
    print $fh $error;

    die $error;
}

And you can call it like this

# kill the program if there are any warnings
local $SIG{__WARN__} = sub {
    my $message = shift;
    log_error_and_die( sprintf( '%s @ %s', $message, getcwd() ) );
};

and

sub execute {
    my $command = shift;
    print "Executing Command: $command\n";
    if (system($command) != 0) {
         log_error_and_die("$command failed.");
    }
}

Why are there always four jobs? If there are a lot of files, wouldn't it be easier to make this an option? Especially with your limited input data, four jobs are overkill. But they might be not enough.

I would add a second argument to run_parallel and pass the number of parallel jobs.

sub run_parallel {
    my ($commands, $jobs) = @_; # alternate way to get arguments
    # ...

    my $manager = Parallel::ForkManager($jobs);
}

Of course, since there is nothing else, you can also get rid of that function all together. If you only ever call it once from the body of your script, I believe there's no need to make it into a function. Opinions vary on this, though.

Other considerations

    chdir $dir or die "Can't chdir to $dir: $!";
    execute( $cmd );
    chdir $START_DIRECTORY or die "Can't chdir to $START_DIRECTORY: $!";

Why do you chdir before calling execute? Is that not part of the execution? I think I would move that into execute.

Furthermore, why do you chdir back afterwards? That's already the working directory of the child, which will be reaped a few lines down. At that point, its working directory doesn't matter, and it will never have any influence on the parent's or the sibblings' working directory. You can safely remove that second chdir.

Once you've done that, you can pass $command along to execute and have a cleaner interface.

$commands[0][0] = 'tmp1';#directory
$commands[0][1] = 'echo "ave Maria" > aveMaria.txt';#command

The inner data structure of your commands could be a hash reference as well. That would make it a bit more work to write it all down, but you would not need those comments any more, and it will be way easier to read half a year later.

my $commands = [
    {
        dir => 'tmp1',
        cmd => 'echo "ave Maria" > aveMaria.txt',
    },
    # ...
];

Then to work with it in your loop, you don't have to assign $dir and $cmd any more.

sub execute {
    my $command = shift;
    chdir $command->{dir}
        or die "Can't chdir to $command->{dir}: $!";

    print "Executing Command: $command->{cmd}\n";
    if (system($command->{cmd}) != 0) {
         log_error_and_die("$command->{cmd} failed.");
    }
}

# ...

foreach my $command (@{ $commands }) {
    $manager->start and next;
    execute($command);
    $manager->finish;
}

Instead of all the die calls you can use the autodie pragma, which will turn all failures into die. It can make the code a lot more readable.

use autodie 'all'; # includes system()

Instead of the signal handler, you can set all warnings to be FATAL on the warnigns pragma.

use warnings FATAL => 'all'; # every warning dies


Python coding style from Java background

Unlike in Java, not everything in Python needs to be a class. In Python we tend to reserve classes for representing things with individual state and common behaviour. If you just want to group some functions together, you can put them in a module.
You have no documentation. What do these functions do and how am I supposed to call them? In Python you should give every public class, function and method a docstring.
Why do you try importing simplejson? This is just the externally maintained version of the built-in json module. You don't seem to use any simplejson-specific feature, so what's the point?
Your code is not portable to Python 3, but this would be easy to fix by putting parentheses around the arguments to print.
This code:

#Check user exists
if user.json()['Data'] is None:
    return None

#Return user
return user.json()['Data']

can be simplified to:

return user.json()['Data']

You have code like this:

VARIABLE = requests.METHOD(api_root + '/accounts/' + account_id + STUFF, headers=self.headers)
VARIABLE.raise_for_status()

in three places. You should make this a function.
It's not clear what the point of this line is:

user_id = str(user_id)

All you ever do with user_id is add it to strings, where it will be converted to a string in any case.
I prefer to use str.format to build up strings, rather than +: the former tends to result in clearer code. For example:

api_root + "/accounts/" + account_id + "/users/" + user_id

would become:

'{}/accounts/{}/users/{}'.format(api_root, account_id, user_id)

Comment on updated question

You have failed to avoid the duplicated code: you have just moved it around.


Is this the right way to use TcpListener in the background?

Your code looks OK, though I think there is some redundant code - e.Result = clientSocket; is never used, since work is never completed...

You might also want to consider a different approach to BackgroundWorker - TcpListener.AcceptTcpClientAsync. Instead of creating a worker thread you can do this:

private Task<TcpClient> listen() {

   return _serverSocket.AcceptTcpClientAsync().ContinueWith(clientSocket => {
       _launcher.NotifyFormNewTcpClient(clientSocket);
       MessageBox.Show("new TcpClient Connected...");
       return listen();
   });


For starter, you don't need to use a global index. Python tuples make it easy to return several values at once, you can return the new index with the deserialized value:

    @staticmethod
    def deserialize(source):
        def _helper(index):
            if source[index] == '#':
                return None, index + 1

            value = source[index]
            left, index = _helper(index + 1)
            right, index = _helper(index)
            return Node(value, left, right), index
        return _helper(0)[0]

Now, what if I what to serialize the node Node('#', None, None)? I will get ['#', '#', '#'] as output that will get deserialized as None. Not that ideal. If you want to keep this intermediate format, you should at least allow the user to chose its sentinel value. Using a parameter with a default value in both serialize and `deserialize is a good option.

I would also improve the interface of your class: turning serialize into a method and deserialize into a classmethod. This allow for ease of use and easy subclassing:

class Node(object):
    ...

    def serialize(self, sentinel='#'):
        serial = [self.value]
        if self.left is None:
            serial.append(sentinel)
        else:
            serial.extend(self.left.serialize(sentinel))
        if self.right is None:
            serial.append(sentinel)
        else:
            serial.extend(self.right.serializr(sentinel))
        return serial

    @classmethod
    def deserialize(cls, source, sentinel='#'):
        def _helper(index):
            if source[index] == sentinel:
                return None, index + 1

            value = source[index]
            left, index = _helper(index + 1)
            right, index = _helper(index)
            return cls(value, left, right), index
        return _helper(0)[0]

And at the very last, I would provide default values for the left and right parameters:

class Node(object):
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

So I can more easily write trees:

t = Node(13, Node(8), Node(15, right=Node(18)))
t.serialize()
# [13, 8, '#', '#', 15, '#', 18, '#', '#']

An other way to look at the problem is to take inspiration from repr. If we were to write an official representation for such objects, we could end up with:

    def __repr__(self):
        return '{}(value={!r}, left={!r}, right={!r})'.format(self.__class__.__name__, self.value, self.left, self.right)

And repr(t) would be the string:

Node(value=13, left=Node(value=8, left=None, right=None), right=Node(value=15, left=None, right=Node(value=18, left=None, right=None)))

It's a bit verbose, but it is serialized as a string. Using eval on this string would even deserialize it and return a Node equivalent to t. I however advise against the use of eval for deserialization purposes as it is too generic and thus dangerous.

Instead, serialization could return a more stripped form such as (8,,) for Node(8) or ('#',(5,,),) for Node('#', Node(5)) and deserialization would be a parser tailored for this representation.

Serialization is easy:

    def serialize(self):
        return '({!r},{},{})'.format(
            self.value,
            '' if self.left is None else repr(self.left),
            '' if self.right is None else repr(self.right))

Deserialization is left as an exercise for the reader.


There are a couple of things in here that concern me.... but, the most concerning is:

Use .equals() to compare String values

Code like this:

if(basket[i][0]==X){

will fail when you get data that is not String-constant data.

That line should be:

 if(basket[i][0].equals(X)){

This problem is found all over your code.

In addition, there are other problems:

your arrays are pre-sized. This code:

String[][] basket = new String[16][2];

is potentially OK if you are initializing the array, but what if there are more than 16 pairs?
it would be better to create a 'Pair' class to contain your two strings, than to use the 2-size array on the basket. Then your basket could be something like:

StringPair[] basket = new StringPair[SIZE];

your StringPair class could look something like:

public class StringPair {
    private final String first, second;

    public StringPair(String first, String second) {
        this.first = first;
        this.second = second;
    }

    ..... getFirst() .....
    ..... getSecond() .....

}

compare(String[][] that, String[][] ths) is a method that needs no state data. It should be a static method, or a utility method. Alternatively, it should be a simple 1-value method compare(MyClass that) ... which, for what it is worth, would be very similar to the equals(...) method.

but, that method is pretty broken. It has the two input parameters that and ths, but it then overwrites those values with the internal versions bag and basket.

that = basket;
ths = bag;
boolean equal;

if(that.equals(ths))
    equal = true;
else
    equal = false;
return equal;

now, since you set bag = basket earlier, this will always return true.

Further, that last 5 lines of the method can be replaced with:

return (that.equals(ths));


You are doing the lookup twice.
            if (!encoded_url.count(long_url)) {

                .. stuff

            } else {
                tiny_encoded = encoded_url[long_url];
            }

I know that it is O(1) for the lookup. But there is a real constant inside that. Avoid it if you can.
Use find(). Then if it is there you can simply use it.
            auto find = encoded_url.find(long_url);
            if (find == encoded_url.end()) {

                .. stuff

            } else {
                tiny_encoded = find->second;
            }

This is great if you want random URL that are hard to guess.
                for (auto index = 0; index < kTinySize; ++index) {
                    tiny_encoded.push_back(char_pool[rand_generator() % std::size(char_pool)]);
                }

But is that a requirement of the puzzle. Seems (not sure how expensive the generating the random number is) like this is very expensive way of generating a name.
There is also a chance for a clash. If you are using randomly generated values append a timestamp on the end to avoid a clash.

Personally I don't like having to specify a type. But if you are goint to do it use the type of the method rather than being this specific:
    encoded_url.insert(std::pair<std::string, std::string>(long_url, tiny_encoded));

    // Top of the class.
    using Map      = std::unordered_map<std::string, std::string>;
    using MapValue = Map::value_type;

    // In the code.
    encoded_url.insert(MapValue(long_url, tiny_encoded));

But I think I would simply have used emplace().
    encoded_url.emplace(long_url, tiny_encoded);


the high <= low part does not involve x and could be pulled out of the case. The rest is fine IMHO.

One remark: the -1 return in the error-case is a bit of a smell - why not return Option[Int] instead?

And finally: I think you don't need mid as an argument - as you guard for low > high anyway you can as easily compute it inside your inner function and make the calls a bit more readable (only low and high)

Could look like this

  type Index = Int

  def binarySearch(ds: Array[Double], key: Double): Option[Index] = {
      @tailrec
      def go(lo: Index, hi: Index): Option[Index] = {
        if (lo > hi)
          None
        else {
          val mid: Index = lo + (hi - lo) / 2
          ds(mid) match {
            case mv if (mv == key) => Some(mid)
            case mv if (mv <= key) => go(mid + 1, hi)
            case _ => go(lo, mid - 1)
          }
        }
      }
      go(0, ds.size - 1)
  }


The name LinkedListImplementation seems a little awkward, especially if someone else may try to use it.  It's understandable that you want to avoid using the same name as the official class, in which case you can consider MyLinkedList as the class name.
There's no need for that stray return at the end of clear() since it's a void function.
I'm not sure why those statements in main() are commented out.  Testing for exceptions is okay.  But, perhaps this indicates that you should have actual unit testing using JUnit.  main() would then initiate these tests without the need to comment out any of them.


Helper function to return a string based on passed object and some defined rules

boolean isUpdateMessage = (chat.getTag().equals(TAG_UPDATE_MSG));

Consider using a chat.isUpdateMessage() method for that logic.

UserRelationshipInfo relationshipInfo = UserRelationshipInfoManger.getInstance().getInfo(chat.getUserId());

Singleton pattern detected! I would not recommend using the singleton pattern, I am quite certain that there's a better way to do this, as I don't know the entire context of your code I am not sure which method would be the best, but to get you started take a look at a previous answer of mine.

boolean isUserMyFriend = (relationshipInfo != null && relationshipInfo.getSource() == SOURCE_FRIEND);

Again, consider using as method such as relationshipInfo.isMyFriend()

message = Resources.string(isUserMyFriend ? R.string.text_user_is_friend : R.string.text_user_is_stranger);

Again, this seems like you have a Context stored in a static variable somewhere. I wouldn't recommend that. Tell, don't ask. If something needs your context, tell them about it. Don't have them ask some other object/place about it.

boolean isDirectMessage = (chat.getType() == DIRECT_MESSAGE);
boolean isTextMessage = (chat.getTag().equals(TAG_TEXT_MSG));

Two methods: chat.isDirectMessage() and chat.isTextMessage().

String messageName = Resources.string(getMessageType(chat.getTag()));

getMessageType should be a method in the ChatMessage class. chat.getMessageType(). And again, I'm not a fan of the Resources.string method as it tells me you got a static Context object somewhere.

message = String.format(Resources.string(R.string.text_new_message), chat.getUserInfo().getDisplayName());

When using Android resources, there's a special method for combining the getString with String.format. See this method


From a "How to get the right answer" point of view, David's comment which explains why asking the OS is the only trustworthy solution best answers the question.

But this is Code Review, not Stack Overflow.  From that point of view:

The cpuid instruction returns different data depending on the input value of eax.  Since you never set it before executing your asm, (conceivably) the length of the operation could vary between calls, mucking up your calculation.

Also, the mov statements are unnecessary:

asm ("cpuid\n\t"
     "rdtsc"
     : "=d"(my_edx), "=a"(my_eax)
     : "a"(0)
     : "%ebx", "%ecx");

It might also be worth looking at rdtscp as a replacement for cpuid + rdtsc.


Applicative permutation to generate knight moves

Using pattern matching you can write:

invert 1 = 2
invert 2 = 1
invert n = 0 -- Error would be better in my opinion

You can inline 6 and 2 instead of taking them from a single item list.


"Backwards Read Primes" of Codewars powershell version

Update: Later this night after I asked my question I continued to think of ways I could have improved the performance of my solution. I made some refactors that I'm going to share which gave me enough boost to beat the time requirement for this problem.
But please continue to post your answers, I'm here to learn as well. And any new nugget of efficiency I can add or look at is still super valuable to me.
Thanks in advance...
So the fist changes I made even though a bit small was
I removed the .ToString() to my $num in my isPrime function, I realized that it was not even needed, and yes that's a small change but every bit helps in this case...
The update isPrime function below...

  function isPrime ($num) {

      if ($primes.containsKey($num)) {
          return $true;
      }

      if ($num -lt 3) {
          return $num -gt 1;
      }

      if ($num % 2 -eq 0 -or $num % 3 -eq 0) {
          return $false;
      }

      $i = 5;

      while ($i * $i -le $num) {
          if ($num % $i -eq 0 -or $num % ($i + 2) -eq 0) {
              return $false;
          }

          $i += 6;
      }

      $primes[$num] = $num; # removed the .ToString() here... very small optimization but it all matters I guess.

      return $true;
  }

Next I went to the for-loop and realized that I was doing 2 isPrime calls and a reverse number call as well... It dawned on me that I could easily just declare and assign $nPrime variable and then check if it's false then no need to continue and just go to the next iteration, same with $nPrimeReverse. But before that I would call revNum and test if $nReversed is equal to $i if it is, then also I would call continue and start the next iteration. Then finally I just add a check at the start determining if $i is greater than 13.
Here is the updated for-loop:

  for ($i = $start; $i -le $stop; $i += 2) {

      if ($i -lt 13) { continue; }

      $nPrime = isPrime $i;

      if ($nPrime -eq $false) { continue; }

      $nReversed = revNum $i;

      if ($nReversed -eq $i) { continue; }

      $nPrimeReverse = isPrime $nReversed;

      if ($nPrimeReverse -eq $false) { continue; }

      $res += $i;
  }

After all these small changes my solution passed within the time constraint.
Please feel free to comment any additional items that I could refactor and improve.
Warm Regards


private IEnumerable<int> NextFive(int int1, int int2)

The names int1 and int2 give absolutely no clue about what they are good for. I tried to ready the code but I cannot figure it out. Looking at if (i == int1 || i == int2) I guess it means exclude but who knows.

throw new IndexOutOfRangeException("int1 == int2");

This isn't IndexOutOfRangeException but rather ArgumentException. The argumetns have invalid values but they might be within the allowed range.

throw new IndexOutOfRangeException("int1 > 51 || int2 > 51");

I agree this is the right type of the exception but I preferred it checking each value separately to give the user a hint which one of the parameters is incorrect.

Random rand = new Random();
private int[] deckBase;
int nextFiveLastStart = 45;

Inconsistent access modifier usage. private implicit, private explicit, private implicit... Pick one ;-)

int j = 0;
for (int i = 0; i < 52; i++)
{
    if (i == int1 || i == int2)
        continue;
    deckBase[j] = i;
    j++;
}

There's no need for the int j = 0; you can put it inside the for:

for (int i = 0, j = 0; i < 52; i++)
{
    if (i == int1 || i == int2)
        continue;
    deckBase[j] = i;
    j++;
}


General
There are a few issues in here that cause inaccurate data, as well as some inefficiencies.

When a post is created it is also registered in PostHistory (three times, actually) There is no need to check for post creation at all since you already check for the same activity in the history.
You populate the Source column, but never use it. SQL is in large part dependent on data volume, and you are 'shifting' more data than you need to.
Your VoteCreation section is OK, but you realize you only pull out bounties and favourites from that, right (VoteType 5 and 8)? Other votes are anonymized, and are not possible to find...
Somehow you have 0-day streaks. How does that make sense?

SuggestedEdits requires a special section....
You have three sections for SuggestedEdits. One uses the Creation date, the others use the Approved and Rejected dates. The approval and rejection are not activities by the Owner of the suggested edit, but you are counting them as such.... Only the CreationDate indicates activity by the OwnerUserId in the SuggestedEdit.
The approval and rejection activity are recorded in the SuggestedEditVotes table (which you process from a different section).
Note, you are missing 'accepts an answer' which can be calculated from the Post/Votes combination.
As for your 'additional questions'....
Without the temp table
Yes, this can be done without the temp table, and without the loop.
You can do it all as a single query, if you use CTE expressions to hold the data.
With a CTE containing the 'activity' data, you can find the first day in a streak (Using a self-join, does the user have activity on the previous day, if they do not, then it's the first day of a streak)
Once you have identified the first day, you can also identify which activity belongs in which streak (the most recent start before the current activity must be the start...)
Finally, the streak is as long as the furthest date that belongs to each streak....
As it happens, this is efficient enough to be run for all users on the whole of Code Review.... the query is (Here in SEDE):
declare @userid integer = ##UserId:int?-1##;

with ActiveDays as (

    select Distinct
           UserId as UserId,
           Convert(Date, CreationDate) as Day
    from   PostHistory

  UNION

    select Distinct
           UserId as UserId,
           Convert(Date, CreationDate) as Day
    from   Comments

  UNION

    select Distinct
           OwnerUserId as UserId,
           convert(Date, CreationDate) as Day
    from SuggestedEdits

  UNION

    select distinct
           Q.OwnerUserId as UserId,
           Convert(Date, V.CreationDate) as Day
    from Posts Q inner join Votes V
      on Q.AcceptedAnswerId = V.PostId
      and V.VoteTypeId = 1

  UNION

     select distinct
            UserId as UserId,
            Convert(Date, CreationDate) as Day
     from SuggestedEditVotes

), StreakStarts as (

    select UserId, Start.Day
    from ActiveDays Start
    where not exists (
        select 1
        from ActiveDays
        where Start.UserId = UserId
          and DateAdd(dd, -1, Start.Day) = Day
    )

), StreakMerge as (

    select A.UserId, A.Day, Max(S.Day) as Start
    from ActiveDays as A inner join StreakStarts as S
      on A.UserId = S.UserId
      and A.Day >= S.Day
    group by A.UserId, A.Day

), LongStreaks as (

    select UserId, Start, 1 + max (DateDiff(dd, Start, Day)) as  Streak
    from StreakMerge
    group by UserId, Start
)

Select U.Id as [User Link], U.DisplayName, Start, S.Streak
from Users as U inner join LongStreaks as S
  on U.Id = S.UserId
where S.Streak > 1
  and (@userid = -1 OR U.Id = @userid)
order by S.Streak desc


Fix getNextId

static const idType& getNextId()
{
   static idType id = 0;
   return id++;
}

is not right.

There is no need to return a const idType&. It can be just idType.
If you want to return a const idType&, you need to change the return statement to:

return ++id;

Using

return id++;

has couple of problems.

The value of the first ID will be 0, not 1. Is that your intention?
id++ is an rvalue, not an lvalue. It is like:

int temp = id;
++id;
return temp;

I get the following compiler warning with your code using g++ 4.8.4:

 warning: returning reference to temporary [-Wreturn-local-addr]
  return id++;

In conclusion, I suggest:

static idType getNextId()
{
   static idType id = 0;
   return ++id;
}

Fix return type of main

You have

void main() { ... }

The standard requires the return type of main to be int. Change it to:

int main() { ... }

Change physical layout of the classes

The public section of a class are most important to users. Hence, I recommend the pubilc section listed first. If we could, we could completely hide the private section from the users. Hence, I recommend the private section to be listed last.

class EventListenerHandle
{
   public:

      // Add the public members

   private:

      // Add the public members
};

Of course, I recommend this change for Channel too.

Unused macro

You have

#define KDFA_DEFINE_VOID_EVENT(__NAME__)    struct __NAME__{EVET_TYPE_FUNC(__NAME__)};

It's not used anywhere in your posted code. It's not clear what the purpose of the macro is.

Unclear purpose of macro

You also have

#define EVET_TYPE_FUNC(T) static std::string eventType(){return #T;}

which is used in:

struct TouchEvent
{
   int t_id;
   float x;
   float y;
   EVET_TYPE_FUNC(TouchEvent);
};

However, removing the line

   EVET_TYPE_FUNC(TouchEvent);

from TouchEvent does not create any compiler or linker errors. It's not clear what the purpose of creating eventType() is.

Don't use ALL CAPS for functions

You have

template <typename T>
void DISPATCH_EVENT(const T& t)
{
   EventChannel<T>::tringgerEvent(t);
}

template <typename T>
void DISPATCH_EVENT(T* t)
{
   DISPATCH_EVENT<T>(*t);
}

All caps are usually reserved for macros, not for functions. Change them to:

template <typename T>
void dispatchEvent(const T& t)
{
   EventChannel<T>::tringgerEvent(t);
}

template <typename T>
void dispatchEvent(T* t)
{
   // No need for explicit use of T here.
   // That should be correctly deduced.
   // dispatchEvent<T>(*t);
   dispatchEvent(*t);
}

Registering and removing listeners is not symmetric

You have:

EventChannel<T>::registerListener() { ... }

for registering listeners but removing listeners is accomplished using

EventListenerHandle::remove()

I recommend adding a function removeListener in EventChannel.

EventChannel<T>::removeListener(EventListenerHandle handle) { ... }

If you do that, the only member data needed in EventListenerHandle will be just the ID of the event.

Suggested event handling code

#include <iostream>
#include <functional>
#include <unordered_map>
#include <string>

struct EventListenerHandle
{
   unsigned int id;
};

template <typename T>
class EventChannel
{
   public:

      using idType = unsigned int;

      static EventListenerHandle registerListener(std::function<bool(const T&)> listener)
      {
         auto id = getNextId();
         getHandlers()[id] = listener;
         return EventListenerHandle{id};
      }

      static void removeListener(EventListenerHandle handle)
      {
         getHandlers().erase(handle.id);
      }

      static void tringgerEvent(T e)
      {
         for (const auto& h : getHandlers())
         {
            h.second(e);
         }
      }

   private:
      static idType getNextId()
      {
         static idType id = 0;
         return ++id;
      }

      static std::unordered_map<idType, std::function<bool(const T&)>>& getHandlers()
      {
         static std::unordered_map<idType, std::function<bool(const T&)>> handlers;
         return handlers;
      }
};

template<typename T>
class EventChannel<T*>{};

template<typename T>
class EventChannel<T&>{};

template <typename T>
class EventChannel<const T>{};

template <typename T>
void dispatchEvent(const T& t)
{
   EventChannel<T>::tringgerEvent(t);
}

template <typename T>
void dispatchEvent(T* t)
{
   dispatchEvent(*t);
}

Test code

struct TouchEvent
{
   int t_id;
   float x;
   float y;
};

int main()
{
   auto lid = EventChannel<TouchEvent>::registerListener([](const TouchEvent& ev)->bool
                                                         {
                                                         std::cout << "got touch " << ev.t_id << "\n";
                                                         return false;
                                                         });

   TouchEvent t;
   t.t_id = 10;

   dispatchEvent(t);  // dispatch with object
   dispatchEvent(&t); // dispatch with pointer

   EventChannel<TouchEvent>::removeListener(lid);

   dispatchEvent(t);
}


Simple parallel foreach loop code correctness

No, when you use the lock like that, it's completely useless. Each lock would get its own identifier, so none of he locks would keep any other thread out. To make the lock work at all, you need to use the same identifier for all locks. Demonstration:

object sync = new Object();
var keytofind = rawDataMeasure.RateKey.ToString(CultureInfo.InvariantCulture);
Parallel.ForEach(measures, measure => {
  lock(sync) {
    var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
    if (firstOrDefault != null) {
      measure.TopicCode = firstOrDefault.TopicCode;
    }
  }
});

However, if you need a lock around the code in a parallel loop, then the parallel loop is pointless. The reason that you use the parallel loop is that several threads can run at once, and the lock would prevent that.


Java - How to represent the result of an operation

If you don't want to use exceptions you should know that in OOP there is a lot of ways to implement the fact that some object belongs to some specific class. It can be either some enum that enumerates all possible domains or in case of OOP languages it can be class.

So in case of Java (again if you don't want exceptions by some reason) you can use:

class Result
{
    public static final Result ok = new Result(); // I'm not sure this is correct in terms of Java
}

class Failure extends Result
{
    public final String errorMessage;
    public Faliure(String message)
    { this.errorMessage = message; }
}

if (result instanceof Failure)
{
    // do something
}


You can use LINQ to do it, but that will end up as pretty ugly code. LINQ is used to process data and return a result, and that is not what you are doing here, so using LINQ for this would only mean that your code would produce a dummy result and have a side effect doing so.

Well, for completeness, here is some ugly code that misuses LINQ extension methods to loop through the items:

lst.Select((item, i) => item.ColumnOrder = (short)i).Last();

(Note the Last call that is used to pull the result out of the expression, so that it actually loops through the items. Even if you don't use the result, you still have to loop through the entire result to make it complete the loop.)

Your original code is just the simplest way to do it (except for the use of Count() instead of Count as svick mentioned), and is likely to give the best possible performance. There are other alternatives of course that gives almost the same performance. You can use an enumerator to loop through the items, but then you still need a counter for the column order:

int i = 0;
foreach (var item in lst) {
  item.ColumnOrder = (short)(i++);
}


I don't see anything wrong or debatable in this so far. Just a couple nitpicks:

I would use parameter splatting to make the color part more compact. For example, from my own log function:
  switch ($Severity) {
      Debug    { $colors = @{ForegroundColor="DarkGray"                               } }
      Info     { $colors = @{                                                         } }
      Warning  { $colors = @{ForegroundColor="Black"      ; BackgroundColor="Yellow"  } }
      Error    { $colors = @{ForegroundColor="White"      ; BackgroundColor="DarkRed" } }
      Critical { $colors = @{ForegroundColor="DarkYellow" ; BackgroundColor="DarkRed" } }
  }

  Write-Host @colors "$($Severity): $Message"

Maybe you could go even further with a hash of hashs and do Write-Host @colors["error"] or something like that.

To create a file only if the file doesn't already exist, you can call New-Item directly, it will throw an exception if the file already exists which you can just ignore with a try-catch or with -ErrorAction SilentlyContinue, saving a couple lines.

Why not make all the configuration fetched from the config file optional parameters, with the values in the file as default values ? That would help if you ever have to use the function on the fly, in a shell or as a debug tool.

Very personal opinion, but I would personally put the default value of $OperationResult to Info, as this is the most common case for me and I'd appreciate just whipping out a simple Write-Log "mymessage" without extra typing.

Last one, this one depends on your environment, but Write-Log is also a function in the officiel VMWare vSphere module that is quite widely used. I wouldn't change any code because of that but remember to document that if you ever have to distribute your code.

Overall I think your cmdlet is pretty readable and produces a log that is easy enough to parse, so it ticks all the important boxes for me.


You need to keep track of visited tiles, or you risk ending in an infinite (recursive) loop. If you use recursion, and if you are not allowed to change the class, this is difficult, as you'd need to add another parameter to findGoldenTile holding the already visited tiles.

Alternatively, you could not make it recursive, but with a queue and with the set of visited tiles in the method itself. Something like this (not tested):

public Tile findGoldenTile() {
    Set<Tile> visited = new HashSet<>();
    LinkedList<Tile> queue = new LinkedList<>();
    queue.add(this);
    visited.add(this);
    while (! queue.isEmpty()) {
        Tile tile = queue.pop();
        if (tile.isGoldenTile) {
            return tile;
        }
        for (Tile x : tile.neighbors) {
            if (! visited.contains(x)) {
                queue.add(x);
                visited.add(x);
            }
        }
    }
    return null;
}


Reduction of time for the code of sorting RGB and Depth images according to timestamp values

You are reading in an image and then writing it back out again without making any changes. If the purpose is to copy the file, you are better off directly copying the file. You can use the function copyfile for that.

The code is fairly readable. There are some improvements you can make:

filePattern = fullfile(depth_img, '*.timestamp');
file = dir(filePattern);

filePattern2 = fullfile(color_img, '*.timestamp');
file2 = dir(filePattern2);

filePattern3 = fullfile(depth_img, '*.bmp');
file3 = dir(filePattern3);

filePattern4 = fullfile(Openpose, '*.png');
file4 = dir(filePattern4);

The four filePatternN variables are never used again. Why use four different variables, rather than repeat the same name? Why not omit the temporary variable and put these into single lines?

file = dir(fullfile(depth_img, '*.timestamp'));

Next, you have two identical loops, one reads from file, one from file2. One writes to A, one to B. Why not make this into a function? You can write local functions at the end of your M-file. You'd simplify this bit to:

A = get_time_stamps(file);
B = get_time_stamps(file2);

Another difference between these two loops is that one uses fileID and one uses fileID2. There is again no need to use two different names for local variables that you don't use outside the loop.

You can improve your code by making A and B numeric arrays rather than cell arrays:

tmp = textscan(fileID,'%d64');
A(k) = tmp{1};

Be sure to preallocate the arrays!

Next you have again two large blocks of mostly repeated code. if length(file2) <= length(file). You could put this into a function and call it do_stuff(file,file2) or do_stuff(file2,file) depending on which of the two is larger. But really, this might not be necessary at all with some better logic.

To find which time stamps are closest to each other, you don't need a O(n2) algorithm. You could instead sort the two arrays of time stamps, and walk through them one by one. The algorithm might be slightly more complex, but you wouldn't need to duplicate the code.

The other alternative is to use vectorized processing to do the O(n2) computation without using loops at all. But in modern versions of MATLAB, loops are not so slow any more, so this is not something you should be worrying about anyway. The way to speed up this loop is to preallocate the array C.

You can also simplify it by writing C{m,k} = abs(A{k,1} - B{m,1});, and removing the if statement.


The algorithm can be improved. I took the liberty to use my existing Java, also as Python might be somewhat slower.

On the Python code: X == true should simply be X.

long largestPrimeFactor(long x) {
    long largest = 0;
    long n = x; // Remaining number where factors divided out.
    if (n % 2 == 0) {
        largest = 2;
        do {
            n /= 2;
        } while (n % 2 == 0);
    }
    for (int c = 3; c*c <= n; c += 2) {
        if (n % c == 0) {
            largest = c;
            do {
                n /= c;
            } while (n % c == 0);
        }
    }
    // Wrong: return largest == 0 ? x : largest;
    return n > 1 ? n : largest;
}

The loop searching for factors handles 2 before the loop and then loops from 3 with steps of 2.

    for (int c = 3; c*c <= n; c += 2) {

In every loop step, if c is a factor of n, n is divided by c as often as possible. In fact n has no longer smaller factors than c.

Hence c is a prime, and in fact the largest found prime upto then.

If after the loop no largest prime was found, the parameter itself is a prime.

As n in every step is divided by all smaller factors, you need only to loop while c <= n / c holds: the second c being the smallest co-factor of n for c. Together with += 2 this hugely decreases the number of steps.

Your extra test on the factor being prime is the largest slow-down, as it does not exploit the factor filtering till then.


First I'd like to call out the good things that you've done:

Writing functions, including a standard main().
Having more or less sensible function and variable names.
Proper use of with.

An improvement here is to stop parsing the file yourself, and to start parsing it with Python's native csv library. Even though your format is not technically CSV (it's separated by semicolon), you can still configure csv to use a different delimiter.

I recommend the use of the DictReader class. Given that you only pay attention to one variable, just use csv.reader. During initialization, get the index of the column you want, and then use that on every record that the reader gives back.

The critical performance issue here is that you have nested loops for row comparison. Given that you are comparing two series expected to be in the same order, but with edits (insertions and deletions), effectively you're doing a diff. Read this for a nice walkthrough.

http://www.xmailserver.org/diff2.pdf


Thread safety and performance when multiple threads write into same Writer

Making the lineCounter volatile will not help here. If synchronized is not used, the following sequence of actions is possible:

Thread A writes something to a file.
Thread B writes something to a file.

If the lineCounter was equal to maxLines - 1 before the first step, the behavior of the program is obviously incorrect.

As you have said, you need to synchronize a group of actions(write, close, addFile, open). That's why you need to use synchronized(or a Lock).

About performance: are you sure that synchronization is really an issue? Did you profile your code or are you just making guesses? Before making things more complicated, you should make sure that it will actually solve the problem.


excel-vba function to filter an array and return an array

ReDim Preserve and Transpose are not free.  I use this pattern when I need to filter an array:

Declare a 1-D array (Indices) with the same number of rows as the 2D array
When a match is found add the matches index to the Indices array and increment the counter
If there is matching data, declare a 2-D array (Results) with the same dimensions of the Input array but a row count equal to the counter
Iterate over the indices in the Indices array and add the matching values to the Results
Return the Results
If there are no matches return an empty array

Quick Filter
Public Function QuickFilter(input_arr As Variant, col_index As Long, filter_value As Variant) As Variant
    Dim r As Long
    Dim Count As Long
    Dim Indices As Variant
    ReDim Indices(LBound(input_arr, 1) To UBound(input_arr, 1))
    Count = LBound(input_arr, 1) - 1
    For r = LBound(input_arr, 1) To UBound(input_arr, 1)
        If input_arr(r, col_index) = filter_value Then
            Count = Count + 1
            Indices(Count) = r
        End If
    Next

    Dim Results As Variant
    Dim c As Long
    Dim index As Long
    If Count >= LBound(input_arr, 1) Then
        ``` we want results to hold the entire row
        ReDim Results(LBound(input_arr, 1) To Count, LBound(input_arr, 2) To UBound(input_arr, 2))
        For r = LBound(input_arr, 1) To Count
            index = Indices(r)
            For c = LBound(input_arr, 2) To UBound(input_arr, 2)
                Results(r, c) = input_arr(index, c)
            Next
        Next
        QuickFilter = Results
    Else
        QuickFilter = Array()
    End If
End Function


Thanks for sharing your code.

What you posted is a nice data structure.

But OOP is about behavior. (we still need data structures to store state but usually objects have behavior.

Let see is this way: There are 3 Types of component in an electronic system:

signal source (such as switches and sensors)
signal receivers (such as Light bulbs, LEDs or electric engines)
logical elements (such as And, OR NOT).

The signals are no objects (with behavior since they are just messages transfered between the objects...

So I'd suggest classes like this:

// signal are still data structure
enum Signal { OFF, ON }

// some interfaces for abstraction
interface SignalReceiver {
    void consume(Signal signal, SignalSource from);
}
interface SignalSource {
    void triggers(SignalReceiver r);
}
interface LogicElement extends SignalReceiver, SignalSource {}

// a switch is a typica "signalSource"
class Switch implements SignalSource {
    private final Collection<SignalReceiver> receivers = new HashSet<>();
    private Signal state = Signal.OFF;
    private final String name;

    public Switch(String name) {
        super();
        this.name = name;
    }

    @Override
    public void triggers(SignalReceiver r) {
        receivers.add(r);
    }

    public void doSwitch() {
        state = Signal.values()[1 - state.ordinal()]; // get the other signal
        System.out.print("Switch "+name+" is "+state +" ");
        for (SignalReceiver signalReceiver : receivers) {
            signalReceiver.consume(state, this);
        }
    }
}

class LightBulb implements SignalReceiver {
    public LightBulb(SignalSource signalSource) {
        signalSource.triggers(this); // tells the source "trigger me!"
    }

    @Override
    public void consume(Signal signal, SignalSource from) {
        System.out.println("light is " + signal);
    }
}

class Or implements LogicElement {
    private final Collection<SignalReceiver> receivers = new HashSet<>();
    private final Map<SignalSource, Signal> inputs = new HashMap<>();

    Or(SignalSource... signalSources) { // "vararg" parameter, accepts many sources
        for (SignalSource signalSource : signalSources) {
            signalSource.triggers(this); // tells the source "trigger me!"
            inputs.put(signalSource, Signal.OFF);
        }
    }

    @Override
    public void triggers(SignalReceiver r) {
        receivers.add(r);
    }

    @Override
    public void consume(Signal signal, SignalSource from) {
        inputs.put(from, signal);
        Signal output = inputs.values().stream() // Java8 functional programming
                .max((s1, s2) -> s1.compareTo(s2))// depends on order in enum!
                .get();
        for (SignalReceiver signalReceiver : receivers) {
            signalReceiver.consume(output, this);
        }
    }
}

And this is the test:

public class Electronics {
    public static void main(String[] args) {
        // circuit configuration
        Switch s1 = new Switch("left");
        Switch s2 = new Switch("right");
        new LightBulb(new Or(s1, s2));

        // operation
        s1.doSwitch(); // light on
        s1.doSwitch(); // light off
        s2.doSwitch(); // light on
        s1.doSwitch(); // light on
        s2.doSwitch(); // light on
        s1.doSwitch(); // light off
    }
}

Yo may notice that I my approach has no "getter" method.
This is because "getter" as well as "setter" violate one of the most important OO principles: information hiding / encapsulation. You should avoid them on classes implementing actual behavior (on pure data objects they are OK...) The "rule of thumb" is: "Tell!, don't ask!"


Extracting the first two components of a version number

I can't think of a simpler way of doing the splitting.

The only thing that comes to mind is replacing [0:2] by [:2] to take the first two components of the version number, since the first index in the slice notation defaults to the beginning of a sequence object.

However, instead of using a string, you could use a namedtuple with integer elements to represent a version number, which would allow you to do comparisons more easily:

>>> from collections import namedtuple
>>> VersionNumber = namedtuple('VersionNumber', 'major minor')
>>> version_str = '1.2.3.dev0'
>>> version = VersionNumber(*map(int, version_str.split('.')[:2]))
>>> print(version)
VersionNumber(major=1, minor=2)
>>> if version.major < 2:  # don't care about minor version
...     print('Need at least version 2.')

You could easily convert it back to a string:

>>> '.'.join(map(str, version))
'1.2'


Since PHP 5.3 you can use the shortcut $a = $b? : $c:

$this->uniqueSessionKey = $settings->get('uniqueSessionKey') ?  : $_SERVER['HTTP_USER_AGENT'] . time();

--

Just a note: you can not use this if you want check if the var $a is set. In this case you must use the original form: $a = isset($b)? $b : $c;

Otherwise, you can write a custom function in this way:

function getIfSet(&$a, $default = null) {
      return isset($a)? $a : $default;
}

$a = getIfSet($b,$c);

Passing var by reference (&$a) avoid the PHP notice if $a is not set.


Join 5 optional strings with a joiner character

I do it a bit more elegantly I believe. First, this extension function is pretty useful.

extension Array {
    static func filterNils(array: [T?]) -> [T] {
        return array.filter { $0 != nil }.map { $0! }
    }
}

An example of my request models.

class PostRequest: BaseRequest {
    var startIndex: Int?
    var fetchCount: Int?
    var programID: String?
    var userID: String?
    let postType: FeedPostType

    var userPostFilter: String? {
        switch postType {
        case .User:
            return "all"
        default:
            return nil
        }
    }

    init(postType: FeedPostType) {
        self.postType = postType
    }

    override var path: String {
        let basePath = "/posts"
        var arguments: [String] = Array.filterNils([basePath,postType.rawValue,programID,userID,userPostFilter,startIndex?.toString(),fetchCount?.toString()])
        return "/".join(arguments)
    }
}

toString is also an extension on Int

extension Int {
    func toString() -> String {
        return String(self)
    }
}


As I said in the comments, your system is pretty close to a system of signals and slots. Congratulations if you never heard of the pattern before, that's an excellent way to implement an the observer design pattern! I still have few notes:

I don't know which compiler you use, but mine won't compile your code unless I include <memory> for std::shared_ptr. I suppose that it may be transitively included from <functional> or <list> in your implementation. Never rely on transitive includes from the standard library and always include the exact header that contains what you need.
Qt, which is the emblematic library when it comes to signals and slots, tends to use past participle for its signas names. For example, instead of click, it would be clicked:

button.clicked.connect(/* whatever */);

It allows to read the line easily as "when button is clicked, do whatever". Also, it makes the object look more like a trigger and less like an action.
From a design point of view, connect being a method taking only one function, I would expect it to add the function to the list, not to return a listener.
You should encapsulate std::shared_ptr<std::list<std::function<void(Args...)>>> instead of inheriting from it. Frankly, you don't want people to expose every method of std::shared_ptr. You don't want people to think of pointers when they want events, right?

The truth is my answer isn't really personal. Since your class obviously looks like a signal class, everything I am saying tends to mean "make your design closer to those of existing signal classes like Boost.Signals2" :/