Counting the most frequently appearing character in a string (i.e. the statistical mode)

I'm worried this is turning into Code Golf, so I'll preface my alternative with some actual review.

There is a pretty big bug in your code, as the following will not terminate:

Console.WriteLine(GetMaximumOccurence(" "));

Can you see why?

The basic structure of your code is good. That is, the part that effectively goes

var maxCount = 0;
foreach (var c in input)
{
    // TODO: Count occurrences of c in input.
    maxCount = Math.Max(count, maxCount);
}

return maxCount;

Now how to we complete that TODO? Using IndexOf like you do seems like a good idea.

var maxCount = 0;
foreach (var c in input)
{
    var count = 0;
    var i = input.IndexOf(c);
    while (i != -1)
    {
        // TODO: Keep counting occurrences of c.
    }

    maxCount = Math.Max(count, maxCount);
}

return maxCount;

Now, string has an overload of IndexOf that takes a starting position. But where do we start searching? We start searching one position after our last found occurrence.

var maxCount = 0;
foreach (var c in input)
{
    var count = 0;
    var i = input.IndexOf(c);
    while (i != -1)
    {
        count++;
        i = input.IndexOf(c, i + 1);
    }

    maxCount = Math.Max(count, maxCount);
}

return maxCount;

If you prefer, this can be written as a for-loop.

var maxCount = 0;
foreach (var c in input)
{
    var count = 0;
    for (var i = input.IndexOf(c); i != -1; i = input.IndexOf(c, i + 1))
    {
        count++;
    }

    maxCount = Math.Max(count, maxCount);
}

return maxCount;

However, this solution is not terribly efficient. For each character in the string, we're iterating over the string again with our calls to IndexOf, so our time complexity is \$O(n^2)\$.

In fact, we've basically just written this:

var maxCount = 0;
foreach (var c in input)
{
    var count = 0;
    foreach (var d in input)
    {
        if (c == d)
        {
            count++;
        }
    }

    maxCount = Math.Max(count, maxCount);
}

return maxCount;

@BlueTrin's answer shows how you can trade space to reduce the time complexity to \$O(n)\$, so I won't go over that here.

All that said, there is an elegant way to express this using LINQ:

return input.Length == 0
    ? 0
    : input.GroupBy(c => c).Max(group => group.Count());


I'm not doing a lot of Python but one thing leaping out at me is the usage of all these single letter variables which make the code really hard to read. While longer names will make the code a bit longer I think they will improve readability quite a lot:

s should be start or rangeStart
e should be end or rangeEnd
stp should be step
r: from just briefly browsing over the code I had no idea what that flag is supposed to represent. Given that it's set to True when the step is negative I assume it could mean reverse.


Although optional, you can keep your #includes organized (alphabetically, for instance) so that it's easier to locate an individual one or to determine if you've already included a particular one.
You've included <sstream>, but I don't see any use of stringstreams.  If you're not utilizing this library, then remove it.
Avoid using namespace X in global scope as it will expose it to the entire program or file, which can break code in cases such as name-clashing (using the same name for something in which something doesn't belong to the namespace).  It could also make it difficult for readers to tell what is part of a particular namespace (I cannot tell what belongs to v8, so I'm having a bit more trouble reviewing this).  If you insist on keeping a using, then keep it local, such as in a function.
For this enum:

enum Tags {
    Closing = 0,
    Paragraph,
    Heading
};

You don't need to explicitly set it to 0.  This is already the default starting value for enums.
You don't need a char* here:

int tagDetect(char *ptr){

Looking at the calling code, you're passing in an std::string.  You should just pass this object by itself.  Also, because it's not being modified, pass it by const& to avoid a needless copy and any accidental modification:

int tagDetect(std::string const& str){

In C++ in general, you should avoid passing raw pointers to functions as you cannot keep track of ownership with them (C++11 smart pointers helps with that for when points are necessary).  But in this case, you shouldn't need to deal with pointers.

With this change, you will need to modify the function code (I'll use different names for clarity):

This is accessing the first character:

if (*ptr == 'p')

so use front():

if (str.front() == 'p')

This is accessing the second one:

*(ptr + 1)

so you can use indices to make it more clear (while they are technically the same thing; yours is doing pointer arithmetic):

str[1]

I'd keep these on separate lines for readability:

int tagID, lastTag, id = 0, lastAppended = 0, clearStartPos;

They aren't entirely related to each other, and there could be some maintenance issues since some are declared and the others initialized.

int tagID;
int lastTag;
int id = 0;
int lastAppended = 0;
int clearStartPos;

You should also have these declared/initialized as close to their scope as possible.  This will help determine if any variable is no longer used (keeping around unused variables will clutter the code).  But if you cannot put them any closer, then do have each one on separate lines.


Pure Swift solution for socket programming

(Remark: I am using println() for diagnostic output in this review instead of your
log.atLevelDebug(). The reason is that I wanted to test the code before posting
an answer.)

That seems to be working code (with one exception, see below), but there are some things that can be simplified
or improved.

nil is a possible value for any UnsafeMutablePointer<T>, so you can simplify your
initialization, for example:

var hints = addrinfo(
    ai_flags: AI_PASSIVE,       // Assign the address of my local host to the socket structures
    ai_family: AF_UNSPEC,       // Either IPv4 or IPv6
    ai_socktype: SOCK_STREAM,   // TCP
    ai_protocol: 0,
    ai_addrlen: 0,
    ai_canonname: nil,
    ai_addr: nil,
    ai_next: nil)

You traverse the address list from getaddrinfo with

var info = servinfo
while info != UnsafeMutablePointer<addrinfo>.null() {
    // ...
    info = info.memory.ai_next
}

Writing this as a for-loop might be easier to read:

for (var info = servinfo; info != nil; info = info.memory.ai_next) {
    // ...
}

Your printing of the numerical IP addresses with inet_ntop() does not work correctly,
the second argument must be the address of a struct in_addr/in6_addr
and not the address of struct sockaddr, for example:

var sin4addr = UnsafePointer<sockaddr_in>(info.memory.ai_addr).memory.sin_addr
var ipAddressString = [CChar](count:Int(INET_ADDRSTRLEN), repeatedValue: 0)
inet_ntop(
    info.memory.ai_family,
    &sin4addr,
    &ipAddressString,
    socklen_t(INET_ADDRSTRLEN))
let addressStr = String.fromCString(&ipAddressString)

But the more modern interface is getnameinfo() (which works for both IPv4 and IPv6
addresses). Written as a separate utility function:

func sockaddrDescription(addr: UnsafePointer<sockaddr>) -> String
{
    var host : String?
    var port : String?

    var hostBuffer = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
    var servBuffer = [CChar](count: Int(NI_MAXSERV), repeatedValue: 0)

    if (getnameinfo(addr, socklen_t(addr.memory.sa_len),
                    &hostBuffer, socklen_t(hostBuffer.count),
                    &servBuffer, socklen_t(servBuffer.count),
                    NI_NUMERICHOST | NI_NUMERICSERV) == 0) {
            host = String.fromCString(hostBuffer)
            port = String.fromCString(servBuffer)
    }
    return "host: " + (host ?? "?") + " port: " + (port ?? "?")
}

which you could use as

for (var info = servinfo; info != nil; info = info.memory.ai_next) {
    let addrInfo = info.memory

    let desc = sockaddrDescription(addrInfo.ai_addr)
    println(desc)
}

Instead of errno you could log strerror(errno) if any of the socket functions fails.
The error message string would be more instructive than a error number. For example:

status = bind(...)
if status == -1 {
    println("bind failed: " + String(UTF8String: strerror(errno))!)
}

Your function prints all found IP addresses in debug mode, but binds the socket
only to the first one. The recommended practice (if I remember correctly, and I will
try to find a reference) is to

try all IP addresses until socket/bind/listen is successful, or
try to listen on all IP addresses.

is successful. In the first case, your main loop would look like

var socketDescriptor : Int32 = -1 // Invalid socket

for (var info = servinfo; info != nil; info = info.memory.ai_next) {
    let addrInfo = info.memory

    let sd = socket(addrInfo.ai_family, addrInfo.ai_socktype, addrInfo.ai_protocol)
    if sd == -1 {
        println("socket failed: " + String(UTF8String: strerror(errno))!)
    } else {
        status = bind(sd, addrInfo.ai_addr, addrInfo.ai_addrlen)
        if status == -1 {
            println("bind failed: " + String(UTF8String: strerror(errno))!)
        } else {
            status = listen(sd, 1)
            if status == -1 {
                println("listen failed: " + String(UTF8String: strerror(errno))!)
            } else {
                // SUCCESS !!
                socketDescriptor = sd
                break
            }
        }
        close(sd)
    }
}

and then socketDescriptor is -1 or a valid socket descriptor which is bound and
listening.

The more Swifty way however would be to define an optional

var socketDescriptor : Int32?

which is set to a valid socket descriptor or stays nil in the error case.


Filtering conversation by filter type and value

I want to mention only one thing especially:

You're using "magic string" to choose your filter types. Instead of doing that (because it's brittle) you are probably better off with an enum:

public enum FilterType {
    USER, WORD, HIDE_WORD
}

Your code would have to adjust a little, but to give a short look into the filter method:

private void filter(Filter filter, Conversation conversation, String outputFilePath) {
    switch (filter.filterType) {
        case FilterType.USER:
            conversation = Filter.filterByUser(conversation, filter.argumentValue);
            writeConversation(conversation, outputFilePath);
            break;
        case FilterType.WORD:
            conversation = Filter.filterByWord(conversation filter.argumentValue);
            writeConversation(conversation, outputFilePath);
            break;
        // ...

This exposes another small improvement possibility in your code.

In every case you will call this.writeConversation with exactly the same arguments. You can move that to outside the switch-case block:

switch (filter.filterType) {
    // ...
}
this.writeConversation(conversation, outputFilePath);

Another last thing I want to recommend is using Path intead of String to refer to outputFilePath. This makes it blatantly obvious, that you're  actually referring to a File. Strings are .. not Paths...


Printing primes between user-given numbers

Others have already said to change the algorithm.
There are other general coding practice problems that are worth highlighting too.

Naming

Most of the variable names are awful. If I see x, I'll never guess it's a Scanner.
m and n for the lower and upper limits are poor names too,
as it's easy to mix up which is which.
sqr_root and is_prime don't follow the Java convention of using camelCase.

Testing

How do you test that your solution actually works?
You rerun the program and enter some inputs and verify that the result is correct?
And if you make a change? You recompile, rerun, reverify?
That's an awful lot of work.
It's a lot less work to write some unit tests instead,
which you can easily re-run as simply as the click of a button,
and the result is as easy to verify as seeing all green lights or not.

However, to make the implementation unit testable, it needs to change a bit:

Make the method to take the inputs as parameters instead of standard input
Make the method return the list of primes found

Something like this:

private static final int MAX_UPPER = 1000000000;
private static final int MAX_DIFF = 100000;

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int num = scanner.nextInt();
    for (int t = 1; t <= num; t++) {
        int lower = scanner.nextInt();
        int upper = scanner.nextInt();

        for (Integer prime : getPrimesBetween(lower, upper)) {
            System.out.println(prime);
        }
    }
}

static List<Integer> getPrimesBetween(int lower, int upper) {
    List<Integer> primes = new ArrayList<Integer>();
    if (lower >= 1 && upper <= MAX_UPPER && upper - lower <= MAX_DIFF) {
        for (int current = lower; current <= upper; current++) {
            int squareRoot = (int) Math.sqrt(current);
            boolean isPrime = true;
            for (int i = 2; i <= squareRoot; i++) {
                if (current % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                primes.add(current);
            }
        }
    }
    return primes;
}

And some unit tests, to get you started:

@Test
public void testBetween_4_and_5() {
    assertEquals(Arrays.asList(5), getPrimesBetween(4, 5));
}

@Test
public void testBetween_4_and_9() {
    assertEquals(Arrays.asList(5, 7), getPrimesBetween(4, 9));
}

Extract constants

Notice in the example earlier,
I converted your original hard-coded constants to proper constants.

private static final int MAX_UPPER = 1000000000;
private static final int MAX_DIFF = 100000;

It's cleaner and better this way.

Correctness

It's not so good that the method returns an empty list if you use a too high input number or too big difference, without any indication that something went wrong.
The user might expect a huge list of numbers between 1 and 99999999, or an error, but definitely not an empty list.

Here's a unit test that fails now, until you fix the method to throw an exception in the case of unsupported input values.

@Test(expected = IllegalArgumentException.class)
public void testTooBigDiff() {
    int lower = 11;
    int upper = lower + MAX_DIFF + 1;
    getPrimesBetween(lower, upper);
}


I think at the end it depends on the use case.
For a simple loading of data, i would use the approach of getting the Observable directly.
When the backendcall is not anymore the single source of changes (for example when i could change the data in the frontend and persist it later), or when i want to "store" the data, so that i do not have to call the backend for each request, then i would start thinking about providing an extra observable.

But i would not make the "storage" public, because then others would be able to emit values on it. I would make it private and provide a method that gives access to the data.

// ...
private articles$ : BehaviorSubject<Article[]>([]);

public getArticles(): Observable<Article[]> {
   return this.articles$.pipe(
     distinctUntilChanged();
   )
}

public loadArticles(): void {
  this.db.collection('articles').valueChanges({ idField: 'id' })
  .subscribe(
    (articles: Article[]) => this.articles.next(articles)
  );
}

In my experience i worked mostly with a direct connected backend call. Perhaps with a pipe to map the backend data format into my frontend data format, but thats it.
The other approach i use mostly when i want to implement a central data source.

By the way, i have the tendency to type the return types of my methods, so that the transpiler can provide me some support. :-)


Best way to implement a web MVC application (language agnostic)

Should controllers implement business logic?

That depends on your design and style of doing things "your" MVC-way. As you're designing a framework you should probably allow both to keep the usage of the framework flexible.
Taking a closer look on your code examples I'd say you're only shifting things around anyway. Why do you have a controller when you use it to access the request? Shouldn't the request lead into the controller call and the controller should not care at all about the request any longer? Just a counter question, if you want to make your framework strict for some reason, think about why.

Now the second question. Should repositories deal with create, edit and delete operations?

Normally that's within the domain of a repository, but whatever suits your design needs, a repository could be just a delegate to different create, edit and delete components as well. Application-wise it shouldn't make a difference whether or not, so probably do a risk analysis and then decide which part of the question you actually need to answer now or if you can solve this by just deciding now, and if the future shows that your design needs change, change your design.

We need to deal with ACLs. Whether a domain object or collection is accessible by the current user is determined by the ACLs.
Isn't it part of the model?

Sure, it's part of the model, the ACL Domain Model (and explicitly not other models).


Vue.js Stoplight app - Dynamically changing classes on elements

You could use the Object Syntax to specify the class bindings instead of the Array Syntax:

<input type='button' id='red' :class='{"btn": true, "btn-danger": (count % 3 === 0)}'  />

That "btn": true is okay but a little annoying. Luckily "it’s also possible to use the object syntax inside array syntax"1

<input type='button' id='red' :class='["btn", {"btn-danger": (count % 3 === 0)}]'  />

The documentation uses double quotes and I attempted to use those but it didn't appear to work - perhaps because btn-danger needs to be surrounded by quotes.

<input type='button' id='red' :class="[btn, {'btn-danger': (count % 3 === 0)}]" />

There doesn't appear to be anything dynamic about the styles in styleObject, so those can be moved out of the business logic and maintained with the other styles in the CSS section.

The interval function could be simplified using the increment operator:

setInterval(function() {
  app.count++;
}, 1000);

See the rewritten code that utilizes the advice above.

var app = new Vue({
  el: '#app',
  data: {
    count: 0
  }
});

setInterval(function() {
  app.count++;
}, 1000);
#light {
  background-color: yellow;
  display: inline-block;
  border: 2px solid black;
  margin: 10px;
  padding: 5px;
}

#light .btn {
  display: block;
  width: 30px;
  margin: 0;
  border-radius: 50px;
  border: 1px solid black;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

    <input type='button' id='red' :class='["btn", {"btn-danger": (count % 3 === 0)}]'  />

    <input type='button' id='yellow' :class='["btn", {"btn-warning": (count % 3 === 1)}]'  />

    <input type='button' id='green' :class='["btn", {"btn-success": (count % 3 === 2)}]'  />

1https://vuejs.org/v2/guide/class-and-style.html#Array-Syntax


Firstly, I don't quite understand why are you declaring so much functions that consist of a single line dedicated to printing a string. They are only used once and in one file, so there's no need to use a function or constant. I suggest you to get rid of them and replace calls to these functions with their bodies. Also, put break; inside default case (Here you can learn more about the reason why you should do this):

    switch (option) {
        case F_TO_C:
            printf("Celsius: %f\n", F_to_C(input_temp));
            break;
        case C_TO_F:
            printf("Fahrenheit: %f\n", C_to_F(input_temp));
            break;
        case OFF:
            printf("OFF\n");
            break;
        default:
            printf("Incorrect input, try again\n");
            break;
    }

Secondly, I recommend to use puts() instead of printf() when printing simple strings as it is obviously simpler and places a newline automatically (And you use it often throughout your code). Note that this doesn't involve cases when printing formatted strings.

    switch (option) {
        case F_TO_C:
            printf("Celsius: %f\n", F_to_C(input_temp));
            break;
        case C_TO_F:
            printf("Fahrenheit: %f\n", C_to_F(input_temp));
            break;
        case OFF:
            puts("OFF"); // No need for printf()!
            break;
        default:
            puts("Incorrect input, try again"); // No need for printf() as well!
            break;
    }

Thirdly, I'd suggest to move the body of inter_face() function to main() as it is not used anywhere else and basically creates a run loop, so I don't see any reasons why you should place it in a separate function. In addition to this, you probably want to define your functions before they're used, thus moving all functions above main(). It's not necessary as the compiler will find them anyway, yet I reckon the source code looks better that way (Just imagine reading a book from the end to the beginning).

float F_to_C(float input_temp)
{
      return (5.0 / 9.0) * (input_temp - 32);
}

float C_to_F(float input_temp)
{
    return (9.0 / 5.0) * (input_temp)+32;
}

float get_input_temp()
{
    float input_temp = 0;
    scanf_s("%f", &input_temp);
    return input_temp;
}

int get_option()
{
    int option;
    scanf_s("%d", &option);
    return option;
}

int main()
{
    int option = -1;
    float input_temp = 0.0;

    printf("Temperature conversion Calculator!!\nPlease select an option:");
    printf("\n1.) F to C\t2.) C to F\t3.) off\n\n");

    while (option != OFF) {

        printf("Option: ");
        option = get_option();

        if (option == F_TO_C || option == C_TO_F) {
            printf("Temp: ");
            input_temp = get_input_temp();
        }

        switch (option) {
            case F_TO_C:
                printf("Celsius: %f\n", F_to_C(input_temp));
                break;
            case C_TO_F:
                printf("Fahrenheit: %f\n", C_to_F(input_temp));
                break;
            case OFF:
                puts("OFF"); // No need for printf()!
                break;
            default:
                puts("Incorrect input, try again"); // No need for printf() as well!
                break;
        }
    }

    getchar();
}

Fourthly, you should put function prototypes, enumerations and other objects that carry data (Of course, prototypes do not carry data, yet they belong in header files) into a separate header file (For instance, main.h). That way your source file looks a lot cleaner, and if someone wants to use these functions elsewhere, he can easily find this header file with needed prototypes within.

Fifthly, I'd consider either merging or getting rid of get_option() and get_input_temp() functions as they perform the same task, just with different data types. I suggest to create a single function called get_input() that returns a float (Since float can be compared to int without requiring you worry about loosing precision) instead if you don't want to put them inside main() as we did with other redundant functions before. You may then compare these variables normally as usual arithmetic conversions from int to float will occur when comparing float to int (You can learn more about such conversions here, here and here).

#include "main.h" // Prototypes and enum are there!

float F_to_C(float input_temp)
{
      return (5.0 / 9.0) * (input_temp - 32);
}

float C_to_F(float input_temp)
{
    return (9.0 / 5.0) * (input_temp)+32;
}

float get_input(void)
{
    float input = 0;
    scanf_s("%f", &input);
    return input;
}

int main()
{
    int option = -1;
    float input_temp = 0.0;

    printf("Temperature conversion Calculator!!\nPlease select an option:");
    printf("\n1.) F to C\t2.) C to F\t3.) off\n\n");

    while (option != OFF) {

        printf("Option: ");
        option = get_input();

        if (option == F_TO_C || option == C_TO_F) {
            printf("Temp: ");
            input_temp = get_input();
        }

        switch (option) {
            case F_TO_C:
                printf("Celsius: %f\n", F_to_C(input_temp));
                break;
            case C_TO_F:
                printf("Fahrenheit: %f\n", C_to_F(input_temp));
                break;
            case OFF:
                puts("OFF"); // No need for printf()!
                break;
            default:
                puts("Incorrect input, try again"); // No need for printf() as well!
                break;
        }
    }

    getchar();
}

Also, be sure to check chux's answer. It contains even more useful tips and tricks to improve your code. Especially scanf_s() checks, option = -1 change and math simplification.


Implementation of Stack using Linked List

You leak every single node you pop. You need to delete the node.

You should add move and emplace push overloads. So that non-copyable T can be stored.

you check against "overflow" by testing top is less than -1. However signed overflow is undefined behavior and if you ever had more than 2 billion items in your stack you probably ran out of ram earlier. You can check if the stack is empty by testing if head is nullptr. So top isn't really necessary.

For every operation you seek the end of the stack, that is not necessary at all.

template<class T>
void Stack<T>::push(T val){
    top++;
    Node *node=new Node(val);
    node->next = head;
    head=node;
}

template<class T>
T Stack<T>::pop(){
  if(stack_empty()==true)
    std::cout<<"Underflow"<<std::endl;
  else{
    top--;
    Node *node=head;
    head = node->next;
    T tmp = std::move(node->data);
    delete node;
    return tmp;
  }
}


CSV file reader in PHP that supports large files (>15k lines)

Performance

As performance is your main concern, let's face this first. To complete the example CSV-file with ~36k lines your original script needs around 139s*.

The main bottlenecks are in_array:

if (!in_array($record,$return_waarde)) {}

and array_combine:

$return_waarde[] = array_combine($header_trimmed, str_getcsv(utf8_encode($record), ';'));

As you want an associative array, we can't get rid of array_combine but we can improve the very expensive and slow test from in_array.

Idea

Instead of checking the fastly growing and complex result-array for existence of the newly created associative array, you can do this:

create a second array
create a hash of the current dataset/row
check this array's keys for the existence of the latest hash using isset, which is faster than in_array
only if the hash is not found, store it, run array_combine on the row and append the result as well

Result

while (false !== ($data = fgetcsv($handle, 1000, ','))) {
    $hash = md5(serialize($data));

    if (!isset($hashes[$hash])) {
        $hashes[$hash] = true;
        $values[] = array_combine($headerUnique, $data);
    }
}

With this improvement the script processes all 36k lines in ~0.5s now*. Seems a little faster. ;)

Unique entries in the result

Even though this is solved by using the hash now, let me point out a flaw in your logic:

if (!in_array($record, $return_waarde)){
    $return_waarde[] = array_combine($header_trimmed, str_getcsv());
}

This will never find any duplicates, because you check for existence of the indexed array $record but afterwards you insert a different associative array.

Unique header names

In the beginning you create unique names for duplicate entries in the header row:

if(!in_array($value, $header_trimmed)){
      $header_trimmed[] = $trim;
  } else {
      $header_trimmed[] = $trim . "1";
  }

If you have a column name more than two times, you'll end up with this, probably unintended, result:

['column', 'column1', 'column1']

You can create a function to make the names truly unique, e.g.:

function unique_columns(array $columns):array {
    $values = [];

    foreach ($columns as $value) {
        $count = 0;
        $value = $original = trim($value);

        while (in_array($value, $values)) {
            $value = $original . '-' . ++$count;
        }

        $values[] = $value;
    }

    return $values;
}

This will result in

['column', 'column-1', 'column-2']

Return value of read_cvs

Currently your function read_csv() does return either a string or an array. The function should always return an array. You can even make the parameter- and return-value-types more strict:

function read_csv(string $file): array {}

Also try to exit early, when something went wrong instead of nesting if-statements. If you actually want to do something, if an error occurs, throw an exception:

if (!$file) {
    throw new Exception('File not found: ' . file);
}

Final result

Finally let's make this function more versatile by adding the line length and delimiter as optional parameters.

function read_csv(string $file, int $length = 1000, string $delimiter = ','): array {
    $handle = fopen($file, 'r');
    $hashes = [];
    $values = [];
    $header = null;
    $headerUnique = null;

    if (!$handle) {
        return $values;
    }

    $header = fgetcsv($handle, $length, $delimiter);

    if (!$header) {
        return $values;
    }

    $headerUnique = unique_columns($header);

    while (false !== ($data = fgetcsv($handle, $length, delimiter))) {
        $hash = md5(serialize($data));

        if (!isset($hashes[$hash])) {
            $hashes[$hash] = true;
            $values[] = array_combine($headerUnique, $data);
        }
    }

    fclose($handle);

    return $values;
}

* For testing I used an example CSV-file with over 36.000 lines from the site SpatialKey. I duplicated a few column names and added at least one duplicate line. My environment is the latest MAMP running PHP 7.1.1. The time was measured using: $start = microtime(true); $x = read_csv('test.csv'); print microtime(true) - $start;.


It actually works...

After thinking a bit I believe I figured out why this thing works.

This paragraph is inteded purely for people who thinks that the question is invalid due to broken code.

It is invalid. Yes. In terms of standard C++. But undefined behavior doesn't mean that the behavior can be defined on some platform when using some compiler. By defined I don't mean accident. By defined I mean reproducible and consistent behavior. Compiler can do copy elision from call site to function site, so that the function will receive the same thing in terms of memory location as on the call site!

But it is non standard conformant compiler. Or is it? The thing is that taking the address of the local variable and using it somewhere else is undefined behavior, so why miss such a great opportunity to optimize code? I believe these are the thoughts that came to mind of the compiler implementer.

May be it is possible to verify that using disassembly.

Code Review:

As I mentioned in the comment, the design is strange mix of C and Java/C#. Class is used, but parent and data are left public. Data is taken by value (or maybe by reference was intended?). So there are lots of strange things happening here aside from the undefined behavior.

Ambiguous model

After a few minutes thinking I couldn't find out what is meant by the Quadtree.

Obsolete design

C++ now has smart pointers. I've seen on cppcon 2016 unique_ptr<> compiling down to the version with raw pointers. It was simple case, but I believe more complex cases will behave the same. It might complicate design a bit, but it will make it leak free by default (well, the program can crash though, due to double free, but it is better than memory leak in my opinion).

using declarations are now preferred to typedefs.

using Quadrants = std::array<Quadtree, 4>;

No clear preference of value/reference

The array is stored by pointer. I know that may be copy elision is intended, but the code leaves lifetime management of the nodes to the caller, which potentially makes the usage very hard and error prone. Famous Scott Meyers said: "Make interfaces easy to use correctly and hard to use incorrectly". Very sound advice and should be kept in mind when designing public interfaces.

There is a thing called move constructor in C++11, but on std::array<> it will behave the same as if it is by element copy, so rip it. Some wrapper over std::vector<> might be preferred.

Non idiomatic C++

In general, I would say that the code doesn't look like C++ in the form that I see here or on the web by acknowledged people. Though I would say that it is also important to know when idiomatic C++ can't do the job wanted, but idiomatic C++ should be preferred if it possible.


Checking whether customers in a dataframe have social media accounts

Few things to note here:

Columns:

email_results=['facebook','foursquare','instagram']
phone_results=['facebook','linkedin','twitter']

Conditions:

c1=df.phone.isna()&df.email.notna()
c2=df.phone.notna()&df.email.isna()

Method1

You can try and replace if else conditions with np.where , also take a look at np.select() if you have elif conditions:

df[email_results]=np.where(c1[:,None],'Found Social Media',df[email_results])
df[phone_results]=np.where(c2[:,None],'Found Social Media',df[phone_results])
print(df)

Method2

Or you can take a look at df.mask():

df[email_results]=df[email_results].mask(c1,'Found Social Media')
df[phone_results]=df[phone_results].mask(c2,'Found Social Media')
print(df)


Extracting all-caps variables from string expressions

Some observations:

It seems that std::adjacent_find essentially already does what you want, which is extracting all continuous sub-strings consisting of uppercase letters.
Removing duplicates from a vector might be fine, but you can also avoid this completely by inserting the found elements into a std::set. I suspect that the number of unique variables is always small, so this is a cleaner approach.
There is no reason for isCapital to be a member function. Instead, it should be a free function. Remember that interfaces should be complete but minimal. But in fact, there's no reason for the function in the first place: the standard already has std::isupper that we should rather use.

So with these in mind, we can re-write your function to e.g.,:

std::vector<std::string> get_variables(const std::string& str)
{
    std::set<std::string> vars;

    for (auto first = str.cbegin(); first != str.cend(); )
    {
        auto var_end = std::adjacent_find(first, str.cend(),
            [](char a, char b)
        {
            return std::isupper(static_cast<unsighed char>(a)) !=
                std::isupper(static_cast<unsigned char>(b));
        });

        if (var_end != str.cend())
        {
            ++var_end;
        }

        if (std::isupper(static_cast<unsigned char>(*first)))
        {
            vars.insert(std::string(first, var_end));
        }

        first = var_end;
    }

    return std::vector<std::string>(vars.cbegin(), vars.cend());
}

Notice that we've cast char to unsigned char before the call to std::isupper (thanks to Deduplicator for explaining this to me). The reason is that std::isupper takes an argument of type int which must be in the range of unsigned char (or special value EOF, -1). Unfortunately, a plain char has either the range of signed char or unsigned char, so we perform a cast to confer to this common convention of character classification functions.


I don't know why compute_moving_average takes a Box, much less why it would take a reference to one.
Prefer &[T] over &Vec<T>.
Why use floating point division with truncation when integer math does same, should be faster, and is shorter to write?
Don't use an iterator on a slice if you are just going to pull out the nth value; just index. Also bakes-in the unwrap.
I'd use Iterator::map and Iterator::sum.
Preserve the sum as an integer until the last moment, then convert it to floating point. This may or may not be a good idea depending on the input data.
Learn and love all the methods on Option and Result. For example, Option::map replaces the 4 lines of an explicit match.
merge_moving_average seems more trouble than it's worth; just inline it and provide better variable names.
There's no need to create a Vec; just pass in a slice of an array.
Can directly pass compute_moving_average with map, no closure or arguments needed.
It's more idiomatic to use |&a| in the closure argument instead of *a in the body when they are equivalent.
Iterator::inspect is more of a debugging tool than anything; use a for loop to drive an iterator for side effects.

fn compute_moving_average(window: &[(u32, u32)]) -> (u32, f32) {
    let window_size = window.len();

    let current_year = window[window_size / 2].0;

    let sum: u32 = window.iter().map(|&(_, val)| val).sum();
    let sum = sum as f32 / window_size as f32;

    (current_year, sum)
}

fn extract_moving_average_for_year(year: u32, moving_average: &[(u32, f32)]) -> Option<f32> {
    moving_average
        .iter()
        .find(|(yr, _)| yr == year)
        .map(|&(_, val)| val)
}

fn main() {
    let vec = [
        (2003, 4),
        (2004, 6),
        (2005, 5),
        (2006, 8),
        (2007, 9),
        (2008, 5),
        (2009, 4),
        (2010, 3),
        (2011, 7),
        (2012, 8),
    ];

    let moving_average = vec
        .windows(5)
        .map(compute_moving_average)
        .collect::<Vec<_>>();

    let moving_average = vec
        .iter()
        .map(|&(year, val)| (year, val, extract_moving_average_for_year(year, &moving_average)));

    for a in moving_average {
        println!("{:?}", a);
    }
}

Thoughts:

It would be interesting to see an implementation that doesn't use windows, but instead is based on an iterator.

If you know your slice is sorted, a binary search might be more efficient.


Linear search algorithm template implementation

Returning int is dubious; it unnecessarily narrows the range of possible return values. Consider retuning an iterator.
The line if (_list[i] == _item) implies that _list must provide an operator[](int), which is very restrictive. A linear search is just like its name implies, linear. It is expected to work on any linear collection, e.g. forward iterator (maybe even on input iterator).
The class sLinear exposes one public method, and keeps no state. There's no reason to make it a class. A standalone

template <typename I>
I findItem(I first, I last, I::value_type value) {
    ....
}

will do as well.
while (_list != nullptr) is very strange. _list never changes; why do you want to loop?

PS: Could you explain a rationale for returning i+1?


I think the problem is you’re starting with an implementation (Entity Framework) and then trying to bind this to two common design patterns – Unit Of Work and Repository.  The Entity Framework handles these two patterns and combines them together in Microsoft’s own implementation – they couldn’t actually work independently, for example you couldn’t just take a DbSet (Repository) and get a Product (entity) without instantiating the context (Unit Of Work).

These design patterns exist so they can be easily replaced within your application without changing much code, but if your IUnitOfWork is returning a DbSet<T> repository and you decide to read your Product entities from a local file instead of a database then you’re not really going to be able to implement this with your current abstraction.

IUnitOfWork should be strongly-named to the domain context – this is actually containing names of repositories which are specific to the domain context i.e. ProductMaster.  You could have IShopUnitOfWork derive from IUnitOfWork (which only has Commit as this is reusable in different domain contexts)
Your IUnitOfWork will get progressively bigger as you add new repositories and stored procedure definitions and I fear you’ll break the Interface Segregation Principle because of this.
I believe your repositories should actually contain the “query” calls specific for an aggregate root entity rather than your Unit Of Work – by putting it in the Unit Of Work you’re giving it two responsibilities:

i.  Maintaining the register of objects to be persisted

ii. Knowing how to authorise a user (in your example) along with all of the other stored procedure calls you’ll have

Therefore this will violate the Single Responsibility Principle

Furthermore SP_UserMaster should probably exist in the User repository as its specific to that domain entity.  Again this is strongly-named to imply a database call with a stored procedure – what if this was to be changed to a web service call?

With these caveats in mind it’s going to be hard to change your implementation to work this way with Entity Framework as Microsoft has taken the design patterns and implemented it in their own way with Unit Of Work and Repository mingled together - I'm not saying this is wrong its just the way they've decided to do it.  The main benefit of having these abstractions in this context is the benefit of being able to create stubs in unit testing so you’ll be mocking stored procedure and query calls without hitting the database.


Function that returns the number of items that appear more than once

The name count is too vague for such a specific task.  I suggest countReappearingChars instead.

Avoid big blocks of variable definitions.  Code is easier to read and maintain when variables are declared and initialized near where they are used.  For example, with a block like this, it's harder to notice that result is never used.

nArr does not need to be an array.  You can just keep a count.

obj is cryptically named.  I suggest calling it charCount.

var arr = str.split("") is unnecessary; you can iterate over str directly.

"occurances" is misspelled in the comment.

This line is hard to read:

obj[letter] === undefined ? obj[letter] = 1 : obj[letter] += 1;

It would be more clearly be written using if-else, and therefore should be:

if (obj[letter] === undefined) {
    obj[letter] = 1;
} else {
    obj[letter] += 1;
}

I would consider your ternary operator to be abusive, since you are not using it as as an expression.  In contrast, this expression could be considered appropriate, since the right-hand side of the assignment is an expression:

obj[letter] = (obj[letter] === undefined) ? 1 : obj[letter] + 1;

But that still looks cumbersome.  If you want to get clever with it, you could use || 0, as shown below.

function countReappearingChars(str) {
    // Count all occurrences in str
    var charCount = {};
    for (var i = 0; i < str.length; i++) {
        charCount[str[i]] = 1 + (charCount[str[i]] || 0);
    }

    // Loop over and filter charCount
    var result = 0;
    for (var char in charCount) {
        if (charCount[char] > 1) result++;
    }
    return result;
}


Assuming this code is solely for learning purpose, there are several main issues

to be honest, a function that returns ERR_DX_FILE_DOES_NOT_EXIST when I request an object looks a bit weird. I don't even know how to use it. Should I wrap every call to a function in a condition that checks the returned value? Or what else I am supposed to do with this string? Consider using errors/exceptions in case of error.
a race condition issue. you can have this file malformed if two parallel processes would try to write at the same time. Consider use file locks
an obvious memory issue - the bigger the file is, the more RAM does it take to process. PHP can let you to read a file line by line without memory overhead
such a clumsy format as keyname__=__urlencode(serialize(value_of_key)) doesn't seem to be very reliable. For such a toy storage I would rather use json format, to ease the search/key access.


Checking if the entries of a map exist in another map

I believe you will find the standard library has the appropriate functions:
Includes

Includes tests whether one sorted range includes another sorted range. That is, it returns true if and only if, for every element in [first2, last2), an equivalent element [1] is also present in [first1, last1) [2]. Both [first1, last1) and [first2, last2) must be sorted in ascending order.
The two versions of includes differ in how they define whether one element is less than another. The first version compares objects using operator<, and the second compares objects using the function object comp.

You can see all the algorithms here
Your code would look like this:
#include <algorithm>
#include <iostream>
#include <map>

int main()
{
    std::map<int, std::string> a;
    std::map<int, std::string> b;

    a[0] = "0";
    a[1] = "1";

    b[0] = "0";

    std::cout << "b ⊆ a? " << std::includes(a.begin(), a.end(), b.begin(), b.end()) << " (should be 1)\n";

    b[1] = "1";
    std::cout << "b ⊆ a? " << std::includes(a.begin(), a.end(), b.begin(), b.end()) << " (should be 1)\n";

    b[2] = "2";
    std::cout << "b ⊆ a? " << std::includes(a.begin(), a.end(), b.begin(), b.end()) << " (should be 0)\n";
}


Is this a good way to go? How can I improve the class? Any suggestions in general?

Right now, your class doesn't really add any functionality to PDO. It basically just renames it's methods (to names other programmers will now have to get familiar with), and reduces it's flexibility and functionality.

The only advantage you gain currently is that you save typing SELECT, FROM, and WHERE. I don't think that this is worth it.

Misc

use spaces around . for increased readability.
sth is a pretty common name, so it isn't that bad, but something like selectStatement would be a lot clearer. And what does dbh stand for?
I would probably rename get to columns (and I would probably make it an array so it's easier to use).


I'd move all of those message into an external resource file something like:

<message id="file.open.fail" type="warning" icon="error" delay="5">
    Error. Could not open file:<tt>{filename}</tt>
</message>

Then I'd simply pop the message using:

self.infobar('file.open.fail', filename = filename)

That should cleanup the calls to infobar, and make it easier to do things like provide strings for a different language.

EDIT:

Quick hack of an implementation

from xml.etree.ElementTree import XML, tostring

# of course, you'd want to load this from an external file
message_file = XML("""
<messages>
    <message id="file.open.fail" type="warning" icon="error" delay="5">
        Error. Could not open file:<tt>{filename}</tt>
    </message>
    <message id="file.open.good" type="warning" icon="error" delay="5">
        File opened!
    </message>
</messages>
""")

messages = {}
for message in message_file.findall("message"):
    messages[message.attrib['id']] = message

def message(id, **kwargs):
    message_detail = messages[id]
    text = ''.join( tostring(node) for node in message_detail)
    return text.strip().format(**kwargs)

print message('file.open.fail', filename = 'file.txt')
print message('file.open.good', filename = 'file.txt')

Doesn't try to handle type/icon/delay. You'll probably also want to consider how you want to do whitespace.


Counting unordered factorizations with distinct parts

I took a couple passes (gist) at this and managed to improve the style a bit, but I couldn't move the needle on performance at all.

Style

My thoughts and justifications on important changes are written as in-line comments below.

module Main where

import qualified Math.NumberTheory.Primes.Factorisation as Factorisation
import           Data.Numbers.Primes                                     (isPrime)
import           Data.Set                                                (toAscList)

duf' :: Integer -> Integer -> [[Integer]]
duf' _ 1 = [[]] -- Underscores in place of unused variable names
duf' 1 _ = [  ]
duf' 0 _ = [  ]
duf' m n | isPrime n = if m < n then [] else [[n]]
         | otherwise = concatMap (\x -> map (x:) $ duf' (x-1) (n `div` x)) -- Sectioning cons operator
                                 (tail . takeWhile (<= m) $ divisors n) -- Reflowed for legibility
  where
    divisors = toAscList . Factorisation.divisors -- Locally bound to decrease datatype mismatch line noise

duf :: Integer -> [[Integer]]
duf n = duf' n n

pd :: Integer -> Int -> Int
pd n k = length . filter ((== k) . length) $ duf n -- Function composition for ordering

Some reorganizing of layout in duf' made it a lot more comprehensible.

Performance

After rewriting duf', I noticed that the inner lists it returns are only ever really used for their length, so I came up with this version that tosses out the actual elements in favor of keeping a tally whenever a new element would be added instead.

duf' :: Integer -> Integer -> [Int]
duf' _ 1 = [0]
duf' 1 _ = [ ]
duf' 0 _ = [ ]
duf' m n | isPrime n = if m < n then [] else [1]
         | otherwise = concatMap (\x -> map (+1) $ duf' (x-1) (n `div` x))
                                 (tail . takeWhile (<= m) $ divisors n)
  where
    divisors = toAscList . Factorisation.divisors

duf :: Integer -> [Int]
duf n = duf' n n

pd :: Integer -> Int -> Int
pd n k = length . filter (== k) $ duf n

Unfortunately, this doesn't net us any wins in run time as I only really smeared out the inner call to length from filter in pd across duf' (this is less idiomatic, in my opinion). One potential positive is that this version may be more space efficient due to not keeping lists of elements around when all we really care about is the list spine anyway. I wasn't testing for that though, so I don't have any cold hard facts at hand and I suspect you'd have to use an argument strict version of (+1) to prevent building up chains of thunks before realizing any real decrease in memory.


Extracting a conversation from a Skype sqlite database

First off, you should be using argparse for any argument parsing more complicated than python script.py arg1. It has automatic parsing of sys.argv, allow default values, custom help messages, custom argument types, prints a help message if any arguments mismatch and exits, ...

import argparse
import os.path
import sys

def is_file(f):
    if os.path.isfile(f):
        return f
    raise OSError("{} does not exist".format(f))

parser = argparse.ArgumentParser(descr="Skype history reader")
parser.add_argument('db_path', type=is_file, help="Database path")
parser.add_argument('partner_id', help="Partner to show history of")
parser.add_argument('output_path', help="Location to save output to", default="-")
args = parser.parse_args()

args.output_path = args.output_path or "{.partner_id}.txt".format(args)
output = sys.stdout if args.output == "-" else open(args.output_path, "w")

For your SQL, you should be using Prepared Statements (or the Python implementation of it)

cursor.execute("""
    SELECT timestamp, from_dispname, body_xml
    FROM Messages
    WHERE dialog_partner = ?
    ORDER BY timestamp
    """, partner_id)

This needs paramstyle='qmark'. Otherwise use %s instead of ?. It ensures that partner_id is correctly escaped, so you can't do SQL injection with something like

partner_id = "'; DROP TABLE Messages; SELECT * FROM USERS '"

(Not sure this exact string would work, but something similar to it would be able to delete your whole database. Or print all your chat partners. Or add swearwords to all your messages.)

You should always close your files, otherwise you could get file corruption. Normally I would advise using with open(file_name, "w") as output:, but here we need to also use sys.stdout. Therefore you need to add an explicit output_file.close() at the end, ideally by wrapping your code in a try...finally to ensure it is also closed if some code in between raises an exception.

Likewise, you should close your connection to the db at the end:
connection.close().


When you find yourself having a lot of duplicate code, you should factor out the commonalities. In this case, we have four separate directions we need to consider. So let's write one function that considers one direction:

def append(dx, dy):
    for i in itertools.count(start=1):
        newx = x + dx*i
        newy = y + dy*i
        sq = (newy, newx)

        if 0 <= newx < 8 and 0 <= newy < 8:
            if not board[sq].isupper():
                out_squares.append(sq)
                if board[sq].islower():
                    break
            else:
                break
        else:
            break

And then just call it 4 times:

for dx in (-1, 1):
    for dy in (-1, 1):
        append(dx, dy)

Full solution:

def bishop(insquare):
    '''
    Gets all legal moves for bishop on insquare
    output is a list (outsquares) of indices of possible squares
    '''
    out_squares = []
    y,x = insquare

    def append(dx, dy):
        for i in itertools.count(start=1):
            newx = x + dx*i
            newy = y + dy*i

            if 0 <= newx < 8 and 0 <= newy < 8:
                sq = (newy, newx)
                if not board[sq].isupper():
                    out_squares.append(sq)
                    if board[sq].islower():
                        break
                else:
                    break
            else:
                break

    for dx in (-1, 1):
        for dy in (-1, 1):
            append(dx, dy)

    return out_squares


Square root approximations, implemented two ways

In version 1, you are testing the difference of the square is within 0.001.

The square root of 9.001 is 3.000167

In version 2, you are testing the difference of the square root part. When you square it, the error becomes bigger.

The square of 3.001 is 9.006001

One error:

You need to get rid of the

if(guess*guess-n<epsilon)

at the end of version 2, it will not print for positive differences > 0.001 e.g. for 3.001 9.006001 is 0.00601 bigger.


Design class to handle calls for support functions

I like the Employee class with the built-in Manager chain.
I think Call class should be "dumb" like the Employee. The methods seem like call processing - what the CallManager should be doing.
Id say part of the "call handing process" is in the CallManager and part of it is in Call class. Broken apart like this it's hard to discern/follow the flow of a call-handling.
Should you implement queues? A queue of Calls to model lots of calls coming in before they can get allocated.
The code has allocation and "isFree" as 2 separate things. This suggests to me that we could have a Employee.CallQueue for allocated calls, then set IsFree = false when he picks up the phone.
Also an Employee.CallQueue of assigned calls. The code suggests that allocation and handling are 2 separate things
In ReceiveAndAllocateCall.FindFreeEmployee() could return null so we need code to handle that. Maybe that when the call goes into a waiting queue.

public class CallManager {
     . . .

    // call processing
    call1.AllocatedTo = FindFreeEmployee();

    // what to do if AllocatedTo is null?

    call1.AllocatedTo.IsFree = false;
    call1.IsHandled = false;

    // I see `IsHandled` as a `Call` property. It will persist if we
    // pass it to the manager. As is, `IsHandled` disappears when `HandleCall()` ends and we don't know if the call is handled anymore.

    while (! call1.IsHandled) {
     // Write custom logic to handle the call & set the value of isHandled
     if (! call1.isHandled) {
         if (call1.AllocatedTo.Manager != null) { call1.AllocateTo = AllocateTo.Manager
         }else{ break;}
      }
    } // while

    // if IsHandled == false still, what to do? Hang up and send them a lollypop I guess.

The 1st line, calling FindFreeEmployee() might best be done outside of, or somewhere else in CallManager Imagine a complex process for deciding how to pair calls to employees. Then pass that pair into CallManager, and all call manager does is process the call. - Separation of Responsibilities.


No. Your function needs to handle the empty list too. If your implementation supports unless, use this:

(define (for-each f l)
  (unless (null? l)
    (f (car l))
    (for-each f (cdr l))))

Otherwise, the R5RS-compatible version would be:

(define (for-each f l)
  (cond ((not (null? l))
         (f (car l))
         (for-each f (cdr l)))))

Granted, the implicit begin behaviour of cond is not explained until Chapter 3. So if you want to avoid using that, here's a similar version that uses let to simulate begin:

(define (for-each f l)
  (cond ((not (null? l))
         (let ()
           (f (car l))
           (for-each f (cdr l))))))

Now, here, too, the let body is an implicit begin. If you want to work around that, too, then bind the result of the side-effect to a dummy variable:

(define (for-each f l)
  (cond ((not (null? l))
         (let ((unused (f (car l))))
           (for-each f (cdr l))))))


Given a string of brackets, return the count of brackets that are properly matched

We dont need close variable if we can decrease open by 1 when close bracket is found.

public class MatchBrackets{

    public static int matchBrackets(String brackets){

      int open = 0;
      int count =0;

     for(int i=0;i<brackets.length();i++){
        if(brackets.charAt(i)=='('){
        open++;
        }else if(brackets.charAt(i)==')'){
         open--;
        }
        if(open<0){
        count++;
        open++;
     }
  }
  return count+open;
}

  public static void main(String[] args) {

  System.out.println(matchBrackets("())("));
  System.out.println(matchBrackets("(((())))"));
  System.out.println(matchBrackets("))))"));
}}


Displaying records from a MySQL database

Dependency injection

Use dependency injection everywhere you can

public class AuthorsController : Controller
{
    private readonly bookisticsEntities _booksEntities;

    public AuthorsController(bookisticsEntities entities)
    {
        _booksEntities = entities;
    }

    public ActionResult Index()
    {
        //all authors on one page can be slow, paging?
        //.ToList() is useless here
       return View(be.authors);
    }

    //default value is not neccessary becouse 0 is an invalid value
    public ActionResult Books(int author_id)
    {
        var author = _booksEntities.authors.SingleOrDefault(a => a.id == author_id);

        if (author == null)
        {
            return HttpNotFound();
        }

        /*var books = from b in be.books
                    join a in be.authors
                    on b.author_id equals a.id
                    where b.author_id == author_id
                    select b;

        ViewBag.author_name = aut.name;*/

        //pass the author to the view and in the view you can iterate on the author.Books collection
        //if the foreign keys are correct in the database
        //or you setted everything correctly in code first approach
        return View(author);
    }
}

Now the controller expects a bookisticsEntities instance as constructor parameter but the default controller factory in the MVC framework only can use a parameterless constructor so you need a solution for this; use a dependency injection container like Ninject! It's easy to use available through Nuget.

N-tier

It seams to me your application missing one or two (maybe three) application level becouse currently you managing the database directly which is not a best practise. You have to build at leas one level between the MVC and the dataaccess tier which is called business layer (or two: a service layer and under that a business layer). In this way you controller will expect one or more different type of object instances but not your database model!

If you are done whith this you can use simplified models in your application, for example in the Books action method you can use a model which can contain the author's name, identifier and the books also (books can be simplified also).

Learn Entity Framework

Read a lot about how EF works. :)


I agree with @Reinderien that this shouldn't be a class. You can see evidence for this in your constructor:

def __init__(self, input_list:list)->list:
    self.input_list = input_list
    self.__iter__()

You are constructing the object (and calling the constructor) simply to call self.__iter__(). There is no reason for the creation of an object here just to sort the list. If you needed to maintain some state between sorts or something (I'm not sure why you would though), then it may be appropriate.

I'll also point out, you're attempting to violate at least two "contracts" with your usage of __init__ and __iter__:

__init__ must return None:

  no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.

Now, you aren't actually returning anything, but your type hinting is saying that you are. If you're going to use type hinting, the hints should make it clearer what types are involved, not make false claims.
__iter__ should return an iterator:

  This method should return a new iterator object that can iterate over all the objects in the container

The problem is, you're returning a list, and a list isn't an iterator, it's an iterable (it has an iterator). This isn't just a theoretical problem. Note how this can bite you:

class T:
    def __iter__(self):
        return [1, 2, 3]

for n in T():
    print(n)

# TypeError: iter() returned non-iterator of type 'list'

Use of "dunder" methods can be helpful for writing clean code, but only if you aren't abusing them. Make sure to read the documentation and understand the purpose and contracts of methods before attempting to use them.

And on the subject of type hints, you could make use of a TypeVar to allow the type checker to see the consistency between the element types going in and out of your sorting function. After making your class into a standalone function, you basically have:

def selection_sort(input_list: list) -> list:

The problem with this is, it doesn't tell the checker what the relationship is between the types of elements in input_list and that of the list that selection_sort returns. This can lead to subtle issues where it won't be able to help you with types:

lst: List[int] = [1, 2, 3]
sorted_list = selection_sort(input_list)
x = sorted_list[0]  # It has no idea what type x is

You can fix this by introducing a TypeVar that tells it that the element type remains consistent. I'm also changing from using list to List since list doesn't seem to support generics yet:

from typing import List, TypeVar

T = TypeVar("T")

# The sort returns the same element type T that it received
def selection_sort(input_list: List[T]) -> List[T]:
    . . .

Now, it is able to infer the type of x, and can give you better completions and type warnings.


TL;DR

Be as specific as you can:

When naming functions,
And when setting up loops.

Details:

Here's what I've noticed in your code, line-by-line:

def run(input)

Avoid common names for your functions. While it's not always possible to prevent having the same name as functions from other modules (there are methods to deal with that), naming a function run is asking for trouble. For example, a commonly used command in Python test-suites is also run.

Your function name should match as closely as possible the specific goal of the function. e.g. maybe call it insertion_sort.

for i in range(1,len(input)):

Try to use the most specific iterators possible.

The general construction for i in range(... gets used a lot where it doesn't have to be. Any time you see it, there is usually a better way iterate, whether using a list comprehension, using Itertools, or other more specific methods. In your case, replacing for i in range( with for i in input results helps a lot (as in my example below).

The next two lines j = 1 and saved = input[i] are only there to convert i from the non-specific `for I in range (...' to the values you actually want. They can be elimited by changing how the loop is set up.

    while(j > 0 and input[j-1] > saved):

The same goes for your while loop. You will never need a i+=1 (or j-=1) to increment a loop in Python. It's always best to think of what information the inside of the loop needs, and set up an iterator, list comprehension, or for loop that immediately provides that information.

Here is a modified version of your code, to show what I mean about being specific with loops:

def insertion_sort(input):
    for i,n in enumerate(input):
        ins_pos = 0               # default location to insert n
        for j,m in reversed([r for r in enumerate(input[:i]])):
            if m > n:
                ins_pos = j + 1   # insert n one position after first larger number found
                break
        input.insert(ins_pos, input.pop(i))
    return input

Once inside the loop, you only need:

i and j, the indices of the values to pop and insert.
n and m, the values to compare.

Once you know what the inside of the loop needs, set up the loop statements (e.g. In my example, for i,n in enumerate(input), and for m in reversed(input[i])) so they return only what is needed. This eliminates the extra lines in your code. Also, after this modification, the purpose of each loop is more clear.

    input.insert(j,input.pop(i))

PEP8 specifies spaces between arguments in function calls.

And a note on the last line:

Try not to modify a list that is the source of your iterator.

In general, it's a bad idea to modify the same list that is being iterated over. Your example only works because the pop and insert functions get applied to the parts of the input list that have already been read through by the iterator. If you need to do it in future, be aware of why this works, and how other examples of the same practice might go wrong. I've assumed that part of your spec is to modify the list in place, so I've left it how it is.

Performance:

Nice work with eliminating the extra slice steps. Re-writing the list with each step in the inner while loop is indeed more expensive than just comparing values and moving on. However, both pop, and insert within a list are both \$\mathcal{O} (n)\$, not \$\mathcal{O} (1)\$, sad but true. There may be a small speed-up of a constant factor, doing away with the slices, but both your versions of insertion sort are ultimately limited by the time complexity of the algorithm itself, which is \$\mathcal{O} (n^2)\$, where n is the length of the list.

This line:

    saved = input[i]

Won't change anything as, in Python, this sets up saved as a pointer to the value in input[i], rather than making a copy and storing it in saved. You could explicitly force a copy, but this would probably be self-defeating, as reading an index from an array is no more expensive than accessing any other int.


Having individual setters has a couple of advantages:

A dedicated setter allows you to put dedicated validations for these properties. You could obviously put them in the bulk setter as well, but that will make the bulk setter large and unwieldy very quickly. You want methods to do one dedicated thing instead. That keeps them maintainable.

Dedicated setters clearly communicate which properties can be set. With a bulk setter, it needs documentation or a look at the source code to learn what I can legally set. I usually don't want to look at your class code. I just want to look at the public API and understand how I can use that class.

That's not to say bulk setters are bad per se. If you know folks are likely to set two or more values after another because they naturally go together, you could allow for a setFooAndBar($foo, $bar) method. But as you can see, that's still much more explicit than a generic set(array $data). Also one could argue that if you need to set arguments that naturally go together, you rather want them to be in an object of their own and pass that object then.

On a side note: Your bulk setter will create properties on the fly for those keys that are not properties in the class. While you could consider that a feature, it makes debugging harder because a developer has to know the object's current state at runtime to know what properties it has.

On another side note: a base class is usually a code smell. It tends to amass unrelated functionality and turn in a God object quickly. It also hampers reuse because all your classes will depend on it then.


Compile SASS files in a directory via Gulp.js tasks, one of which produces logging output

Interesting question;

some review remarks before addressing your actual question:

You never seem to pass filePath to src but use path["sass"] instead
I always suggest to pipe your console.log calls through a log function that accepts a severity parameter so that you can customize the level of logging, but that's probably overkill for Gulp

I would add a new function that does nothing, called doNothing() and then up front point an output function to either doNothing() or console.log().

function doNothing(){
  //Do nothing
}

function CompileSass(filePath) {
    const time = process.hrtime();
    const out = (filePath === "string") ? console.log : doNothing;
    out("compiling now");

    return src(path["sass"])
        .pipe(sass({outputStyle: "expanded"}))
        .on("end", () => {
            out(`Compiled '${filePath}' now`);
        })
        .pipe(dest("css"))
        .on("end", () => {
            out(`Finished compiling ${prettyTime(process.hrtime(time))}`);
        });
}

exports.default = () => {
    watch(dir).on("all", (directory) => {
        CompileSass(directory);
    });
};

exports.sass = series(CompileSass); // in fact, there is other tasks in series function's argument


LeetCode: N-ary Tree Level Order Traversal

Time and space complexity are just the number of nodes in the graph. You can't do better than this with the API given. If the API were open to negotiation, I'd consider IEnumerable<IReadonlyList<int>>, which would permit better memory characteristics for some trees (e.g. if the level-width stays reasonably constant rather than, say, growing exponentially). There is also no need for this to be an instance method.

I don't like this:

if (root == null)
{
    return result;
}

No-where in the spec is it said that a null input should produce a null output, and this is a design decision which needs to be documented. Without something saying that null should map to null, I'd much prefer an ArgumentNullException which doesn't obscure any assumptions. If this behaviour is wrong, then you'll know the moment you try to use it. If returning null is wrong, it might take you a while to find out where your code messed up. Either behaviour warrents inline documentation. I'd also prefer these sorts of checks were performed straight-away, so that they can't be lost in the other clutter, and in this case avoid unnecessarily allocations.

Similarly, is it specified that Node.children can be null, and that this is supported? If not, then I'd be inclined to remove the check, as it will simplify the code and cause it to blow up if this assumption is violated, forcing the consumer to address the null rather than hoping the behaviour is as expected. (Ideally any constraint would be enforced by the Node class, and I appreciate that isn't yours to change).

Q isn't a great variable name: it describes what the thing is, which can be confused with its purpose; and because it is capitalised, it feels like a member variable.

It would be nicer if the test methods were separated from the functionality. Currently, anyone trying to find aryTreeLevelOrderTraversal.LevelOrder will be confronted with N_aryTreeLevelOrderTraversalTest in their intellisense

Personally I don't like this sort of 'staged' consumption of a queue; it just feels fiddily. In this case you can avoid it completely (and save memory) by enumerating over the previous level when you construct the next. This can make the code more-compact, and harder to break (e.g. someone might 'helpfully' inline qSize thinking it's clearer only to break the code completely) with fewer variables whereof to keep track. With a bit of LINQ, we can write (untested):

List<int> level = new List<int> { root };
while (level.Count > 0)
{
    result.Add(level);
    level = level.Where(n => n.Children != null).SelectMany(n => n.children).ToList();
}

There is virtually nothing to go wrong here apart from getting those 2 lines inside the loop the wrong way round. You don't need anything more complex unless performance is a real concern, or you want a lazy implementation, in which case you need to be careful you don't yield state you are about to access:

List<int> level = new List<int> { root };
while (level.Count > 0)
{
    var previous = level;
    level = previous.Where(n => n.Children != null).SelectMany(n => n.children).ToList();
    yield return previous;
}


Problems :

methods mkdirs() and createNewFile() return booleans to indicate whether they are successful. You should check and handle if they return false.
IOException gets ignored, you print the stacktrace but clients have no way of knowing the method failed.

Style :

This is one procedural block in which different concerns ( finding and creating files, directories, computing hash, converting byte[] to a String, ... ) are handled. Despite an attempt to limit the of variables scope with a block statement, variable scope is unclear and often wider than strictly needed. There is but one cure : refactor : extract method.
variable naming does not follow Java conventions.
Don't return a dummy return value, declare the method to have void as return value, and you don't need to return a value.
Comments : step 1, step 3 what happened to step 2?
printStackTrace() statement ends with ;; only one is needed. (probably a typo)
loop over the byte array can be a foreach loop :

like this :

for (byte aResult : computeSha1Hash(input)) {
    builder.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));
}

coupling should be reduced. The hashing algorithm (sha1), output mechanism (files) and byte[] to String encoding are all hardwired.
use of magic numbers; replace with explaining constants.


I'm sorry, but the best solution to this problem has to be a logic solution, not a code solution. There are only 2 digits that, when multiplied by 3, have the same last digit... 0, and 5. So, 0+0+0 is 0, and 5+5+5 is 15.

Since C cannot be 0, it means that C can only be 5. Now, if C is 5, and we know that there is a 'carry' of 1 in to the tens column, it means we need to find a number other than 5 that when added together 3 times ends in a 4.

There is only one value that does that, 8. 8 + 8 + 8 is 24, and with the carry of 1, we have 25 (and a carry of 2 in to the 100's column).

So, now we need a digit that sums three times to 3, and that's 1.

There is only one possible solution where ABC + ABC + ABC is CCC, and that's 185. It can be deduced using logic alone, and brute-forcing it is overkill.


For each element in a list, finding the element in a second list, that minimizes a distance function

The approach is fine and this is exactly the purpose of the key attribute of min.

I’d just nitpick that the _ variable name is usually meant to indicate unused arguments and thus, using it inside the lambda goes against conventions.

Alternatively, you can make use of functools.partial which may yield better performances on larger lists:

[min(y, key=partial(d, a2=xindex)) for xindex in x]


Generate all possible combination of n-pair parentheses

Names

The plural of parenthesis is parentheses (as used in the specification). So I think it would make more sense to call the top level function generateParentheses, or even generateBalancedParentheses.

The inner function should be addParenthesis (with an e substituted for the third a).

Opinions will vary on cur as an abbreviation for current. I think it's common enough to be easily recognised, although given the meaning of the value it names perhaps prefix would be better.

open and close read to me as verbs, although open could also be a count of the number of parentheses which have been opened and not closed (i.e. the surplus of ( over ) in cur). I've reverse engineered that they count, respectively, the number of ( and ) in cur. Perhaps opened and closed would be clearer, along with a comment explaining what they are.

Scope

Although JavaScript is very forgiving of the order of declarations, humans tend to read code in order. I would find it clearer if res were defined before addParenthesis, since that references it.

Correctness

Although the code looks correct to me, I would like to see some comments to justify why it's correct. Why are the if guards necessary and sufficient?

With these comments, you would also be able to justify a slight simplification:

  const addParenthesis = (prefix, opened, closed) => {
    if (closed === n) { res.push(prefix); }
    if (opened < n) { addParenthesis(prefix + '(', opened + 1, closed); }
    if (closed < opened) { addParenthesis(prefix + ')', opened, closed + 1); }
  };


N-queens problem in Haskell by bruteforce

The standard way to solve this is to:

Only keep track of the positions of the queens - not whether a square has a queen.
Since only each column may have one queen (and must have one queen), a solution is a [Int] indicating the row positions of the placed queens, e.g. [0,2,4] is a solution for a board having 3 columns (and at least 5 rows) where the queens are at (0,0), (1,2) and (2,4).

So build up the solution iteratively. If you have the placement [r1] how can it be extended to a valid placement [r1, r2]? Clearly r2 can't equal r1 and (0,r1) can't be on the same diagonal as (1,r2). And, of course, r2 has to be a valid row number.


Converting polar coordinates to Cartesian coordinates

You are missing a key feature of the R language: "vectorization". A fancy word for saying that most functions are implemented in such a way that you can provide them vectors and they will apply the computations to each element. As an example, the multiplication function * is vectorized so you can do r.polar <- x[, 3] * 0.075 and it will return the full vector of x[i, 3] * 0.075 where i goes from 1 to nrow(x). This is less typing than doing for (i in 1:nrow(x)) { r.polar[i] <- (x[i,3] * 0.075) } and also a lot faster as you can test.

Applying that idea throughout your code, you can rewrite your Polar2Cart as follows:

Polar2Cart <- function(x) {
   z <- x[, 1]
   t <- x[, 2]
   r <- x[, 3]
   theta.polar <- t * pi / 180
   r.polar <-  r * 0.075
   x.cart <- r.polar * cos(theta.polar)
   y.cart <- r.polar * sin(theta.polar)
   value  <- rf.190301[cbind(z, t, r)]
   Cart.x <- cbind(z, y.cart, x.cart, value)
}

One thing that needs explanation is the use of rf.190301[cbind(z, t, r)]. It is a little known use of the [ function documented as follows (you can access the doc by typing ?"[")

  A third form of indexing is via a numeric matrix with one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector.

Finally, a recommendation. Be careful using single characters as variable names, since R already uses a few of them for built-in variables or functions. You could for example confuse your variable t for the t() function for transposing data. Other single character variable names used by R that come to mind are c (concatenation), q (quit), T (TRUE), F (FALSE), I (inhibit). Anyway, it is always better to use descriptive variable names and that usually implies more than one character.


Evaluating algebra expression using an auxiliary VB class compiled on the fly and consumed in a C# project

public static class Parser

Why is this class static? When you have a class with some state, you should almost never make that state static. For example, you might be very surprised when you try using this code from multiple threads.

using (StreamReader sr = new StreamReader("template.vb"))
{
    source = sr.ReadToEnd().Replace("expression-in-x", expression);
}

You could have used File.ReadAllText() to make this simpler.

CompilerParameters cps = new CompilerParameters();
cps.GenerateExecutable = false;
cps.GenerateInMemory = true;

Using var and object initializer, you can shorten this to:

var cps = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true };

Also, cps is not a great name, don't shorten names unnecessarily.

obj = a.CreateInstance("AnyNamespace.AnyClass");
mi = obj.GetType().GetMethod("AnyMethod");

Instead of object and MethodInfo, you could store the method as a delegate:

Func<double, double> compiledFunction;

…

var obj = a.CreateInstance("AnyNamespace.AnyClass");
var mi = obj.GetType().GetMethod("AnyMethod");
compiledFunction =
    (Func<double, double>)Delegate.CreateDelegate(typeof(Func<double, double>), obj, mi);

…

return compiledFunction(x);

As another advantage, this is likely going to be faster, since it's not using reflection for every invocation of Evaluate().


Behaviour

I assume that you are writing this code in preparation for some programming challenges involving an online judge.  In that case, it's unconventional that you are producing a matrix of digits.  That is, each element is a single digit, no negative numbers, and no numbers larger than 9.

Usually, each line represents an independent test case.  You should be able to compute a result for each line of input without waiting for all of the input to be read first.

Abstraction

If you want to focus on input-handling as a problem to be solved, then the "proper" solution would be to provide a convenient way for your computation code to fetch its input.  The goal would be to enable simple code like:

public class Multiply {
    public static int product(int[] numbers) {
        int product = 1;
        for (int n : numbers) {
            product *= n;
        }
        return product;
    }

    public static void main(String[] args) {
        IntTestCaseInput input = new IntTestCaseInput(System.in);
        for (int[] multProblem : input) {
            System.out.println(product(multProblem));
        }
    }
}

Here is a class that could achieve that:

import java.io.*;
import java.util.*;

public class IntTestCaseInput implements Iterable<int[]> {
    private class Iter implements Iterator<int[]> {
        public int cases = -1;

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean hasNext() {
            try {
                maybeInitialize();
                return cases > 0;
            } catch (IOException e) {
                return false;
            }
        }

        @Override
        public int[] next() {
            try {
                maybeInitialize();
                if (cases == 0) {
                    throw new NoSuchElementException();
                }
                cases--;

                String[] strings = IntTestCaseInput.this.in.readLine().split("\\s+");
                int[] numbers = new int[strings.length];
                for (int i = 0; i < strings.length; i++) {
                    numbers[i] = Integer.parseInt(strings[i]);
                }
                return numbers;
            } catch (IOException e) {
                throw new NoSuchElementException(e.getMessage());
            }
        }

        /**
         * On first use, find out how many test cases to expect.
         */
        private void maybeInitialize() throws IOException {
            if (cases < 0) {
                cases = Integer.parseInt(IntTestCaseInput.this.in.readLine());
            }
        }
    }

    private BufferedReader in;

    public IntTestCaseInput(InputStream in) {
        this(new InputStreamReader(in));
    }

    public IntTestCaseInput(Reader in) {
        this.in = (in instanceof BufferedReader) ?
            (BufferedReader)in : new BufferedReader(in);
    }

    @Override
    public Iterator<int[]> iterator() {
        return new Iter();
    }
}

In total, this results in a lot more code than your in your original question.  However, once the calculations start getting more complicated, you may find that getting the input routines out of the way is worthwhile.


Some recommendations:

Instead of creating monolithic DAOs, you should split it in domain objects and data mappers. This way you would separate the entity-specific business logic from storage.
Do not ever use active record as default solution in any code. It has very specific and limited use-case, and when you exceed those limitation, your code becomes convoluted and hackish. Active records are good for two things: fast prototyping (creating temporary throw-away code) and implementation extremely simple domain entities with almost no business logic (glorified value objects with hard-coded storage).
Look into use of PDO. It should provide you with a bit more flexible storage infrastructure when dealing with SQL databases.
You currently have domain business logic from model layer leaking in the controller. This is kinda bad. Controller should only change the state of model layer. It should not know how to create and save entities. You might benefit from reading this answer.
Watch every lecture, that is listed here. Your code seems to suffer from tight and violations of Law of Demeter. You won't be able to understand everything, that is talked about, at first (at least , I didn't). If that happens, watch the listing till the end ad start again. Each time you will understand more of it.


Is this a correct implementation/use of move semantics?

Yes BUT.

The std::array itself is not moveable. But it is still optized for move semantics when its content type T is moveable. So it will move each of its internal elements rather than copy them. But your function limits the type of T to std::is_arithmetic which is only defined for built-in integers and floats. Moving integers and floats is the same as copying them. So you get no real benefit.

But lets take this a step further.
If you remove the static_assert so it can be used by any type that supports the operator* etc.. then you have a usability issue.

When you do a multiplication like this you destroy the original array (Its content has been moved so there is no way to know what the elements are or if they are usable. About the only thing you can do is reset them to a specific state).

#include <array>

int main()
{
    std::array<MyMathType, 5>  a = initArray();
    std::array<MyMathType, 5>  c;

    // Your code moves the content of a here.
    c = a * 5;

    // So at this point the content of a is in an undefined state
    // So you can not rely on what is in `a` or use it in ANY way that would
    // need the content to be in a defined state (all you can really do is reset).
    //
    // This is not what I would expect of `operator*`
    // So it is quite easy to make mistakes with this code.
}


You could use a better name for the template argument float_t, maybe value_t

Maybe you could combine both log functions as they are very similar:

template <typename Container, typename InputIt>
void log(Container &c, InputIt begin, InputIt end, std::true_type) {
    c.emplace_back(begin, end);
  }


Project Euler 1 - Multiples of 3 and 5 by Loki

You can replace sort | uniq with sort -u.
Note that (...) executes in a sub-shell.
Grouping with { ...; } would be more efficient,
and equivalent to what you did.

So without optimizing much, keeping it still simple and easy to type, you get:

{ seq 0 3 999; seq 0 5 999; } | sort -u | xargs | tr ' ' '+' | bc

Even so, sorting doesn't sound great. Probably it would be better to not sort, but add the sum of seq 0 -15 -999.

seq is not portable. And it's an additional process. You could either use {start..end..step} native Bash syntax, or native Bash counting for loops, but I bet you intentionally didn't because it's a bit longer to type.

And as Bash can easily do such simple math, you don't really need bc.

Here's a more efficient version, using fewer processes:

((x = $({ seq 0 3 999; seq 0 5 999; } | tr '\n' '+')$(seq 0 -15 -999))); echo $x

Here's another version using native Bash features only:

x=0
for ((i = 0; i < 1000; i += 3)); do ((x += i)); done
for ((i = 0; i < 1000; i += 5)); do ((x += i)); done
for ((i = 0; i < 1000; i += 15)); do ((x -= i)); done
echo $x

The most performant solution is of course using the closed form formula:

n=999; echo $((3 * (n / 3) * (n / 3 + 1) / 2 + 5 * (n / 5) * (n / 5 + 1) / 2 - 15 * (n / 15) * (n / 15 + 1) / 2))


JSON AsyncTask refactoring to improve quality?

Don't open a resource in one place and close it in another. Keep the opening and closing of a resource localized to the same function (if you open it, you close it). This makes it easier to spot potential resource leaks.

For example, an InputStream is being opened in doInBackground(), but it is being closed in readStream(). Since doInBackground() opened the resource, it should be responsible for closing it.

HttpURLConnection con = (HttpURLConnection)url.openConnection();

You are not using anything specific to HttpURLConnection, so there is no reason to cast it. This works just fine:

URLConnection con = url.openConnection();

try {
    ...
} catch (Exception e) {
    e.printStackTrace();
}

Don't ignore exceptions. Either let them continue up to the caller, or handle them appropriately. The readStream() function is a good example of where the exception should continue to the caller. Declare it as throwing IOException and remove the exception handling:

private String readStream(InputStream in) throws IOException {
    String content = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while ((line = reader.readLine()) != null) {
        content += line;
    }
    return content;
}

JSONObject jObject = new JSONObject(jArray.get(i).toString());

This can be simplified to this:

JSONObject jObject = jArray.getJSONObject(i);

Declare variables closer to there they are used. For example, in onPostExecute(): i, strValue and arrCategories are all declared at the top of the function, but are only ever used inside the try block.

protected void onPostExecute(String strResult) {
    TextView txtDebug = (TextView)findViewById(R.id.txtdebug);
    try {
        JSONArray jArray = new JSONArray(strResult);
        String[] arrCategories = new String[jArray.length()];
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject jObject = jArray.getJSONObject(i);
            arrCategories[i] = jObject.getString("name");
        }
        txtDebug.setText(Arrays.toString(arrCategories));
    } catch (JSONException e) {
        e.printStackTrace();
        txtDebug.append("Error in categories json file \n");
        txtDebug.append(String.valueOf(e));
    }
}

I would also like to see onPostExecute() broken down further. It is currently doing two things: parsing the JSON array and updating the UI. Move those into their own functions.

I am not a big fan of the comments in this code. I do not believe they add any value, and are only a distraction while reading.


Caching a value just once and update it without blocking other threads

The initial creation looks thread-safe at first glance. I don't know why you await your semaphore instead of just waiting synchronously with _ss.Wait(0) but I don't think it matters much.

The updating part however is not thread-safe. Any number of threads can come in between:

if (!_isUpdating && _isRenewNeeded(_container.Value))

and

_isUpdating = true;

This will result in every thread getting their own value, which is probably not what you want.

You should also call Dispose on disposable objects when you no longer need them.


I am afraid your code cannot be simplified further due to the imperative nature of Benchmark.realtime (it would have been better if it also returned the result of the block). Anyway, I think the best solution is to abstract it and write a wrapper method. For example:

def benchmark(msg)
  logger.debug(msg)
  result = nil
  ts = Benchmark.realtime(&block) { result = yield }
  logger.debug("Completed in #{ts} seconds")
  result
end

def query(sql)
  benchmark("DB: Executing query #{sql}") do
    @db.exec(sql)
  end
end

Now, if your question was on a more generic plane, let's say, that you have lots of methods that work like realtime which force you write a lot of boilerplate, I'd propose this generic Object#capture wrapper:

class Object
  def capture(method, *args)
    result2 = nil
    result1 = send(method, *args) { |*bargs| result2 = yield(*bargs) }
    [result1, result2]
  end
end

realtime_output, block_output = Benchmark.capture(:realtime) do
  "my output"
end #=> [7.263e-06, "my output"]


Calculate temperature based on differing regression coefficients

There are a couple of things you can do to speed this up.

Set the initial capacity of result

The List<T>() constructor uses a default initial capacity. When the number of elements in the list goes beyond its capacity, the list must be resized. We can avoid resizing the list by setting the initial capacity of result to suctionPressureList.Length.

Remove the call to Array.IndexOf.

Assuming that each element in coefficients is unique, we can remove the call to Array.IndexOf. We can do this by either using the overload of Select that gives us the index of the element:

var sst = coefficients.Select((c, i) => c * Math.Pow(psig, i)).Sum();

or we can manually do the summation:

double sst = 0;
for (var i = 0; i < coefficients.Length; i++)
{
    sst += coefficients[i] * Math.Pow(psig, i);
}

With these changes, these are the results that I got for an input array of size 1,000,000:

BenchmarkDotNet-Dev=v0.9.3.0+
OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-6650U CPU @ 2.20GHz, ProcessorCount=4
Frequency=2156248 ticks, Resolution=463.7685 ns
HostCLR=MS.NET 4.0.30319.42000, Arch=64-bit RELEASE [RyuJIT]

Type=Foo  Mode=Throughput

   Method |      Median |    StdDev |
--------- |------------ |---------- |
      New |  80.4571 ms | 2.6079 ms |
 Original | 220.0254 ms | 9.9705 ms |


MySQL statements to update overlapping database entries and insert new data into various tables

I was going in circles looking at your query and then I thought
... it looks like you're just updating the one table form the same table

Why can't you just use

UPDATE hashes
SET id=@id
    WHERE hash IN ('hash1', 'hash2');

Or is this a typo?

UPDATE hashes


Checking if an xy position is within a rectangular bounds

There is. You can use Math.min and Math.max to determine which is the smaller end and the larger end. This way, you avoid the if statements.

function isWithinBounds(obj, pos) {
    var oXmin = Math.min(obj.startPos.x, obj.endPos.x);
    var oXmax = Math.max(obj.startPos.x, obj.endPos.x);
    var oYmin = Math.min(obj.startPos.y, obj.endPos.y);
    var oYmax = Math.max(obj.startPos.y, obj.endPos.y);
    return ( oXmin < pos.x && pos.x < oXmax && oYmin < pos.y && pos.y < oYmax);
}


Loki's solution does not enforce the order in which the function calls are performed, because the order in which function arguments are evaluated is unspecified. Here's a C++14 solution that ensures the function is called from left to right:

#include <cstddef>
#include <tuple>
#include <utility>

template <typename Tuple, typename F, std::size_t ...Indices>
void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) {
    using swallow = int[];
    (void)swallow{1,
        (f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...
    };
}

template <typename Tuple, typename F>
void for_each(Tuple&& tuple, F&& f) {
    constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
    for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f),
                  std::make_index_sequence<N>{});
}

I use swallow{f(x)...} to force the evaluation order. It works because the order in which the arguments to a brace initializer are evaluated is the order in which they appear. You can then use it like:

#include <iostream>

int main() {
    for_each(std::make_tuple(1, '2', 3.3), [](auto x) {
        std::cout << x << std::endl;
    });
}

EDIT

I modified the code so it works on both GCC and Clang. Here's a more in-depth explanation of for_each_impl.

First, we make sure that we call f inside a braced initializer, so the evaluation order is from left to right:

using swallow = int[];
swallow{f(std::get<Indices>(tuple))...};

But then, what if f does not return an integer value? What if it returns void for example? So we use the comma operator to make sure the expression is an integer which can be used inside the braced initializer:

swallow{(f(std::get<Indices>(tuple)), int{})...};

The expression (f(stuff), int{})... is a parameter pack expansion. It expands to (f(stuff_1), int{}), (f(stuff_2), int{}), ..., (f(stuff_n), int{}), so each expression is really an int, except that some side effect has been performed before. Then, to avoid nasty overloads of the comma operator by whatever is returned by f, we insert a void between f(...) and int{}. Since operator,(SomeType, void) can't be overloaded, this ensures that the builtin operator, is used, which is what we want. This might seem overkill, but we do this in highly generic code where we must assume that f(...) could overload operator,:

swallow{(f(std::get<Indices>(tuple)), void(), int{})...};
                                      ^~~~ Make sure the builtin operator, is used

Then, what happens if for_each_impl is sent 0 arguments? We're gonna try to create a 0-sized array, so we must make sure the array always has at least one element in it. We use a dummy int for this:

swallow{1, (f(std::get<Indices>(tuple)), void(), int{})...};
        ^~~~ Now the array always has at least one element in it

We're almost done, but now there's an anoying compiler warning saying "You're creating a temporary array 'swallow' which is never used". To silence it, I cast the swallow{...} to void. Finally, just add perfect forwarding of the Tuple and you're done:

(void)swallow{1, (f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...};
^^^^^^ Silence warning                ^^^^^^^^^^^^^^^^^^^ Perfect forwarding

Note that the way I use std::forward here could be unsafe in other circumstances. This is because tuple could be double-moved-from if the function I forwarded it to had different characteristics. Consider:

swallow{f(function_that_moves_from_its_arg<Indices>(std::forward<Tuple>(tuple)))...};

Now, tuple might be moved-from several times:

swallow{
    f(function_that_moves_from_its_arg<Index1>(std::forward<Tuple>(tuple))), // move here
    f(function_that_moves_from_its_arg<Index2>(std::forward<Tuple>(tuple))), // move here
    f(function_that_moves_from_its_arg<Index3>(std::forward<Tuple>(tuple))), // move here
    ...
}

However, I know std::get is a friendly function and so there's should be no problem in doing this. There's an alternative way to do it "safely", but it involves using std::tuple_element and it's more complicated.


Calculating sum of manhattan distances in a sliding puzzle

Assuming you hold the right order of the puzzle pieces in the goal-array, wouldn't it be natural that the right order itsself is 0 to #pieces - 1?

If that's the case, you could calculate the manhatten distance by just iterating over ps[]:

for (int i = 0; i < ps.length; i++)
    if( ps[i] == i ) continue;
else
    manhattanDistanceSum += (Math.abs(ps[i]/rowSz - i/rowSz) + Math.abs(ps[i]%rowSz - i%rowSz));