Simple prime number search with trial division

Instead of doing this you should instead use a sieve, where you filter the output. It would make the code much simpler, and would make it much faster.

Your comments are useless at best. If you know two languages it'd not make sense to say the same thing in both. Which is what you are doing here. Instead what you want to use comments for, is for high-level overviews of your code.

Say you create a primality test which is heavily optimized, you would want to put a comment on the hard to read parts. Such as your sqrt part.

To improve the actual code, I'd:

Remove unneeded comment.
Change the while to not square root num each iteration.
Change the code to use the less accurate ** operator, rather than math.sqrt. You're using int and adding by 1 anyway, so it won't make a difference.
Change seeker to yeild 2 if it's within the domain.
Change seeker to use a for loop, to simplify the code. As with the above you don't need to increment by one ever.
Move the keyboard interrupt code out of the function, into the main. As functions are meant to do one thing, not two.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Made for Python 2.7.x
See __main__ block at the end of this
script to change the range to be searched.
"""

def is_prime(num):
    """
    Test if a number is a prime with Trial Division.

    num: The number to be tested.
    Returns True if num is a prime and False if not.
    """

    if num < 2:
        return False
    if num == 2:
        return True
    if num % 2 == 0:
        return False

    # Check if number is divisible by any odd number,
    # from one to the square root of the number.
    # as one of a or b will be in this range,
    # for all a and b that are `a * b = num`.
    for i in range(3, int(num ** 0.5) + 2, 2):
        if num % i == 0:
            return False
    return True

def seeker(num_start, num_end):
    """
    Search for primes from and including num_start to num_end.
    Uses 'is_prime_td()'.
    """
    # Force `num_start` to be odd with xor, ^. And go up in twos.
    if num_start <= 2 <= num_end:
        yield 2
    for i in range(max(3, num_start ^ 1), num_end + 1, 2):
        if is_prime_td(num):
            yield num

if __name__ == '__main__':
    num_start = 0
    num_end   = 100
    try:
        for num in seeker(num_start, num_end):
            print num
    except KeyboardInterupt:
        pass


Simple way to prevent duplicate logging of errors

ErrorObject newError = new ErrorObject(…);

This is one of the cases where most people will probably agree that you can use var here. Doing that doesn't lose any information (you can still see at a glance that newError is an ErrorObject) and it makes the code shorter and more DRY.

return retVal;

In general, you shouldn't use integer retVals. If you need to report errors, use exceptions. If you want to report success or failure, use a bool. If you want to report multiple possible results, use an enum. If you want to report some kind of count (though I don't see how would that make sense here), at least name your variable something like count, not retVal.

//Store 4 previous errors to compare against
private static Queue<ErrorObject> PreviousErrors = new Queue<ErrorObject>(4);

This sounds like a job for a simple reusable custom collection. Something like:

class BoundedQueue<T> : IEnumerable<T>
{
    private readonly int count;
    private readonly Queue<T> queue;

    public BoundedQueue(int count)
    {
        this.count = count;
        this.queue = new Queue<T>(count);
    }

    public void Enqueue(T item)
    {
        if (queue.Count == count)
            queue.Dequeue();

        queue.Enqueue(item);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return queue.GetEnumerator();
    }
}

lock (PreviousErrorLock)

Since you want to lock access to the PreviousErrors object, you should use that in the lock, you don't need another object for this. (An object used just for locking makes sense when you logically want to do something like lock (this), but that's not the case here.)

foreach (ErrorObject previousError in PreviousErrors)
{
    if (previousError.AdditionalInfo == newError.AdditionalInfo &&
    Math.Abs((previousError.Time - newError.Time).TotalSeconds) < 3 &&
    previousError.Exception.GetType() == newError.Exception.GetType() &&
    previousError.Exception.Message == newError.Exception.Message &&
    previousError.Exception.TargetSite == newError.Exception.TargetSite)
    {
        isDuplicate = true;
        break;//Exit the loop
    }
}

You should extract this equality testing code into a separate method, possibly as ErrorObject.Equals(). With that, this code would simplify to:

bool isDuplicate = PreviousErrors.Contains(newError);

break;//Exit the loop

You don't need this comment. Everyone knows what break does inside a loop.

Also, I find the queue logic suspicious: when you detect a duplicate, you add it to the queue anyway. So if the sequence of exceptions is something like 1, 2, 2, 2, 2, 1, then you're going to report 1 twice, even though it's among the 2 most recent error kinds.


A function does one thing, and one thing only.

final protected function syncToDatabase(array $data)
{
    $isMulti = FALSE;

    // ...

    // determine if the array has multiple result sets
    foreach ($sh as $x) {
        if (is_array($x)) {
            $isMulti = TRUE;
            break;
        }
    }

    if ($isMulti) {
        // ...
    } else {
        // ...
    }
}

Please don't do this. You are trying to provide two different functions under a single interface. That's error prone, and not exactly necessary either.

The calling site should already know whether it's invoking this function with a single result set, or an array of such.

Use this knowledge in your API design. In your case, this means stripping your syncToDatabase of all the special handling regarding multi updates.

final protected function syncToDatabase(array $item) {
    $model      = $this->model;
    $identifier = $this->tableIdColumn;

    $row = $model::get()
        ->filter(
            array(
                "{$identifier}" => $item[ $identifier ]
            )
        )
        ->first();

    if (is_null($row)) {
        // row not found insert
        $new = $model::create();
        foreach ($item as $res => $val) {
            $new->$res = $val;
        }
        $new->write();
    }
    else {
        // update existing row
        $row->update($item);
        $row->write();
    }
}

If you know that you need multi row updates commonly, provide that by a dedicated function, only for that task:

final protected function syncToDatabaseAll(array $items) {
    foreach ($items as $item) {
        $this->writeRow($item);
    }
}

Reinventing the wheel

foreach ($item as $res => $val) {
    $new->$res = $val;
}

Why? Only 3 lines further down, you used the correct function to update a row from an array.

$row->update($item);

Even worse - what you just implemented yourself can have unitended side effects if the row object has additional properties with special meaning, which coincidentally collide with (not actually ignored) keys in the passed data.

So your logic can be written more compact and less error prone once again:

$row = $model::get()->[...]->first();

if (is_null($row)) {
    $row = $model::create();
}

$row->update($item);
$row->write();

syncToDatabase is a pretty long name, you would commonly just call the whole process persist.

Your PHPDoc comment is a lie.

  Will ignore keys where a column does not exist for which will allow you to enter a dirty array as long as it has the key => value pairs that you wish to update.

This however is not what your function actually does.

For starters, you implicitly require a valid key/value pair for the primary key.

Not provided? $item[ $identifier ] will throw a warning and then default to null, as you attempt to read from a key which didn't exist before.

Neither did your comment describe in any way the "multi update" functionality. Especially the heuristic you are using to determine whether the passed array contains one or more data sets.

If only one of the (not actually ignored) additional fields is an array, the heuristic triggers and leads to a wrong handling of the argument.

Error handling?

$row->update($item);
$row->write();

Depending on where your ORM does validation, either of these two lines can yield runtime errors.

Especially in the case of the multi row persist, you need to think about how to handle the error case. If one row fails to insert/update, what to do with the rest?

Try to persist as much as possible? Inform the invoking site? And how does the ORM handle validation / SQL errors in the first place? Error codes? Exceptions?

Understanding what the database does

You've got a nasty bug / conceptual error in your code.

You code does work "fine" if the $identifier field is either entirely missing from $item, or if it contains a valid value.

Well, actually it does not work fine in the first case. Because what actually happens, is that accessing $item[ $identifier ] sets this field to null, so you are querying the database for a row with NULL as the primary key. You then continue to insert a new row with explicit null as the primary key, which the database then automatically replaces by the next sequence number. This side effect is a bug, and should be fixed.

But what happens if $item[ $identifier ] was set before, not to null, and not to an existing primary key either? You create a new row, but you did not use the sequence number generator intended by the database for that. Even being set to an empty string will most likely break this already.

Actually, when does it occur that the row, which was supposed to be updated, can't be found?

Either someone just guessed a random primary key (which should not happen), or the row was deleted in the meantime.

In the latter case - is it actually the expected behavior to re-add the formerly deleted row? Or throw an error? Un-assign the (known to be invalid) primary key and let the database assign a new one?

Either way, you certainly don't want a primary key in your table which wasn't generated by the sequence number generator. For various reasons.


Well, given the examples, i'd avoid inheritance and implement an interface for the DataProcessor.

package net.icodeapps.examples.ooad;

public interface DataProcessor<T, OtherData> {

    T processData();
}

This could be implement by any class like

package net.icodeapps.examples.ooad;

public class ADataProcessor implements DataProcessor<AData, OtherData> {

    private AData aData;

    private OtherData otherData;

    public ADataProcessor(AData aData, OtherData otherData) {
        this.aData = aData;
        this.otherData = otherData;
    }

    @Override
    public AData processData() {
        return aData;
    }
}

Having a second class implementing the interface

package net.icodeapps.examples.ooad;

public class BDataProcessor implements DataProcessor<BData> {

    private BData aData;

    private OtherData otherData;

    public BDataProcessor(BData aData, OtherData otherData) {
        this.aData = aData;
        this.otherData = otherData;
    }

    @Override
    public BData processData() {
        return aData;
    }
}

With more information, still would skip the abstract class. The reason you use it is providing a contract and avoid code replication. But since the code you try to avoid replicating is the problem itself, i'd skip that and just provide private fields to store references. That way you have the right type in processData.

Keeping the processors stateless and just store the data in a queue could be a better approach though. Depending on the data, you would create a processor on demand. The could be implemented via the command processor pattern. Using that pattern, more complexity would be introduced though.


Simplifying dictionary of constant values

Your code is short, readable and efficient, so I don't think it needs much improvement. And I don't think adding a static class would give you anything (although changing the field and the method to static could make sense).

Another way to write your code would be to use switch, but I'm not sure whether it's more readable (although it could be slightly more efficient):

public string GetRefStat(string pk)
{
    switch (pk.Substring(2, 2))
    {
    case "00":
        return REF.MenuType;
    case "01":
    case "02":
    case "03":
    case "06":
        return REF.ReferenceStatus;
    default:
        throw new InvalidOperationException();
    }
}


Bug?

The output from your version:

12345
   c
  7
 g
mnopq

But the output should be

12345
   d
  8
 h
mnopq

It's unclear why you chose this.

                    System.out.print(a[i][j-1]);

This could be

                    System.out.print(a[i][j]);

Then it prints the output correctly.

Avoid unnecessary comparisons in loops

You iterate over each element in the entire square and print different things based on an if/else structure.  But you don't actually have to do that.  Consider

    public static void drawZ(String[][] matrix) {
        System.out.println(String.join("", matrix[0]));

        int n = matrix.length - 1;
        for (int i = 1; i < n; i++)
        {
            int m = matrix.length - i - 1;
            for (int j = m; j > 0; j--)
            {
                System.out.print(" ");
            }

            System.out.println(matrix[i][m]);
        }

        System.out.println(String.join("", matrix[n]));
    }

This is in a separate method, which makes it easy to reuse.

This prints the first and last line separately.  So we don't need that part of the if.

This prints the spaces separately from the line of the Z.  So we don't need those parts of the if either.

Rather than calculating i + j - a.length - 1 on every iteration, this code just counts down from m, which it calculates once per row.

This calls a Java 8 built-in method to join the characters in a row rather than rolling our own for loop.

This prints the equivalent part of the matrix.  If that's not what you want, you can replace [m] with [m - 1].  That would give the original behavior.


Showing a tooltip on hover based on a tooltip attribute

Don't do anything in JavaScript that can be done with just CSS!  The :hover pseudo-class is perfect for tooltips.  Use ::after to append a pseudo-element with the tooltip content, where the content is specified by the content property.

div[tooltip]:hover::after {
    content: attr(tooltip);
    display: block;
    position: absolute;
    transform: translateX(-50%);
}

/* Don't review this CSS; it was added just for the demo. */
div[tooltip] { width: max-content; margin: auto; }

Hover me.


hash image url and if valid store image url

here's a few comments in no particular order.

Have a look over PEP8. It's Python's style guide which helps keep Python code consistent and readable. Things like naming functions which snake_case, constants as CAPS, proper spacing around operators, commenting style and placement, spacing between imports, etc.

It's recommended to use a context manager for opening files, this prevents them from being left open and the indentation makes it clear when a file is being used. You can open two files at once like so:

with open('file_one.txt', 'a') as file_one, open('file_two.txt', 'a') as file_two:
    ...

Instead of using return to handle errors, just raise the error itself. Catch the specific exception (ValueError, TypeError, etc (not Exception or worse BaseException)) then raise it with a message like so:

except TypeError:
    raise TypeError('Reason for failure message')

If you want to continue having caught the error, you can print the error message and continue instead:

except TypeError as exc:
    print(f'Reason for failure: {exc}; continuing ...')

A better way of storing lines from a file to a list would be to use readlines() and strip(). readlines() converts a file to a list where each item is a line in the file, and strip() can remove unwanted linebreaks and whitespace.

Wrap the code you're going to run with:

if __name__ == '__main__':
    ...

This stops any old code being executed if importing it as a module.

Why do you take val as an argument then immediately rename it to url? Just take url as the argument, it's more descriptive. You've also used url in your except block where it may not have been defined. It wouldn't fail in this example but it could have done if you wrote code like this elsewhere.

Your variable names could be much improved. No single letter variables! Make them descriptive and avoid putting their type in the name. k -> hash_file; image_hash_list -> image_hashes; etc.

You're importing pickle but not using it. You're also using urllib without importing it.

You're calling os.remove(local) regardless of the if condition. Put this outside the if check.

There are a few other nitpicks and I can't speak to what the code is actually doing as it's not something I'm familiar with, but I hope that helps.


Compute all the permutations for a given vector of integers

A cleaner solution is to trust the standard library and try to re-use the generic components already available there. Your problem is solved by std::next_permutation, so you can proceed along the lines of:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> v = { 1, 2, 3, 4, 5 };

    do
    {
        for (auto e : v)
            std::cout << e << " ";
        std::cout << "\n";
    }
    while (std::next_permutation(v.begin(), v.end()));
}

For pedagogical purposes, if you wanted to keep your current structure, you could also use standard functions there. In particular, remove_item and merge could be rewritten to:

std::vector<int> remove_item(const std::vector<int>& a, int id)
{
    assert(id >= 0 && id < a.size());

    std::vector<int> res(a.begin(), a.begin() + id);
    res.insert(res.end(), a.begin() + id + 1, a.end());
    return res;
}

std::vector<std::vector<int> > merge(const std::vector<std::vector<int> >& a, const std::vector<std::vector<int> >& b)
{
    std::vector<std::vector<int> > res(a);
    std::copy(b.begin(), b.end(), std::back_inserter(res));
    return res;
}

Whatever you do, as general comments:

Avoid writing using namespace std;.
Don't write std::endl when \n will do.
You don't need std::to_string, just print b.
You are more likely to make mistakes when you put multiple statements on the same line. So instead of writing for(...) if(...) v.push_back(x); just write

for(...)
{
   if(...)
   {
      v.push_back(x);
   }
}

This also improves readability.


Light Security Local-Machine Password Encryption

I'd suggest using built-in libraries, especially if you're looking to solve something for production/industry. Quick search shows that there are two to consider that should be available within JDK, the JCA (Java Cryptography Architecture) for local storage of secrets, and JSSE (Java Secure Socket Extension) for comunicating with the remote service.

    The JCA is a major piece of the platform, and contains a "provider" architecture and a set of APIs for digital signatures, message digests (hashes), certificates and certificate validation, encryption (symmetric/asymmetric block/stream ciphers), key generation and management, and secure random number generation, to name a few...

    The Java Secure Socket Extension (JSSE) enables secure Internet communications. It provides a framework and an implementation for a Java version of the SSL, TLS, and DTLS protocols and includes functionality for data encryption, server authentication, message integrity, and optional client authentication...

Utilizing the documentation for local encryption, and examples scattered about, may cause one to write code similar to...

//  Helpful resources
// https://docs.oracle.com/javase/8/docs%2Ftechnotes%2Fguides%2Fsecurity%2Fcrypto%2FCryptoSpec.html#PBEEx
// https://stackoverflow.com/questions/4644415/java-how-to-get-input-from-system-console
// https://www.tutorialspoint.com/check-if-a-string-is-empty-or-null-in-java
// https://stackoverflow.com/questions/18142745/how-do-i-generate-a-salt-in-java-for-salted-hash

import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;

import java.security.SecureRandom;

import java.io.Console;

class pass_enc {

  public static void main(String[] args) throws Exception {
    Console console = System.console();
    if (console == null) {
      System.out.println("Unable to fetch console!");
      return;
    }

    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;

    // Salt
    byte[] salt = new SecureRandom().nextBytes(salt);

    // Iteration count
    int count = 1000;

    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);

    // Prompt for encryption password
    // Use char array because String objects are immutable
    // Convert to SecretKey object using PBE key factory
    char[] password = console.readPassword("Enter a passphrase: ");
    // char[] password = System.console.readPassword("Enter a passphrase: ");
    pbeKeySpec = new PBEKeySpec(password);
    keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

    // Create PBE Cipher
    Cipher pbeCipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");

    // Initalize PBE Cipher with key and parameters
    pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

    // Cleartext to be encrypted
    byte[] cleartext = "This is an example".getBytes();

    // Encrypt cleartext
    byte[] ciphertext = pbeCipher.doFinal(cleartext);

  }

}

... though the compiler will complain about salt being void; Java isn't a language that I write a whole lot in but perhaps the above code will get ya a little closer to something that preforms the necessary steps more securely. Edits and comments are certainly welcomed if someone does figure out how to get Oracle's example code working as intended.


Beginner's attempt for Project Euler problem 12 (highly divisible triangle number)

Iteration, flow control, naming, and clarity

Your iteration is a bit clumsy.

It seems that target is an arbitrarily chosen number that you picked just to act as a sufficiently large second parameter to xrange().  If you want an unbounded counting loop, itertools.count(1) would be better.

Instead of else: counter = 0, you should just set counter = 0 in the right place — just before the inner loop.

Avoid using sys.exit() — it's like killing your program with a sledgehammer.  You should structure your code so that it terminates naturally.

from itertools import count

for value in count(1):
    x = (value * (value + 1))/2
    for divisor in xrange(1, x+1):
        product = x % divisor
        if product == 0:
            counter += 1

    if counter >= 500:
        break

print x

There is an idiom for counting items that meet some criterion: sum() with a generator expression.

from itertools import count

for value in count(1):
    x = (value * (value + 1)) / 2
    if 500 <= sum(1 for divisor in xrange(1, x + 1) if x % divisor == 0):
        print x
        break

As you noted yourself, your variables are poorly named.  product, in particular, should be called remainder.  counter is vague; divisor_count would be more helpful.

What you want to express is a loop over the triangle numbers.  For even greater clarity, I'd break that out into a triangle number generator function.

from itertools import count

def triangle_numbers():
    """Generator of triangle numbers, starting with 1, 1+2, 1+2+3, ..."""
    n = 0
    for i in count(1):
        n += i
        yield n

def divisor_count(n):
    """Count of the divisors of n"""
    return sum(1 for divisor in xrange(1, n + 1) if n % divisor == 0)

print next(t for t in triangle_numbers() if divisor_count(t) >= 500)

Mathematics

Note that \$\dfrac{n(n+1)}{2}\$ is a product of two coprimes.  As explained here, the divisors of such a product can be computed based on the divisors of each of its two known factors.

from itertools import count

def divisor_count(n):
    """Count of the divisors of n"""
    return sum(1 for divisor in xrange(1, n + 1) if n % divisor == 0)

for n in count(1):
    tn = n * (n + 1) // 2
    # n and (n + 1) are relatively prime.  Therefore, if n is even,
    # the factors of tn can be derived from the factors of n/2 and
    # the factors of n+1. If n is odd, then the factors of tn can be
    # derived from the factors of n and the factors of ((n+1)/2).
    tn_divisor_count = (
        divisor_count(n // 2) * divisor_count(n + 1) if n % 2 == 0 else
        divisor_count(n) * divisor_count((n + 1) // 2)
    )
    if tn_divisor_count >= 500:
        print tn
        break


Canvas in Tkinter app for Conway's Game of Life updates so slowly

A few things to make your code better/faster :

You can use tuple unpacking to rewrite :

def init_field(height=10, width=10, alives=()):
    fld = [[False] * width for _ in range(height)]
    for alive in alives:
        fld[alive[0]][alive[1]] = True
    return fld

like this :

def init_field(height=10, width=10, alives=()):
    fld = [[False] * width for _ in range(height)]
    for x, y in alives:
        fld[x][y] = True
    return fld

You could compute alive_neighbours less often by storing the result :

        nb_neighbours = len(alive_neighbours(fld, i, j))
        if fld[i][j] and nb_neighbours not in (2, 3):
            result[i][j] = False
        elif nb_neighbours == 3:
            result[i][j] = True

I must confess that I find alive_neighbours really complicated.


"Rasterbation" function to split an image into a grid

Before you opt for a <canvas> solution you might try adapting your current code with a few go-faster tricks.

var t = Date.now();
var img = new Image();
var length = 30;
var ylength = 20;
img.onload = function() {
    var width = this.width,
        height = this.height,
        _length = -length,
        i, j;

    // create a <div/> with all basic characteristics, to be cloned over and over in the loops below.
    var $basicDiv = jQuery('<div/>', {
        class: 'splitImg',
        css: {
            'width': Math.floor(width/length),
            'height': Math.floor(height/ylength),
            'background-image': 'url(' + img.src + ')'
        }
    });
    // Finding a node in the DOM is slow. Do it once and assign the returned jQuery collection.
    // Also, #wrapper's width can be set here.
    var $wrapper = $('#wrapper').width(width + length * 2);

    for (i = 0; i > _length; i--) {
        for (j = 0; j > _length; j--) {
            $basicDiv.clone().css({'background-position': `${width/length * j}px ${height/ylength * i}px`}).appendTo($wrapper);
        }
    }
    console.log(Date.now() - t);
}
img.src = 'http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg';

Updated fiddle

Playing around with the code, I found all of the following to make a difference :

cloning a basic div created outside the nested loops,
avoiding assignments (other than loop counters) in the nested loops,
avoiding the need to multiply by -1 (twice) by counting backwards in the for(...) expressions,
using a template literal to build the background-position string. But beware, this is not yet well supported in browsers.

With the modified code, execution time on my computer halved from about 1200 - 2000 ms to 600 - 1000 ms.

You may well find a <canvas> approach to be even faster. I was surprised at what could be achieved with <canvas> when I wrote this answer.


Inserting strings in middle of a text file using streams

First and foremost, fix your formatting.  A little bit of effort spent on making the code readable will mean that it can be understood (and thus reviewed) faster.  By the way, you are not using the STL.

Now, significant issues in order of when they appear in your code:

Use an std::vector in favour of new[] pretty much always.  In this case, as the content is all text, an std::string may be even better, but causes problems due to you wanting to read directly into it.
As you want to work with the input on a line-by-line basis, I would advise an std::vector<std::string> that you can populate using a std::string line; while (fileSt >>
line) lines.push_back(line);.  There may be more efficient solutions, but check that you really need them first.
What you're doing with sprintf doesn't make sense.  That could all be replaced with std::string strToFind = "Input" + boost::lexical_cast<std::string>(outPutNumber);.
Notice that if you store the strings as I recommended above, finding a certain line is as simple as lines[nInputLine].
To write everything back, just insert another line into the vector and then write it using a loop or with stream iterators.
No need to explicitly close the files unless you care about the exception that may throw.

And some minor issues:

Your comments are inconsistent, and duplicate information.  You have specified the type everywhere except for in filename, despite the type already being given by the signature.
No need to check for fileSt.good() when checking if its open.
As your function only does anything if the file is opened successfully, return early instead of wrapping the whole thing in a giant if.
Be consistent with qualifying things with std::; do it or don't do it, but don't mix it.  (I would advise explicitly qualifying things above using-declarations (and even more so above using-directives), but all three may be acceptable.)
Same with Hungarian notation: even if you don't agree that the qualifiers don't help with anything, you should at least either use them consistently.


Passing $_POST from view to model in MVC

Superglobals

I cloned your repo and it looks like you've already taken my advice about passing in the superglobals instead of using them directly from your methods.

Formatting

I would have also commented on the formatting but you've also significantly improved that since posting the question. Cheers!

Commenting

The next good habit to get into is commenting, which s just as important as formatting and entirely lacking in this project. You should always put a short comment above every method explaining what it does, what parameters it takes and what it returns so you (and people maintaining the code in
 the future) don't have to read the code to figure out what it does.

I see you're using NetBeans. I Like NB too. NB makes documenting your PHP and JS classes and functions very easy. I looked and I could not find any good documentation because I cannot remember what it's called, so I'll just explain the features as best I can.

Auto-commenting Pro Tip

Netbeans will actually do most of the work for you - place the cursor on the empty line just above the start of the function and type /** and hit the enter key. Netbeans will create the rest of the comment including the parameters and the return type (if there is one).

This is what Netbeans generated for your loginAction method.

/**
 *
 * @param type $username
 * @param type $password
 * @param type $rememberMe
 * @param type $token
 * @param type $redirect
 */
public function loginAction($username, $password, $rememberMe, $token, $redirect = null)

Now you just need to write a short description on the first blankk line and fill in the types (if NB wasn't able to guess them already). eg..

/**
 * Authenticate a user and start a session
 * @param String $username - The username of the user
 * @param String $password - The user's password
 * @param Boolean $rememberMe - Set a cookie?
 * @param String $token - Login token
 * @param String|Null $redirect - URL to redirect to
 */
public function loginAction($username, $password, $rememberMe, $token, $redirect = null)

Now, not only will this be easy to read and maintain, but NetBeans will actually parse these comments and show you what parameters are required when you start to type the method name:


Simple SqlHelper which wraps ADO.NET methods

Nesting.
You can reduce nesting by stacking the using blocks, like this:
    using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(cmdText, connection))
    {
        try
        {
            command.CommandType = cmdType;
            command.Parameters.AddRange(commandParameters);
            connection.Open();
            return await command.ExecuteNonQueryAsync();
        }
        finally
        {
            connection.Close();
        }
    }

I like your usage of var, and the fact that you've wrapped the IDisposable stuff in using blocks. However this is overkill:

    finally
    {
        connection.Close();
    }

Because the connection is wrapped in a using block, the connection will be cleanly closed and disposed, whatever the reason is for the code to reach the end of the using scope. In other words, you can also ditch the try block, and further reduce nesting:
    using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(cmdText, connection))
    {
        command.CommandType = cmdType;
        command.Parameters.AddRange(commandParameters);
        connection.Open();
        return await command.ExecuteNonQueryAsync();
    }

That's because a using block is a language shortcut for... a try...finally block.

The XxxxxHelper Syndrome
The problem with a static class called SqlHelper, is that over time, it becomes a dumping ground for anything remotely related to SQL; it grows hair and tentacles, and becomes a huge mess before you even notice: "Helper" is simply too vague of a name to result in anything cleanly focused.
I would suggest renaming it to something like SqlCommandWrapper - then it's far less likely to become bloated with things that have nothing to do with executing a SqlCommand, but might be remotely related to SqlWhatever.


I updated the code to include @TinMan's remarks.
I also added a safety net by intersecting the range in parameter with the UsedRange to avoid scanning 1 million empty cells if a full column is provided as a parameter.

The most effective change is probably using .SpecialCells(xlCellTypeConstants, xlNumbers): I tried on about 100.000 rows in various configurations:
- all numbers: makes little difference
- just a few numbers: goes from 18 sec to 0.02 sec!

Finally I turned of recalc during the macro.

Sub num2text(rng As Range, Optional keepFormat As Boolean)
'change numbers to text, optionally leaving the numberFormat unchanged
    Dim oldFormat As String, t
    Dim c As Range, i As Long, r As Range
    On Error GoTo finito    'in case selection contains no numeric constants
    Set r = Intersect(rng, rng.Parent.UsedRange).SpecialCells(xlCellTypeConstants, xlNumbers)
    On Error GoTo 0
    Application.Calculation = xlCalculationManual
    For Each c In r
        If keepFormat Then oldFormat = c.NumberFormat   'save num fmt
        t = c.Text
        c.NumberFormat = "@"
        c.Value = t
        If keepFormat Then c.NumberFormat = oldFormat   'restore num fmt
    Next c
    Application.Calculation = xlCalculationAutomatic
finito:
End Sub

Sub selection2text()
    num2text Selection
End Sub


Extracting Country Names from Cell Values

The small(er) things before we tackle the elephant in the room:

Naming

Your names aren't terrible, but could be a lot better. However, whatever you name things, you should comply with standard naming conventions. To wit:

  Local Variables: Written in camelCase.

  Dim localVariable As String
  includes method arguments.

  Module / Global Variables: Written in PascalCase.

  Private ModuleVariable As String
  Global PublicVariable As Long

  Method Names: Verbs. Written in PascalCase

  Private Function ReturnThisValue() As Long
  Public Sub DoThisThing()

  Constants: Written in SHOUTY_SNAKE_CASE

  Public Const CONSTANT_VALUE As String = "This Value Never Changes"

Also, Block is declared and set but never used. It should be removed.

Don't use :

Just don't. Keep your instructions on separate lines. They're too easy to miss and violate too many conventions.

Put things in Variables

Range("C" & i)

You see this? This is telling Excel to go and find that range. Every time you write it. What if you want to check a different column? Right now, you'll have to rewrite the declaration on 20 different lines.

Instead, put it in a variable then just reference the Variable. Now, if the variables need to change, you only have to change them in 1 place, and the rest takes care of itself.

Dim cCell As Range, dCell As Range, eCell As Range
Set cCell = Range("C" & i)
Set dCell = Range("D" & i)
Set eCell = Range("E" & i)

Dim countryName As String

countryName = "Canada"
If Instr(1, cCell, countryName) Or Instr(1, dCell, countryName) Or Instr(1, eCell, countryName) Then
...
...

Don't Repeat Yourself

Also known as DRY. Take your i = i + 1 statement. That is always going to happen. So why write it 20 times when you can just put it at the start or end of your loop?

While i <= lastRow

    Code
    Code
    Code

    ...

    i = i + 1

Wend

Boom. 12 lines of code gone

And now the big stuff:

Refactoring

Refactoring is the process of splitting one big thing into many little things.
Any time you find yourself copy-pasting code, you should be thinking "Hmm, this can probably be turned into a method of some kind".

1st Refactoring

This check:

If Instr(1, cCell, countryName) Or Instr(1, dCell, countryName) Or Instr(1, eCell, countryName) Then

Can be a Separate Method Like so:

Public Function NameIsInRange(ByVal searchName As String, ByRef range1 As Range, range2 As Range, range3 As Range) As Boolean

    Dim result As Boolean
    result = InStr(1, range1, searchName) Or InStr(1, range2, searchName) Or InStr(1, range3, searchName)

    NameIsInRange = result

End Function

And now we're down to:

Sub PullCountries()

    Dim i As Long
    i = 1

    Dim LastRow As Long
    LastRow = Range("B1").End(xlDown).Row

    While i <= LastRow

        Dim resultRange As Range
        Set resultRange = Range("A" & i)

        Dim cCell As Range, dCell As Range, eCell As Range
        Set cCell = Range("C" & i)
        Set dCell = Range("D" & i)
        Set eCell = Range("E" & i)

        If NameIsInRange("Canada", cCell, dCell, eCell) Then
        resultRange = "Canada"

        ElseIf NameIsInRange("United States", cCell, dCell, eCell) Then
        resultRange = "United States"

        ElseIf NameIsInRange("Britian", cCell, dCell, eCell) Then
        resultRange = "UK"

        ElseIf NameIsInRange("UK", cCell, dCell, eCell) Then
        resultRange = "UK"

        ElseIf NameIsInRange("Spain", cCell, dCell, eCell) Then
        resultRange = "Spain"

        ElseIf NameIsInRange("Portugal", cCell, dCell, eCell) Then
        resultRange = "Portugal"

        ElseIf NameIsInRange("Ireland", cCell, dCell, eCell) Then
        resultRange = "Ireland"

        ElseIf NameIsInRange("Japan", cCell, dCell, eCell) Then
        resultRange = "Japan"

        ElseIf NameIsInRange("Greece", cCell, dCell, eCell) Then
        resultRange = "Greece"

        ElseIf NameIsInRange("Italy", cCell, dCell, eCell) Then
        resultRange = "Italy"

        End If

        i = i + 1

    Wend

End Sub

Public Function NameIsInRange(ByVal searchName As String, ByRef range1 As Range, range2 As Range, range3 As Range) As Boolean

    Dim result As Boolean
    result = InStr(1, range1, searchName) Or InStr(1, range2, searchName) Or InStr(1, range3, searchName)

    NameIsInRange = result

End Function

2nd Refactoring

The only things that actually change in the loop are the name to check and the name to output. So, why don't we make those a list? For an iterable list with more than 1 element per line, I'd use an Array.

Let's make a new sheet and give it the codename wsCountryNames. Then a function to get the table and pass it to an Array:

Public Function GetCountryNamesTable() As Variant

    With wsCountryNames

        Dim topLeftCell As Range
        Set topLeftCell = .Cells(1, 1) '/ "A1"

        Dim finalRow As Long
        finalRow = .Cells(.Rows.Count, topLeftCell.Column).End(xlUp).Row

        Dim tableWidth As Long
        tableWidth = 2

        Dim tableRange As Range
        Set tableRange = .Range(topLeftCell, Cells(finalRow, topLeftCell.Column + tableWidth - 1))

    End With

    GetCountryNamesTable = tableRange

End Function

The value in Cell A1 is now in GetCountryNamesTable(1, 1), A2, (2, 1), B1, (1, 2) etc.

Now, we can just iterate through your list:

Sub PullCountries()

    Dim i As Long, j As Long
    i = 1

    Dim LastRow As Long
    LastRow = Range("B1").End(xlDown).Row

    Dim namesList As Variant
    namesList = GetCountryNamesTable

    Dim searchName As String, displayName As String

    While i <= LastRow

        Dim resultRange As Range
        Set resultRange = Range("A" & i)

        Dim cCell As Range, dCell As Range, eCell As Range
        Set cCell = Range("C" & i)
        Set dCell = Range("D" & i)
        Set eCell = Range("E" & i)

        For j = LBound(namesList, 1) + 1 To UBound(namesList, 1) '/ +1 for header row
            searchName = namesList(j, 1)
            displayName = namesList(j, 2)

            If NameIsInRange(searchName, cCell, dCell, eCell) Then
                resultRange = displayName
                Exit For '/ We found our result so we can terminate the loop early
            End If

        Next j

        i = i + 1

    Wend

End Sub

Public Function NameIsInRange(ByVal searchName As String, ByRef range1 As Range, range2 As Range, range3 As Range) As Boolean

    Dim result As Boolean
    result = InStr(1, range1, searchName) Or InStr(1, range2, searchName) Or InStr(1, range3, searchName)

    NameIsInRange = result

End Function

Public Function GetCountryNamesTable() As Variant

    With wsCountryNames

        Dim topLeftCell As Range
        Set topLeftCell = .Cells(1, 1) '/ "A1"

        Dim finalRow As Long
        finalRow = .Cells(.Rows.Count, topLeftCell.Column).End(xlUp).Row

        Dim tableWidth As Long
        tableWidth = 2

        Dim tableRange As Range
        Set tableRange = .Range(topLeftCell, Cells(finalRow, topLeftCell.Column + tableWidth - 1))

    End With

    GetCountryNamesTable = tableRange

End Function

3rd Refactoring

I'm going to put your search range in an Array:

Public Function GetSearchRange() As Variant

    With (codename of your sheet here, call it wsSearchSheet for now)

        Dim topLeftCell As Range
        Set topLeftCell = .Cells(1, 1) '/ "A1"

        Dim finalRow As Long
        finalRow = .Cells(.Rows.Count, 2).End(xlUp).Row '/ "2" for "B" column

        Dim finalCol As Long
        finalCol = 5 '/ "E" column

        Dim tableRange As Range
        Set tableRange = .Range(topLeftCell, Cells(finalRow, finalCol))

    End With

    GetCountryNamesTable = tableRange

End Function

And Re-Jig the IsInRange function to deal with an array value instead:

Public Function ValueContainsString(ByVal valueToSearch As Variant, ByVal searchString As String) As Boolean

    ValueContainsString = InStr(1, CStr(valueToSearch), searchString)

End Function

And implement these changes to the main sub:

Option Explicit

Sub PullCountries()

    Dim i As Long, j As Long, k As Long

    Dim namesList As Variant
    namesList = GetCountryNamesTable

    Dim searchNameCol As Long, displayNameCol As Long
    searchNameCol = 1
    displayNameCol = 2

    Dim searchArray As Variant
    searchArray = GetSearchValues

    Dim searchStartCol As Long, searchEndCol As Long
    searchStartCol = 3
    searchEndCol = 5

    Dim outputCol As Long
    outputCol = 1

    Dim foundMatch As Boolean

    Dim valueToSearch As Variant
    Dim searchName As String, displayName As String

    For i = LBound(searchArray, 1) To UBound(searchArray, 1)
        foundMatch = False

        For j = searchStartCol To searchEndCol
            valueToSearch = searchArray(i, j)

                For k = LBound(namesList, 1) + 1 To UBound(namesList, 1) '/ +1 for header row
                    searchName = namesList(k, searchNameCol)

                    If ValueContainsString(valueToSearch, searchName) Then
                        displayName = namesList(k, displayNameCol)
                        searchArray(i, outputCol) = displayName
                        foundMatch = True
                        Exit For '/ We found our result so we can terminate the loop early
                    End If
                Next k

            If foundMatch Then Exit For
        Next j
    Next i

    '/ Read output back to sheet.
    For i = LBound(searchArray, 1) To UBound(searchArray, 1)
        Range("A" & i) = searchArray(i, outputCol)
    Next i

End Sub

Public Function ValueContainsString(ByVal valueToSearch As Variant, ByVal searchString As String) As Boolean

    ValueContainsString = InStr(1, CStr(valueToSearch), searchString)

End Function

Public Function GetCountryNamesTable() As Variant

    With wsCountryNames

        Dim topLeftCell As Range
        Set topLeftCell = .Cells(1, 1) '/ "A1"

        Dim finalRow As Long
        finalRow = .Cells(.Rows.Count, topLeftCell.Column).End(xlUp).Row

        Dim tableWidth As Long
        tableWidth = 2

        Dim tableRange As Range
        Set tableRange = .Range(topLeftCell, Cells(finalRow, topLeftCell.Column + tableWidth - 1))

    End With

    GetCountryNamesTable = tableRange

End Function

Public Function GetSearchValues() As Variant

    With (codename of your sheet here, call it wsSearchSheet for now)

        Dim topLeftCell As Range
        Set topLeftCell = .Cells(1, 1) '/ "A1"

        Dim finalRow As Long
        finalRow = .Cells(.Rows.Count, 2).End(xlUp).Row '/ "2" for "B" column

        Dim finalCol As Long
        finalCol = 5 '/ "E" column

        Dim tableRange As Range
        Set tableRange = .Range(topLeftCell, Cells(finalRow, finalCol))

    End With

    GetSearchValues = tableRange

End Function

Want to change your country names? Just change the values in your table. Your data moves about? Just change the GetSearchValues targets. You can extend either as far as you like.

Total number of values you now have to change in your code: Maybe 10. And then only if your sheet data moves around positions.

Codenames Addendum

Codenames are big and clever. Every worksheet and workbook has a "name" that the user can see and change.

MyCurrentWB.Worksheets("Country Names")

is referencing a sheet name.

A Codename on the other hand is a secret name that can only be set/changed in the IDE.

the name in brackets is the "name". The name not in brackets is the "codename". It is set in the properties window.

If you give a sheet a codename then the user can change the name as much as they like, all you have to do is use

wsCountryNames.Cells()

in your code and it will keep running.


Unit testing extension method adding view location expander

I find your test is excelent (and I'll borrow it from you). I would, however, make it a litte bit more exact and not only test the counts of generated locations but also whether they have the expected values.

You are not testing basic functions of collections or ASP.NET-Core aspects because it doesn't matter how it's implemented. What you are testing is whether your application has all the view locations it needs to work correctly.

This is a very important (integration) test and you should not remove it but improve it by asserting the actual locations too. If this breaks then your app wont't work anymore so it's a real lifesaver.


Usually, when using for loops and numpy together, you’re probably doing it wrong.

Some things you could replace in your code:

Use np.arange(256) instead of np.zeros + for i in range(256);
Use slicing instead of manually extracting values out of an array;
Use comparisons and .sum() instead of manually counting the number of pixels of a certain color intensity ((array_rgb == 42).sum(axis=1).sum(axis=0))

But all that is nothing compared to the use of numpy.histogram which does exactly what you want.

You also open the same image twice without closing it and yet, you use a with statement with your third open. Always use a with statement to better manage your resources.

I would use several plt.figure() and a single plt.show() to get all 5 plots show at once and be able to compare them. It will also make the whole thing more responsive.

Lastly, I would put all the code in a function that can be parametrized with the image name:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

def histogram(image_name):
    with Image.open(image_name) as image_file:
        array_grey = np.asarray(image_file.convert('L'))
        array_rgb = np.asarray(image_file.convert('RGB'))

    plt.figure()
    plt.imshow(array_grey, cmap='gray')
    plt.figure()
    plt.imshow(array_rgb)

    for i, color in enumerate('rgb'):
        hist, bins = np.histogram(array_rgb[..., i], bins=256, range=(0, 256))
        plt.figure()
        plt.bar(bins[:-1], hist, color=color)
    plt.show()

if __name__ == '__main__':
    histogram('picture1.jpg')

(Using the ... syntax from this answer)

Or you could keep the 3 different histograms in variables for further processing:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

def build_histograms(image_array):
    for i in range(image_array.shape[-1]):
        hist, _ = np.histogram(image_array[..., i], bins=256, range=(0, 256))
        yield hist

def histogram(image_name):
    with Image.open(image_name) as image_file:
        array_grey = np.asarray(image_file.convert('L'))
        array_rgb = np.asarray(image_file.convert('RGB'))

    plt.figure()
    plt.imshow(array_grey, cmap='gray')
    plt.figure()
    plt.imshow(array_rgb)

    red_frequencies, green_frequencies, blue_frequencies = build_histograms(array_rgb)
    grey_frequencies, = build_histograms(array_grey[..., np.newaxis])

    x_axis = np.arange(256)
    plt.figure()
    plt.bar(x_axis, red_frequencies, 1.0, color='r')
    plt.figure()
    plt.bar(x_axis, green_frequencies, 1.0, color='g')
    plt.figure()
    plt.bar(x_axis, blue_frequencies, 1.0, color='b')
    plt.figure()
    plt.bar(x_axis, grey_frequencies, 1.0, color='k')

    plt.show()

if __name__ == '__main__':
    histogram('picture1.jpg')


Filter a list of persons by age and write the results to a relevant file

Why is your class called Data? It's obviously a Person.
In compound words like lastname each "part" needs to be capitalized, so it should be lastName. You did this correctly with LastName, so be consistent.
What is People[]? A collection of Peoples? No, it's a collection of Persons. Also, you didn't provide us with the code for People, not the code for ReadData();.
Why define something -- People[] people = new People[MaxPeople]; -- and then assign it a value on the next line -- people = ReadData();? Combine the two lines.
Why do you use for (int i = 0; i < Count; i++) and not foreach?

Why do File.WriteAllText(@"Kids.csv", String.Empty); and File.WriteAllText(@"Adults.csv", String.Empty);? StreamWriter will create the file if it doesn't exist

Do you want to clear the file in case it exists? Then use false instead of true for the bool append parameter of your StreamWriter constructor.

Matter of fact, considering you're using the default encoding and considering you're overwriting the existing contents if the file exists, why not use a simpler constructor?

WriteKids and WriteAdults do basically the same thing, except for the logic in the if and the filename. So they're candidates to be replaced by a  single method that accepts these as parameter.

Of course, the if logic is hard to represent as a parameter, so that's an indication you've done something wrong. What if the if logic was simply a bool, isAnAdult? That would make it easier.

So the question is: how can you compare something against that bool? The solution: add a (read-only) IsAnAdult property to the Person class, which returns the result of Age > 18.

Of course, I'm again combining things when your teacher told you:

  He told me that I need to use method to return array and create other
  method for writing the array to file or something.

So you should have:

one method that accepts Person[] and a bool isAnAdult as parameters and returns Person[] for which isAnAdult is true or false,
a second method that accepts this filtered Person[] and a filename and creates the file.


A Python solution can be much more succinct than what you wrote.

Reading the file: The file is a degenerate CSV file with double-quoted values.  You can use the csv module to split on commas and discard the double-quotes.
Opening the file: You can use the fileinput module to avoid hard-coding the filename.  The program will either open the filename given as a command-line argument, or read from stdin.
Generating triangle numbers: You used the given formula ½n(n+1), but if you want to generate the triangle numbers in sequence, you can just add 1+2+3+…, as per the definition.  Calling sorted(list(set(…))) is superfluous, since each appended number should be unique and increasing — if you initialize triangles = [0] instead of triangles = [0, 1].
Binary search: Using a binary search overcomplicates the solution.  A linear search is not necessarily that bad, if the list is short — as it will be in this case.  Furthermore, you could have just used a set, whose in operator works in O(1) time, instead of a list.  Writing less code means fewer opportunities to introduce bugs.

Personally, I wouldn't even bother pre-generating the triangular numbers.  Testing whether a number is triangular can be done using a simple arithmetic loop — the sort of thing that a CPU is very good at doing.  For small numbers, it's likely to be even faster than looking up entries in a data structure, since the CPU doesn't have to access memory to perform arithmetic.

If I had to test a large number t for triangularity in O(1) time, I'd use the formula in this form:

$$\lfloor \sqrt{2t} \rfloor \lceil \sqrt{2t} \rceil \stackrel{?}{=} 2t$$

… verifying that \$\sqrt{2t}\$ is not integer.
Scoring: Use the built-in sum() function with a generator expression.  The words appear to be all uppercase already; no need to .lower().  I would use ord() to convert letters to numbers.
Counting words that meet the criterion: Again, use the sum() function, which will treat True values as 1, effectively acting as a counter.  In my solution below, print(sum(is_triangular(score(w)) for w in words(fileinput.input()))) effectively summarizes the purpose of the entire program in one line.

With those suggestions, the solution can just consist of a few one-liner functions, and a loop.  It would be a good idea to write doctests to verify that the behavior is consistent with the examples given in the challenge.

import csv
import fileinput
from itertools import count

def is_triangular(number):
    """
    Test whether number is of the form n(n+1)/2.

    >>> is_triangular(1)
    True
    >>> is_triangular(55)
    True
    >>> is_triangular(56)
    False
    """
    counter = count(1)
    while number > 0:
        number -= next(counter)
    return number == 0

def score(word):
    """
    Calculate the word value by converting 'A'=1, 'B'=2, ..., 'Z'=26, and
    adding.  Characters must all be uppercase letters.

    >>> score('SKY')
    55
    """
    return sum(ord(c) - (ord('A') - 1) for c in word)

def words(fileinput):
    return next(csv.reader(fileinput))

if __name__ == '__main__':
    print(sum(is_triangular(score(w)) for w in words(fileinput.input())))


One single if and you can add an indeterminate number of temperature conditions without adding a single if.

And this code is very short, the struct stuff isn't code

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct
{
  int low;
  int high;
  const char *text;
} temperatures[] =
{
  { 18, 18, "The temperature is normal, stable conditions. \n" },
  { -INT_MAX, 5, "The temperature is too cold. Massive damage. \n" },
  { 25, INT_MAX, "The temperature is too hot. Massive damage. \n" },
};

int main()
{
  int temp;

  printf("type a number: "),
    scanf("%d", &temp);
  printf("\n\n");

  for (int i = 0; i < sizeof(temperatures) / sizeof(temperatures[0]); i++)
  {
    if ((temp > temperatures[i].low && temp < temperatures[i].high) || (temp == temperatures[i].low && temp == temperatures[i].high))
    {
      printf("%s", temperatures[i].text);
      return 0;
    }
  }

  printf("The temperature is unstable. This condition can make damages. \n");
}


Reading Values From Enviromental Monitor XML Feed

Naming/spacing:

Don't use Interface in a class name, it might be confusing. Just make it EnviromentialMonitor. A name like extraction doesn't say much, try xmlTemperature and xmlHumidity for example.
Be consistent when using var:

  Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.

With extraction you correctly used var, but you should also have done it for value in both methods since you know what the type is from the right side of that assignment.

I don't like the linebreaks you put everywhere, it makes the code harder to read. What I usually do is block a section withy declarations and then block a section with methods, for example:

var a = 1;
var b = 2;
var items = new List<int>();

items.Add(a);
items.Add(b);

Double code:

Both the GetTemperature and GetHumidity method have a very similar structure. You could refactor the XML-handling in a separate method which you call from the other two. Both would return a double then.

public static double GetTemperature()
{
    return GetValueFromXml("//field[@key='TempC']");
}

public static double GetHumidity()
{
    return GetValueFromXml("//field[@key='Humidity']")
}

private static double GetValueFromXml(string field)
{
    var xmlValue = LoadInXML().SelectSingleNode(field).Attributes.GetNamedItem("value").Value;
    retrun Convert.ToDouble(xmlValue);
}

IP address:

Perhaps the IP won't change that fast, or at all for that matter but when you want to write good code, you make it independent. Pass the IP address as a parameter to the method or get it from a config/resource file like the line that is commented out in your question.

Static vs. Instance:

Since this is kind of a utility class and you're nowhere creating instances and/or modyfying properties/fields in the class, you can leave it static.

Also, static methods can be a little bit faster than instance methods. More reading on this from MSDN: CA1822: Mark members as static. Basically:

  Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.


Even though this is a fairly short program, resist the temptation to do everything in the Program class of your console app. Whenever I start a new console app, the first thing I do is create a Runner class with an Execute() method and call that from the Main() of Program.

Using goto is IMHO incredibly rare in a C#/.NET program. Make this code block a method and call it.

Whenever you start copy-pasting code, it's a sign you're doing something wrong.

switch (responseIndex)
{
    case 1:
        Console.WriteLine("Great!");
        Console.WriteLine("Your score: " + score);
        break;
    case 2:
        Console.WriteLine("You nailed it!");
        Console.WriteLine("Your score: " + score);
        break;
    case 3:
        Console.WriteLine("You're correct!");
        Console.WriteLine("Your score: " + score);
        break;
    default:
        Console.WriteLine("Good Job " + userName + ", Keep it up!");
        Console.WriteLine("Your score: " + score);
        break;
}

Clearly Console.WriteLine("Your score: " + score); should be in a method of its own, and the other line you be as well, with its message the parameter for that method, e.g.

private void ReportResult(string message, int score)
{
    Console.WriteLine(message);
    Console.WriteLine("Your score: " + score);
}

You could even write the second line as Console.WriteLine("Your score: {0}", score); or Console.WriteLine($"Your score: {score}");. While a small amount of string concatenation isn't a performance killer, newer versions of C# offer nicer and more readable ways to format strings.

int Answer: "Answer" should be camelCase.

Considering that you calculate int correctAnswer = num01 * num02;, why then do you do if (Answer == num01 * num02) next? Use correctAnswer.

Even though the current code is fairly short, I'd still move the code in the if and the code in the else block to a method of their own (e.g. "ReportSuccess" and "ReportFailure"). This will make your code easier to follow and splits up the logic into smaller chunks.


Perform a Caesar Cipher Shift on a given string

Generally speaking your code looks quite good from my point of view. It's nicely structured, readable and documented. Well done!

Using LOWERCASE = ascii_lowercase + ascii_lowercase in conjunction with n = n % ALPHABET_LENGTH also seems to be a very clever way to implement the shift.

You don't need

if n < 0:
    n = ALPHABET_LENGTH - n

because modulo will handle negative numbers in the same way naturally.

Using LOWERCASE.index(...) to find the position of the letter in the alphabet could be optimized by using some kind of look-up table like so:

LOWERCASE_LUT = {letter: i for i, letter in enumerate(ascii_lowercase)}
UPPERCASE_LUT = {letter: i for i, letter in enumerate(ascii_uppercase)}

Also appending to a string with + in Python is wasteful, because strings are immutable, so each time this is done, a new string will be created. What you'll often find instead is to collect the string parts in a list which is then joined at the end.

All of this leads to the following code:

def encode_string_cr(s: str, n: int) -> str:
    """Perform a Caesar Cipher shift on s leaving punctuation, spaces intact

    :param s: the str on which to perform a Cipher shift
    :type s: str
    :param n: the number of places in the alphabet to shift the letter.
              Positive for a forward shift, negative for a backwards shift
    :type n: int
    >>> encode_string(s="Caesar Cipher", n=2)
    'Ecguct Ekrjgt'
    >>> encode_string(s="Caesar Cipher", n=54)
    'Ecguct Ekrjgt'
    >>> encode_string(s="Aa Bb", n=0)
    'Aa Bb'
    >>> encode_string(s="Cc Dd", n=-28)
    'Aa Bb'
    """
    if n == 0:
        return s

    n %= ALPHABET_LENGTH

    chars = []
    for c in s:
        if c in ascii_lowercase:
            i = LOWERCASE_LUT[c]
            encoded_char = LOWERCASE[i + n]
        elif c in ascii_uppercase:
            i = UPPERCASE_LUT[c]
            encoded_char = UPPERCASE[i + n]
        else:
            encoded_char = c
        chars.append(encoded_char)

    return "".join(chars)

This is roughly 1,5x faster than the original code, at the cost of a little bit more memory for those look-up tables.


Creating unique registration numbers using object factories

The number, letter, and strRep fields should be final and must not be static.  By making them static, you've made all of your RegistrationNumber objects very weird, and quite the opposite of immutable.  Constructing one RegistrationNumber changes every previously generated RegistrationNumber!

getInstance() is a bit odd.  Conventionally, the name getInstance() would retrieve a singleton instance — it should the same object every time it is called.  What you have instead is a method that usually generates a new object, but occasionally returns an existing object.  I'm puzzled by the motivation behind that behaviour.


On Observables

My personal preference is to have as few Subscription objects and subscribe() invocations as possible. If I don't have mistakes in the refactored code, you can achieve a single subscribe() which does the same things as your code. I also got rid of sub2.

this.offerSubscription = this.service
    .isPending$
    .flatMap(data => {
        this.amount = null;
        const offerObservable = data ?
            this.service.getPending() :
            this.service
                .amount$
                .flatMap((data: Amount) => {
                    this.amount = data;
                    return this.service.getOffer();
                });
        return offerObservable;
    })
    .subscribe((offer: Offer) => this.offer = offer);

On TypeScript

sub, sub2, isPending$ and data are pretty bad names because they don't describe the entities they hold. I recommend changing them.

At the bare minimum, specify the type of the input parameter in your arrow function to make the code more readable: (data: Offer) => {...} or better (receivedOffer: Offer) => { ... }.


Rails: create a relationship between comment and user

Don't think your question belongs to this code review section. You would have gotten help much faster if had posted in stackoverflow instead. Anyway there are couple points you need to check.

The CreateComments migration must have been updated (or at least there was another migration that changed the table) because the migration does not say anything about user_id column but the your model has that.
Since comment is a polymorphic association, I'm not sure if it should be connected to user via a belongs_to to user. You are confused between the polymorphic association relation and the user's relation of a comment. They are different, a comment belongs to a Question (or Post, Thread... that why you have polymorphic here) and also belongs to a user who created the comment. Even better, you can have another polymorphic association for commenter (I will skip it to avoid adding noise to your question)
Does this mean, I should create a foreign_key in the comments migration to a user? NO
How can I go about getting the creator of the comment from the comment itself? Something like @comment.creator or @comment.user? They are just methods rails generated for you after you setup the association, so yeah you can have whatever you want

Here is what I would do to get comment.commenter and comment.commenter= to work:

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
  belongs_to :commenter, class_name: 'User', foreign_key: 'user_id'
end


Object instantiation with multiple parameters

The problem might be the semantic reference you are using as a pattern. You are creating a class as a "factory", but the actual Factory patter is related only to creating objects, and it seems that what you mean is actually the "Repository" pattern, where you can created, manage and retrieve objects.

And your case you would create a BlockRepository that it would be injected in the controller to be the interface between the controller and the actual blocks you need to create and retieve.

You can find related references on the links below:

http://heera.it/laravel-repository-pattern
https://stackoverflow.com/questions/21805939/laravel-using-the-repository-pattern


This implementation of Equals violates the contract of Equals.

From MSDN:

  The following statements must be true for all implementations of the
  Equals(Object) method. In the list, x, y, and z represent object
  references that are not null.

  ...
  x.Equals(y) returns the same value as y.Equals(x).

The problem is with this code

HashSet<Mask> uniqueMasks = new HashSet<Mask>(masks);
foreach(Mask mask in other)
{
    if (!uniqueMasks.Contains(mask)) return false;
}

return true;

As it's possible that all masks in other are in uniqueMasks, but uniqueMasks contains a mask not in other (i.e. other \$\subsetneq\$ uniqueMasks).

For example, the following code will print False True.

var x = new MaskCollection(new[] { new Mask(0), new Mask(0) });
var y = new MaskCollection(new[] { new Mask(0), new Mask(1) });
Console.WriteLine(x.Equals(y));
Console.WriteLine(y.Equals(x));

Given this implementation of Mask

public class Mask : IEquatable<Mask>
{
    private readonly int center;

    public Mask(int center)
    {
        this.center = center;
    }

    public int Center
    {
        get { return this.center; }
    }

    public bool Equals(Mask other)
    {
        return this.center == other.center;
    }

    public override int GetHashCode()
    {
        return this.center.GetHashCode();
    }
}

You could write

return new HashSet<Mask>(masks).SetEquals(other);

but I would probably recommend not overriding GetHashCode and Equals for this class, if you don't have a good reason to do so.


As I correctly understood, you want to export matrix in text file.
If its true, your code contains some mistakes:

for (int j = 0; j < matrix.GetLength(1) - 1; j++)

should be without decreasing length by 1 and Console.WriteLine("\n");
should be sw.WriteLine();

Also there is a not good idea to ask user to write a path. You could try to use SaveFileDialog instead.

Full solution

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int[,] matrix = new int[3, 2]
        {
            {1, 2},
            {3, 4},
            {5, 6}
        };
        ExportData(matrix);
    }
    private static void ExportData(int[,] matrix)
    {
        var saveFileDialog = new SaveFileDialog
        {
            Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
            FileName = "export.txt"
        };

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            using (StreamWriter streamWriter = new StreamWriter(saveFileDialog.FileName))
            {
                for(int i = 0; i < matrix.GetLength(0); i++)
                {
                    for(int j = 0; j< matrix.GetLength(1); j++)
                    {
                        streamWriter.Write($"\t{matrix[i, j]}\t");
                    }
                    streamWriter.WriteLine();
                }
            }
        }
    }
}

Just don't forget to add reference to System.Windows.Forms


I believe you don't need to use jquery deferred objects for this task. Just use script tags with sources - they will be downloaded in parallel from CDNs (try to use CDN, its always a good idea). The amount of parallel requests will be limited by browser restrictions.

Since your code just replaces default browser technique, for more sophisticated features (like dependent components, libraries that you really want to defer, because they are not used until some action on the page), use

http://jsload.net/
http://developer.yahoo.com/yui/get/
deferred objects as you did


This is built assuming you want no duplicates in the results, since the goal is a little unclear.
Quickly Finding Combinations
The function you should be using is Array.combination(n), which generates an enumerator that yields all combinations of size n from the array.  Once you have that it is a trivial matter to only select the combinations that sum to the target value.
My function here finds all combinations of size 2 to size data.length and then selects only the combinations with the correct sum.
def find_sum(data, target_sum)
  (2..data.length)
    .flat_map { |n| data.combination(n).to_a }
    .select { |arr| arr.inject(:+) == target_sum }
    #.uniq   # can call this to remove duplicates if necessary, depending on what the input data looks like
end

data = (1..9).to_a
pp find_sum(data, 10)
#[[1, 9],
# [2, 8],
# [3, 7],
# [4, 6],
# [1, 2, 7],
# [1, 3, 6],
# [1, 4, 5],
# [2, 3, 5],
# [1, 2, 3, 4]]


await user input with async/await syntax

First of all, I would not use Promises to do event based programming.
It is not used like that, so your code will get harder to follow.
Also, I would advise you to split up your functions more and omit some comments that way.

//// MAIN ///////

let services = [
    { url: "x", label: "1" },
    { url: "y", label: "2" },
    { url: "z", label: "3" },
];

showServicesToUser(services);

//// END MAIN /////

const serviceList = document.querySelector("#serviceList");

function createButtonFromService(service) {
    let button = document.createElement("BUTTON");
    button.innerHTML = service.label;
    button.addEventListener("click", function () {
        document.dispatchEvent(
            new CustomEvent("serviceChosen", { detail: service })
        );
    });
    serviceList.appendChild(button);
}

function showServicesToUser(services) {
    if (services.length < 1) return;

    serviceList.classList.remove("hidden");

    for (let service of services) {
        createButtonFromService(service);
    }
}

function chooseService(service) {
    console.log("service_chosen:", service);
    // ... go on....
}

document.addEventListener("serviceChosen", function (e) {
    serviceList.classList.add("hidden"); // hide again for we are done
    chooseService(e.detail);
}, { once: true });
.hidden{
  visibility: hidden
}

My proposed code above is written in a scripted kind of way, with a global variable (serviceList), but you could also write this all in a class (especially if you have more code), to make it more readable and reusable.

class ServiceChooser {
    serviceListSelector;
    serviceList;
    services;

    constructor(serviceListSelector, services) {
        this.serviceListSelector = serviceListSelector;
        this.services = services;

        this.serviceList = document.querySelector(serviceListSelector);

        document.addEventListener(`serviceChosen${this.serviceListSelector}`, (e) => this.chooseService(e.detail), { once: true });
    }

    createButtonFromService(service) {
        let button = document.createElement("BUTTON");

        button.innerHTML = service.label;
        button.addEventListener("click", () => {
            const event = new CustomEvent(`serviceChosen${this.serviceListSelector}`, { detail: service });
            document.dispatchEvent(event);
        });

        this.serviceList.appendChild(button);
    }

    chooseService(service) {
        this.serviceList.classList.add("hidden");
        console.log("service_chosen:", service);
        // ... go on....
    }

    showServicesToUser() {
        if (this.services.length < 1) return;

        this.serviceList.classList.remove("hidden");

        for (let service of this.services) {
            this.createButtonFromService(service);
        }
    }
}

//// MAIN ///////

let services = [
    { url: "x", label: "1" },
    { url: "y", label: "2" },
    { url: "z", label: "3" },
];

const sc = new ServiceChooser('#serviceList', services);
sc.showServicesToUser();

// now you could add 2 service choosers, sperate from each other
const sc2 = new ServiceChooser('#serviceList2', services);
sc2.showServicesToUser();

//// END MAIN /////
.hidden{
  visibility: hidden
}


Convert float price to integer price without commas

For me at least, it would be more natural to think of the operation as a multiplication by 100:

def price_format_gateway(price):
    return '{:.0f}'.format(100 * price)


Echoing all of VincentRG's points, with a little clarification and demonstration:

The only reason to wrap code in a if __name__ == '__main__' block is to keep it from being executed when your module is imported by another module.  By that token, the fact that you initialize bot_choices outside of that block means that those random choices will be determined only once at the time of import, so the importing module will get the same result every time it calls RPS().  This is probably not what you want.  It doesn't affect the way your program runs since you don't actually have any other modules, but if you're going to check for __main__ you should understand why you're doing that and apply the same logic to other parts of your code.
This does not need to be a class and therefore should not be.  Here's how to write it as a single simple function (this is mostly just taking your existing code and moving it around):

import random

def rock_paper_scissors() -> None:
    bot_choice = random.SystemRandom().choice(['Rock', 'Paper', 'Scissors'])

    user_choice = str(input('(R)ock, (P)aper, (S)cissors: ')).upper()
    if user_choice not in ['R', 'P', 'S']:
        print('Invalid Input!')
        return

    if (user_choice == 'R' and bot_choice == 'Paper'
            or user_choice == 'P' and bot_choice == 'Scissors'
            or user_choice == 'S' and bot_choice == 'Rock'):
        print('Result: Computer Won!')
    elif user_choice == bot_choice[0]:
        print('Result: Tie!')
    else:
        print('Result: You Won!')

    print(f'\nComputer Choice: {bot_choice}\nYour Choice: {user_choice}')

if __name__ == '__main__':
    rock_paper_scissors()

More notes:

Not necessary to check user_choice for truthiness if you're already checking it for membership in a collection of truthy values.
The name bot_choices is confusing if it's a single choice.  Changed it to bot_choice.
There's no reason to name the choices variable since you never use it again after picking bot_choice.
You can simplify the tie check way down by just checking the user choice against the first letter of the bot choice.
This would be simpler yet if you defined the choices as an Enum and had the player and bot use the same enum instead of their own hardcoded strings.

If you have no need to reuse this function or this module, this script doesn't even need to define a function.  You could have a file that just looks like:

import random

bot_choice = random.SystemRandom().choice(['Rock', 'Paper', 'Scissors'])

user_choice = str(input('(R)ock, (P)aper, (S)cissors: ')).upper()
if user_choice not in ['R', 'P', 'S']:
    print('Invalid Input!')
    exit()

if (user_choice == 'R' and bot_choice == 'Paper'
        or user_choice == 'P' and bot_choice == 'Scissors'
        or user_choice == 'S' and bot_choice == 'Rock'):
    print('Result: Computer Won!')
elif user_choice == bot_choice[0]:
    print('Result: Tie!')
else:
    print('Result: You Won!')

print(f'\nComputer Choice: {bot_choice}\nYour Choice: {user_choice}')

and it would behave exactly the same.

Here's how you might use an Enum to specify the choices:

import enum
import random

class Choice(enum.Enum):
    ROCK = "R"
    PAPER = "P"
    SCISSORS = "S"

what_beats = {
    Choice.SCISSORS: Choice.ROCK,
    Choice.ROCK: Choice.PAPER,
    Choice.PAPER: Choice.SCISSORS,
}

bot_choice = random.choice([c for c in Choice])

try:
    user_choice = Choice(input('(R)ock, (P)aper, (S)cissors: ').upper())
except ValueError:
    print('Invalid input!')
    exit()

if what_beats[user_choice] == bot_choice:
    print('Result: Computer Won!')
elif user_choice == bot_choice:
    print('Result: Tie!')
else:
    print('Result: You Won!')

print(f'\nComputer Choice: {bot_choice.name.title()}'
      f'\nYour Choice: {user_choice.name.title()}')


Set default value for remaining size of list by use of Java 8 and Stream

As mtj already mentioned in the comment, adding stream trickery to fulfill this need only makes the code less readable. Streams are nifty, exciting and popular but they are not always the right tool for the job. Sometimes a plain loop is still the best choice.
The common pattern in padding a collection (well, most often it's a string that gets padded) to certain size is to use a while loop. It has least amount of excess variables and code and the syntax communicates intent quite naturally ("while size is less than 16, do this"). But this still only tells that you are intentionally padding the collection to 16 elements. You also need to document in comments the reason why you are padding the collection to 16 elements.
List<Address> addresses = cardAccountDetails
    .stream()
    .map(AccountService::buildAddress)
    .collect(Collectors.toList());

while (addresses.size() < 16) {
    addresses.add(buildDefaultAddress());
}


This looks to me like it will work as intended. I have a few suggestions for improvement though:

You keep the count variable up to date but never use it's value for anything. You can either remove it or provide a size() method.
You might change your push() method to

public void push(Object item){
   top = new Node(item, top);
   count++;
}

If top is null, you set node.next to null in the Node constructor anyways.
 - If you do this, you can subsequently delete the Node(Item) constructor

I personally would make the item and next member variables in Node final to prevent accidental mutations
(Instead of accepting Object as your items you might want to introduce Generics into your class. But this is an advanced topic and is maybe too hard for you as a beginner)


Keep parsing JSON response until a field becomes false using GSON

Overall I think it is a good solution.
Exception handling
I think getIds()-method cannot handle exceptions properly in the context of any application.
Currently it makes the result look like as nothing has happened even an exception is thrown. I do not think that callers can make valid assumptions on the returned value so I suggest to encapsulate the general Exception into a RuntimeException (or some of your own). The caller of the method should know if the result is valid. If you want the caller continue to process with partial results then you can make your own exception containing the information received so far. But to abstract from errors is dangerous.
The decision of throwing exceptions is as important as catching, rethrowing, wrapping, logging and handle them.
If you throw an exception you do it because you want to indicate that the assumptions a method has are not met so it cannot fulfill its work.
If you want to rethrow an exception the purpose mostly is to intercept information.
If you wrap an exception you want to

map the Exception to an exception of YOUR domain
make the Exception signature irrelevant (RuntimeException)

An exception should be handled at a point it can be handled. And this is not neccessarily the method it occurs.
Logging an exception is the last option for exceptional cases that have no previous mentioned handle. And this is also not neccessarily the method it occurs.
Remove Optional-construct
To exit the loop you determine the existance of a next "url". That should be your single point of truth. "getResponse" is called if "hasMore" is true. But If "getResponse" gets called then it is called under the assumption that there "is" more. If the getResponse-method cannot fulfill the work it is an exception. My view is that getting an "Optional" when "hasMore" has determined before is contradictory.
Throw an exception and the same mechanism as described in "Exception handling" is used. It is transparent to the caller. The caller always will get all necessary information and can decide on its own what to do. Either the getIds()-method returns normal or an exception is thrown that contains the Ids received so far.
Ambigious next-key and semantic redundancy
Currently you have two next-keys holding different values: boolean and String. Theoretically a JsonObject should have unique keys. But any behaviour you rely on to retreive values from this key is specific to the JSON library you use. Maybe GSON does it right somehow.
Furthermore you have semantical redundancy. The existance of the next URL is sufficient information to determine if there is a next URL.
My suggestion is to get rid of the semantic redundancy as early as possible so that further algorithms work with a single source of truth. Maybe you have a preprocession of the Json String and return the JsonObject as the return value of your execute-method().
Reuse JsonParser
I think that is a little issue. But I would reuse the JsonParser-instance as I do not know if this is an expensive operation to instantiate this kind of object.
Extracting constants
There are code fragments that should be extracted to constants. the "key" String is repeated but adresses the same semantic. But also the other keys to access the json object.
Variable scope
The subjects become pedantic... You may reduce the scope of the "hasMore" variable by using a for loop rather than a while loop.
Types
You should also have a look at your GSON-Types. To determine the id you ask an JsonElement. A JsonElement may also be a JsonNull-Object (see here). Maybe you have to introduce some type-check.
Code
private static final String KEY_NEXT = "next";
private static final String KEY_URL = "url";
private static final String KEY_RESULT = "result";
private static final String KEY_ID = "id";

public List<String> getIds() {
    List<String> ids = new ArrayList<>();
    try {
        String url = generateUrl();
        final JsonParser jsonParser = new JsonParser();
        for (boolean hasMore = true; hasMore;) {
            JsonObject jobject = execute(url);
            JsonArray jarray = jobject.getAsJsonArray(KEY_RESULT);
            for (JsonElement type : jarray) {
                ids.add(type.getAsJsonObject().get(KEY_ID).getAsString());
            }
            hasMore = jobject.has(KEY_NEXT); // assumption, that only the next-key with the url is possibly present
            if (hasMore) {
                url = PREFIX + jobject.getAsJsonObject(KEY_NEXT).get(KEY_URL).getAsString();
            }
        }
    } catch (Exception ex) {
        throw new PartialResultException(ex, ids);
    }
    return ids;
}

private static class PartialResultException extends RuntimeException {

    private List<String> idsReceivedSoFar;

    public PartialResultException(Exception ex, List<String> idsReceivedSoFar) {
        super(ex);
        this.idsReceivedSoFar = idsReceivedSoFar;
    }

    public List<String> getIdsReceivedSoFar() {
        return idsReceivedSoFar;
    }

}

// Example call
public void caller() {

    List<String> ids = new ArrayList<>();

    try {
        ids.addAll(getIds());
    } catch (PartialResultException e) {
        // omit this if the caller is not interested in the ids received so far if an exception occured
        ids.addAll(e.getIdsReceivedSoFar());
    }

    // code that uses the ids
    for (String string : ids) {
        ...
    }

}

The execute-method will either wrap the occuring exceptions to a RuntimeException...
private JsonObject execute(final String url) {
    try (AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient()) {
        Future<Response> future = asyncHttpClient.prepareGet(url).execute();
        Response response = future.get();
        final JsonParser jsonParser = new JsonParser();
        JsobObject jsonResponse = jsonParser.parse(response.getResponseBody(StandardCharsets.UTF_8.displayName())).getAsJsonObject();
        removeNextKeyBooleanValue(jsonParser);
        return jsonResponse;
    } catch (IOException | InterruptedException | ExecutionException ex) {
        throw new RuntimeException(ex);
    }
}

... or you may throw them
private JsonObject execute(final String url) throws IOException, InterruptedException, ExecutionException {
    try (AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient()) {
        Future<Response> future = asyncHttpClient.prepareGet(url).execute();
        Response response = future.get();
        final JsonParser jsonParser = new JsonParser();
        JsobObject jsonResponse = jsonParser.parse(response.getResponseBody(StandardCharsets.UTF_8.displayName())).getAsJsonObject();
        removeNextKeyBooleanValue(jsonParser);
        return jsonResponse;
    }
}

The point is that there is no rule to catch and handle an exception where it occurs or as early as possible. The rule is: it has to be the semantic correct location under the assumptions of the involved methods.


Python is notoriously slow with native loops; i.e.

for j in range(nRun):
    ...
    for t in range(T):
        ...

is probably your bottleneck. I haven't tried to understand necessarily what you are coding but can you vectorise some calculations?

Something like

sigma = np.ones(nActions)
mu = np.array([-0.4677,-0.1249,1.4790,-0.8608,0.7847,0.3086,-0.2339,-1.0570,-0.2841,-0.0867])
def Reward(action:int, mu:np.ndarray, sigma:np.ndarray):
    return mu[action] + sigma[action]*np.random.normal()

is better replaced by:

temp_rvs = np.random.rand(nRun * T, 10)
reward_arr = mu + sigma * temp_rvs

then you can just index an existing variable instead of generating random variables each time through a function in your loop, i.e. you can:

reward[(j+1)*T, a]

But this takes up \$10 * nRun * T * 8\$ bytes of RAM to store the random variables.

I answered a similar question to this here: How to simulate this Gamma expansion in a Python way perhaps it might give you some ideas.


Router for quering MySQL results in NodeJS

Are we actually using the obj variable? It seems like you are not using it unless you were intending to pass to the render function. I don't think the try block is necessary. You can first check if results contains elements in it, so doing results[0].X will not return you an error since results[0] will never be undefined.

Here's an improved version:

router.get('/:id', function(req, res) {
  const getId = req.params.id;

  db.con.query('SELECT * FROM employees where id = ?', getId, function(err, results) {
    if (err || !results.length) {
      console.log('error in query');
      res.status(500).render('error', { error: err, id: getId });
      return;
    }

    var obj = {
      id: results[0].id,
      name: results[0].name,
      location: results[0].location
    };
    res.render('showuser', obj); // Assuming you're using obj to render
  });
});


Do I need to remove these event listeners?

Quick answer:

Maybe yes, maybe no. Yes, they'll be garbage collected now, but cleaning up after yourself is not a bad habit to get into. It doesn't hurt to do so.

What you do need to be careful of, however, is that you clean it up right.

Compare:

loader.addEventListener(Event.COMPLETE, onComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);

With:

loader.removeEventListener(Event.COMPLETE, onComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onComplete);

and you'll soon notice the mistake: IOErrorEvent.IO_ERROR is mapped to onError, but the removeEventListener assumes it's mapped to onComplete!

Additionally, you have a unnecessary variable here:

var res:Object;

It's not used by anything, so I'd remove it.


Converting an integer to Greek and Roman numerals

Your conversion routines make no sense.  I don't see why 45 should be ϜϜϜϜϜϜϜγ, as stated in your doctest.  I also get this clearly wrong result:

>>> convert_init(1939, ROMAN_NUMERAL_TABLE)
'XLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXLXVIV'

Since you are using Unicode for the Greek numerals, I should be pedantic and point out that the Roman numerals should also use the appropriate Unicode characters.

The docstring would be better written as

def convert_init(number, convert_to=None):
    """
    Convert a number to a Greek or Roman numeral

    >>> convert_init(45, convert_to=ROMAN_NUMERAL_TABLE)
    'XLV'
    """
    …

… since the print statement obscures the fact that you are returning a string.  (Based on just your docstring, it could also be returning some other kind of object, whose __str__ produces the desired output.)

What is convert_init?  Did you mean convert_int?

Your args = opts.parse_args() is not guarded by if __name__ == '__main__' as it should be.  You shouldn't need to cast int(args.greek) or int(args.roman), since argparse should take care of the type=int for you.


Both your pack and unpack scripts will fail if any of the targets contain spaces (or other shell meta-characters) in their name. Generally it's almost always a bad idea to insert arguments into commands using string interpolation.

I assume you're using backticks rather than system because you don't want the output of the invoked commands to go to the screen. In that case you can use IO.popen, which since ruby 1.9 can take an array as its first argument.

As a trivial sidenote: There doesn't seem to be any point in passing the -v flag to tar if you're not going to print its output, so I'd remove it.


I only see some possible stylistic/reusability improvements:

You use decltype(std::declval<T>() + std::declval<T>()) five times in the function (plus the one in the return type). You could probably typedef that to improve readability. I don't know how you would call it, but I am pretty sure that you can find a meaningful name.
By the way, are there many types for which decltype(std::declval<T>() + std::declval<T>) is different from T while still being amp compatible? If it is the case, that may break some other pieces of your code anyway (I didn't check though; that's a wild guess).
Whenever possible, try to use std::begin and std::end instead of the member functions. It helps to write reusable code; you might someday want to extract parts of your function to write smaller and more generic functions that could work on old C arrays.
By default, if you don't specify the rank of an array_view, it is one. Therefore, you actually don't have to specify it since you always use 1.
Your lines are really long. As I said in the comments, you might want to split some of them to improve readability:

futTailSum = std::async( std::launch::async, [&vecTail]
    {
        return concurrency::parallel_reduce( std::begin(vecTail),
                                             std::end(vecTail),
                                             static_cast<T>(0) );
    } );


Unnecessary work

Consider a list of \$n\$ elements, then insert(1,0) will move approximately \$2n\$ elements in the array when all it really had to do was swap the two elements.

Note that an optimised insert(source, destination) only needs to move source - destination elements. As this looks like self-learning or possibly homework, I'll leave the details to you.

Use binary search

You can binary search for the insertion point to improve the performance even further.


Improving my Tic Tac Toe Solution in Scala

you can remove main method and use extends App. It's safe 3 line of code.
replace Array('1', '2', '3', '4', '5', '6', '7', '8', '9') on ('1' to '9').toArray
I prefer always use type annotation if it is not clear. E.g.: val nextMove: Int = readMove(board)
use Intellij autoformat (ctrl + alt + L)
it is good idea to say user what is wrong with his input before prompt new one
[Char].toString.matches("[1-9]") may be replaced on [Char].isDigit (PS: may be it is not correct, because 0 is also digit)
don't use return keyword, especially in foreach, map and so on. It is not what you want, at least in this cases. foreach + forall + return should be replaced on contains + forall or something.
usually list map f used only for non-chained calls, but not for list map m filter filter collect g, because it is unclear for reader. UPDATE: also this syntax used for symbol-named functions, like +, ::, ! (in akka).
you can use special type for positive digit, for example, case class PosDigit(v: Int) {require(v >= 0 && v <= 9, s"invalide positive digit: $v")}
there is no essential reason to pass board as argument. Commonly if argument is passed, it is not changed. In your code it is not.

UPDATE for 10. In functional programming the clear way is to pass immutable collection to function and return new one if you need. It is programming without side effects. In OOP there is way to use mutable collection of class (or class's object). Scala both OOP and FP language.
Sorry for my English.


Script to temporarily drop admin privileges

Usability

The current script works in a dual mode:

When run without parameters, it toggles group membership
When run with a parameter, the parameter is executed as root, on the condition that the user is not currently an admin

I find the conditional execution in the second mode a bit confusing.
That is, when a parameter is given, but the user is admin,
the command won't be executed.
Instead the script will drop membership.
If you really want to execute the command you have to re-run the same command line, which could be annoying.

I suggest to change the behavior so that when a parameter is given,
execute it always, after the delay, regardless of the membership status.
I think this won't conflict with your main purpose,
but it would improve the usability of the script.

Cross-platform way to add/remove users

As a first step to making the script more portable,
it would be good to separate the platform dependent parts from the platform independents ones, for example:

add_to_admin() {
    dscl . -append /Groups/admin GroupMembers "$uGuid"
}

remove_from_admin() {
    dscl . -delete /Groups/admin GroupMembers "$uGuid"
}

You could have the platform-specific implementations in separate files,
and then source the appropriate flavors as needed.

Minor technical improvements

Instead of sed -nE 's/GeneratedUID: (.*$)/\1/p' to get the UID part,
it would be simpler to use cut -f2 -d' ' or awk '{ print $2 }'.

This seems to check if $1 empty:

if [[ -z "${1+x}" ]]; then

Unless I'm missing something, this is equivalent but simpler:

if [ -z "$1" ]; then

When $1 appears in the middle or near the end of a script,
it can be hard to remember where it comes from and what it's supposed to be.
It's better to assign command line arguments to a meaningful variable early in the script, and refer to them by that name.
That also makes it easier to find all locations where it is used.
For example, you could put near the top of the file:

cmd=$1