Assuming that the id's in users_info exist in users_time, INNER JOIN (or just JOIN) is the way to merge the tables.  If id's in user_info might not exist in users_time then use LEFT JOIN to allow null values in totalHoursWorked.

Assuming you want all four columns' data to be included in your echo'ed json string (your posted code isn't do that), you can just fetchAll() directly into your json_encode() and echo it -- all at once.

SQL: (Demo)

$sql = "SELECT i.id,
            MAX(i.firstName),
            MAX(i.middleName),
            MAX(i.lastName),
            CAST(SUM(TIMEDIFF(t.dateTimeOut, t.dateTimeIn)) AS TIME) AS totalHoursWorked
        FROM users_info i
        INNER JOIN users_time t ON i.id = t.user_id
        GROUP BY i.id";
$query = $pdo->query($sql);
echo json_encode($query->fetchAll(PDO::FETCH_ASSOC));

If you are truly only returning a single column (totalHoursWorked) without any of the other data, then I don't see the need to involve the user_info table at all.


Printing the largest sum from integers in a file

Brad, you code compiles cleanly, which is a good sign :-)  Clearly it could be split into functions. An obvious approach would be to split the reading of the values from the processing of those values.

I would take a slightly different approach, but remember there is no one "correct" solution. I would read and process the file
one line at time.  So the pseudo code would be:

    for each line
        read the line data  (function)
        find greatest sum in line  (function)
        store sum if bigger than max value found

This approach avoids the need for a multi-dimensional array and means you
  can handle an arbitrary number of lines.

Note that nested loops are often not desirable, but are sometime necessary.  Finding the greatest sum in the line looks like a case where a nested loop is optimal.  But this double loop should be a function.

Also check the return value from fscanf.  If you do this you can avoid processing a blank line.

A few comments on notation:

Be consistent!!!  This is important although it might seem trivial.  Many people
reading your code and seeing some places where a comma is followed by a
space (preferred) and some where it is not will judge the code badly.  Similarly,
comments should be consistent - follow // by a space.
Defining just one variable per line is usually preferred.
Leave a space after keywords (if, else, for, while etc). Similarly,
leave a space before and after = (or != etc). (these are my preferences, others might differ).
Many people, including me, prefer code and comments to extend to no more than 80
columns.
Send error messages to stderr and on error from system and library calls
that set errno (the global error variable) use perror (which prints to
stderr).
Exit on failure with exit(EXIT_FAILURE);
On completion, return a value from main, normally return EXIT_SUCCESS
Oh and finally, delete the useless comments. Nearly all of your comments are worse than pointless - they add noise, not information.


Binary Search Tree insert while keeping track of parent for node to be added - iteration 2

You should check the result given by malloc, because otherwise your program may crash. Maybe not on your system right now, but basically, memory allocation can fail, and if it does, your program will crash afterwards by dereferencing a null pointer.

Additionally, your createAChild function should not take a node pointer. What happens if I pass in an existing object? You just overwrite it. That's a cause for memory leaks. Treat createAChild as a constructor: either give it a cleanly allocated node struct, or let it allocate its own struct.


Proper practice using enums in header files

Prefer C++ headers

If you #include <cmath> instead of <math.h>, the mathematical functions will be safely and unambiguously in the std namespace.

Pass read-only parameters by const reference

Instead of copying the input vectors, it's usually more efficient to pass const references to them:

double cosine(const std::vector<double>& A, const std::vector<double>& B, bool similarity);

double euclidean(const std::vector<double>& A, const std::vector<double>& B, bool similarity);

double distance(const std::vector<double>& A, const std::vector<double>& B,
                Metric metric, bool similarity = false);

Use auto to deduce types

Instead of writing

std::vector<double>::iterator A_iter = A.begin();
std::vector<double>::iterator B_iter = B.begin();

We can ask the compiler to deduce the correct type:

auto A_iter = A.begin();
auto B_iter = B.begin();

This also makes it easier if you ever want to change the type of A and B (perhaps even to a template argument type).  In fact, by changing to const references, we already changed the type (to std::vector<double>::const_iterator), but auto isolates us from that.

Use the right kind of exception

You could be more specific, and use std::invalid_argument for the error type here:

if (d_a == 0.0f || d_b == 0.0f) {
    throw std::invalid_argument("Vectors must have a magnitude greater than zero");
}

I've changed the wording above, because length usually means the number of elements when we're using standard collections.

Don't compare booleans against false

This is hard to read:

if (similarity == false) {
    // negative case
} else {
    // positive case
}

You can re-write it as

if (similarity) {
    // positive case
} else {
    // negative case
}

This will normally produce identical code, but the cognitive overhead is reduced.

Avoid non-standard extensions

Although many implementations define a constant called M_PI, this isn't specified by any standard.  Thankfully it's easy to make your own value, using the knowledge that tan(¼π) is 1:

static const auto pi = 4*std::atan(1);

Avoid std::pow(x, 2)

To square a number, it's simpler and more efficient to multiply it by itself.  pow() is very general (handling non-integer powers), and usually works by multiplication of logarithms.  It's worth introducing a temporary to avoid that:

    //sq_dist += pow(*A_iter - *B_iter, 2);
    auto dist = *A_iter - *B_iter;
    sq_dist += dist * dist;

Don't fall off the end of non-void functions

Here, we're assuming that we're always passed a valid enum constant:

switch (metric) {
    case Metric::Cosine:
        return cosine(A, B, similarity);
    case Metric::Euclidean:
        return euclidean(A, B, similarity);
}
// implicit return

Robust code checks that we don't flow out of the switch:

switch (metric) {
    case Metric::Cosine:
        return cosine(A, B, similarity);
    case Metric::Euclidean:
        return euclidean(A, B, similarity);
}

throw std::invalid_argument("Invalid metric");

Invalid enum values shouldn't happen, but it costs little to be defensive against a mistaken cast.

Design issues

It's not clear whether cosine() and euclidean() are intended to be part of the public interface.  If they are not, then give them internal linkage (e.g. by use of the anonymous namespace, or with the static keyword), and consider moving the similarity parameter out of them.

I prefer to avoid booleans that change the meaning of functions like that; see if you agree when you see my full example.

Here's a full version with the above issues all addressed (and assuming that cosine() and euclidean() are intended to be internal detail).

Declarations

This is what I'd put in the header file (let's call it similarity.h):

#ifndef SIMILARITY_H
#define SIMILARITY_H

#include <vector>

enum class Metric { Cosine, Euclidean };

double distance(const std::vector<double>&, const std::vector<double>&, Metric);
double similarity(const std::vector<double>&, const std::vector<double>&, Metric);

#endif

Implementation

Having included the header, here's the C++ file:

#include "similarity.h"

#include <cmath>
#include <stdexcept>

namespace {

    double cosine_distance(const std::vector<double>& a, const std::vector<double>& b)
    {
        double mul = 0.0;
        double d_a = 0.0;
        double d_b = 0.0;

        auto ia = a.begin();
        auto ib = b.begin();

        for (;  ia != a.end();  ia++, ib++) {
            mul += *ia * *ib;
            d_a += *ia * *ia;
            d_b += *ib * *ib;
        }

        if (d_a == 0.0f || d_b == 0.0f) {
            throw std::invalid_argument("Vectors must have a magnitude greater than zero");
        }

        return mul / std::sqrt(d_a * d_b);
    }

    double euclidean_distance(const std::vector<double>& a, const std::vector<double>& b)
    {
        double sq_dist = 0.0;
        auto ia = a.begin();
        auto ib = b.begin();

        for (;  ia != a.end();  ia++, ib++) {
            auto dist = *ia - *ib;
            sq_dist += dist * dist;
        }

        return std::sqrt(sq_dist);
    }

}

double distance(const std::vector<double>& a, const std::vector<double>& b, Metric metric)
{
    if (a.size() != b.size())
        throw std::invalid_argument("a and b must be the same size!");
    if (a.size() < 1)
        throw std::invalid_argument("Empty vectors belong to no metric space");

    switch (metric) {
    case Metric::Cosine:
        return cosine_distance(a, b);
    case Metric::Euclidean:
        return euclidean_distance(a, b);
    }

    throw std::invalid_argument("Invalid metric");
}

double similarity(const std::vector<double>& a, const std::vector<double>& b, Metric metric)
{
    static const auto pi = 4*std::atan(1);

    switch (metric) {
    case Metric::Cosine:
        return std::acos(distance(a, b, metric)) / pi;
    case Metric::Euclidean:
        return 1.0 / distance(a, b, metric);
    }

    throw std::invalid_argument("Invalid metric");
}

Note that I include our own header first.  That's a helpful approach, to improve our chances of discovering if it accidentally depends on something it doesn't explicitly include.


Split a string of hostnames, expand from regex, return non-duplicated names in original order

To jump to the conclusion first, I would rewrite the function like this:

sub hostname_regex_expand {
    my ($patterns_ref, $hostnames_ref) = @_;
    my @patterns = @$patterns_ref;
    my @hostnames = $hostnames_ref ? @$hostnames_ref : get_hostlist();

    my %results;
    foreach my $pattern (@patterns) {
        my @found = grep(/$pattern/, @hostnames);
        @found = $pattern unless @found;
        @results{@found} = ();
    }

    return sort keys %results;
}

First of all, the original variable names were not so good: @target_list, %host_hash, and $host_string contain in the name their types (list, hash, string), which is not normal or necessary. What's worse is that @host_names and $host_name are storing host name patterns, not really host names.

In terms of the logic, instead of iterating over each hostname to try to see if it matches a pattern, it would be more straightforward to use a grep.

It seems you really want to use two list parameters:

List of patterns
List of hostnames

So I changed the function to take two list references, it's cleaner than the original.

I took a shortcut that you might not like: instead of adding matched hosts and patterns to @hosts, I use the %results map, and return the sorted keys. The title of your post (and the original) suggests that you want to preserve the original order. If that's a requirement, not a problem, we can refactor like this:

sub hostname_regex_expand {
    my ($patterns_ref, $hostnames_ref) = @_;
    my @patterns = @$patterns_ref;
    my @hostnames = $hostnames_ref ? @$hostnames_ref : get_hostlist();

    my @ordered;
    my %results;
    foreach my $pattern (@patterns) {
        my @found = grep(/$pattern/, @hostnames);
        @found = $pattern unless @found;
        foreach my $item (@found) {
            if (!$results{$item}) {
                push(@ordered, $item);
                $results{$item} = 1;
            }
        }
    }

    return @ordered;
}


The dilemmas here:

query is an IQueryable. If you join it with offices, i.e. without AsEnumerable(), Entity Framework will throw an exception about primitive values, which is an obscure way of telling you that it can't translate offices into SQL.
So join in memory, i.e. with query.AsEnumerable(). But now all data from query will be pulled into memory, which has two adverse effects: neither the reduction in numbers of records by joining with offices nor the reduction in width of the result set by selecting only a restricted number of properties can be translated back to the SQL query.

You obviously want to benefit from both strands of data reduction.

As for the reduction in number of rows, there's no way to make Entity Framework join with local data other than lists of primitive values. Even then, joining is rather inefficient because EF has to convert the local list into a temporary SQL table (sort of), which requires a considerable amount of code. It's more efficient to use Contains, which translates into an IN statement:

var officesCodes = offices.Select(o => o.Code).ToList();
var employeeInfo = from e in employees
                   where officesCodes.Contains(e.Office)
                   select ...

Now employeeInfo is an IQueryable, so it's possible to reduce the width of the result set by projection:

var employeeInfo = from e in employees
                   where officesCodes.Contains(e.Office)
                   select new
                   {
                       EmployeeId = e.EmployeeId,
                       FullName = e.FullName,
                       Office = e.Office,
                       Position = e.Position,
                       Languages = e.Languages
                   };

This achieves the desired data reduction. But now you haven't got EmployeeData objects yet. Can't be done by this query, because they also contain data from offices. This final step can only be achieved by joining the result in memory with offices:

var employeeData = from e in employeeInfo.AsEnumerable()
                   join o in offices on e.Office equals o.Code
                   select new EmployeeData
                   {
                       EmployeeId = e.EmployeeId,
                       FullName = e.FullName,
                       Office = e.Office,
                       Area = o.Area,
                       Region = o.Region,
                       OfficeName = o.Name,
                       Position = e.Position,
                       Languages = e.Languages
                   };


Displaying member information from a CSV file

There are a number of issues with this code; the first two items below are seriously bad habits.

Inappropriate use of functions.  Functions are not goto labels.  Having optionA call itself or nextchoice() makes no sense.  This must be corrected — it is a fundamental misunderstanding of how to write programs.
Use of global variables.  If you design your functions properly, there should be no need for any global variables.
Lack of abstraction.  There is nothing in common between these two functions, other than the fact that they both read from members.txt.  It would be a good idea to have a function to read, interpret, search the file.  Furthermore, since the data are in a csv format, you should use the Python csv module.
Using string comparison for numbers. This is a bug:

listed[5].strip('\n')<listed[4]

… because you are comparing numbers ASCIIbetically.
Lack of documentation. optionA and optionB are both mysterious names for functions.  It's not immediately clear what the members.txt file looks like, or why optionB ignores rows whose membership type column is not F.
File descriptor leak.  If you call open() without a corresponding call to close(), you might leak file descriptors.  In Python, you almost always want to call open() using a with block.
Member search by all attributes. You ask the user to enter a member number.  However, when you do

listed = line.split(",")
if member in listed:
    …

… you are actually searching all fields, not just the third column.
Python style guide.  PEP 8, the official Python style guide, says that variable names should be lower_case_with_underscores unless you have a good reason to deviate from the norm.

Suggested solution

import csv
from decimal import Decimal

MEMBERS_TXT_FIELDS = [
    ('Team Code', str),
    ('Date of joining', str),
    ('Member number', str),
    ('Membership type', str),
    ('Fee', Decimal),
    ('Amount paid', Decimal),
]

def members(member_number=None):
    with open('members.txt') as member_file:
        csv_file = csv.reader(member_file)
        for row in csv_file:
            member = {
                field_name: conv(val)
                for (field_name, conv), val in zip(MEMBERS_TXT_FIELDS, row)
            }
            if member_number is None or member_number == member['Member number']:
                yield member

def show_single_member(member_number):
    for member in members(member_number):
        print("""
Team Code: {Team Code}
Member number: {Member number}
Date of joining: {Date of joining}
Membership type: {Membership type}
Amount paid: {Amount paid}""".format(**member))
        return True
    return False

def show_owing_members():
    def value_fmt(field_def, member):
        field_name, width = field_def
        value = member[field_name]
        if isinstance(value, Decimal):
            return "£{0}".format(value.quantize(Decimal('0.01'))).rjust(width - 1) + ' '
        else:
            return str(member[field_name]).ljust(width)

    TABLE_FIELDS = [
        # Field name, width
        ('Team Code', 11),
        ('Member number', 20),
        ('Fee', 9),
        ('Amount paid', 17),
        ('Amount outstanding', 31),
    ]

    # Print headings
    print(''.join(field.ljust(width) for field, width in TABLE_FIELDS))
    print(''.join('-' * width for field, width in TABLE_FIELDS))

    total_outstanding = Decimal('0.00')
    for member in members():
        if member['Membership type'] == 'F' and member['Amount paid'] < member['Fee']:
            member['Amount outstanding'] = member['Fee'] - member['Amount paid']
            print(''.join(value_fmt(field_def, member) for field_def in TABLE_FIELDS))
            total_outstanding += member['Amount outstanding']
    print()
    w = sum(width for field, width in TABLE_FIELDS if field != 'Amount outstanding')
    print("Total outstanding: ".rjust(w) + "£{0}".format(total_outstanding))

def menu():
    while True:
        print("A: Member lookup")
        print("B: Outstanding fees")
        print("Q: Quit")
        choice = input("Choice: ").upper()
        if choice == 'A':
            ok = show_single_member(input("Please enter the member number: "))
            if not ok:
                print("No such member")
        elif choice == 'B':
            show_owing_members()
        elif choice == 'Q':
            break
        print()


While you seem to be on a good way, your code still hast a global variable it does not need. You can simplify that code a lot by using something like this:

OFFSETS = {"w": (0, -1), "Up": (0, -1),   # weird coordinate system...
           "a": (-1, 0), "Left": (-1, 0),
           "s": (0, 1), "Down": (0, 1),
           "d": (1, 0), "Right": (1, 0)}

def get_offsets():
    for key, offset in OFFSETS.items():
        if keyboard.is_pressed(key):
            return offset
    return 0, 0

This just returns a tuple of changes for each defined key, and zero otherwise.

You should do as little as possible inside your loop (since that affects performance). You can set the graphic options once before the loop if you afterward continue modifying the object(s) in place. With the Rectangle that is easy, since you can just overwrite the p1 and p2 attributes. The two Point objects have an internal _move method that you can use (or you code it yourself):

class Point:
    ...
    def _move(self, dx, dy):
        self.x += dx
        self.y += dy

Another small performance optimization is to do nothing if the rectangle does not move. I would also add a if __name__ == "__main__": guard to allow importing from this module without running the game and follow Python's official style-guide, PEP8, which recommend adding spaces around operators. It also recommends putting imports from different modules on separate lines and not using unnecessary parenthesis.

With these changes you get this for your main:

def main():
    x = 0
    y = 0
    radius = 10
    speed = 20
    lower_left = Point((width / 2) - radius, (height / 2) - radius)
    upper_right = Point((width / 2) + radius, (height / 2) + radius)
    player = Rectangle(lower_left, upper_right)
    player.setFill("green")
    player.setWidth(2)
    player.draw(win)

    while True:
        dx, dy = get_offsets()
        if dx != 0 or dy != 0:
            player.undraw()
            dx, dy = dx * speed, dy * speed
            lower_left._move(dx, dy)
            upper_right._move(dx, dy)
            player.p1, player.p2 = lower_left, upper_right
            player.draw(win)
        update(10)

if __name__ == "__main__":
    main()

In addition, you might want to look for a different keyboard event handler, the keyboard module requires administrator rights (at least on UNIX). I know I certainly wouldn't just run a game that needs that. In other words, I would at least read the whole source code to make there is no exploit hidden in it (which was still possible with the code you have so far), but probably stay on the safe side and not play it at all.


Project Euler 12 (triangle numbers), solved using functools.reduce() and looping

Here's an in-depth view from BDFL.

reduce should be faster, especially if you supply it with function that is written in C . Try replacing your multiplication lambda with operator.mul and see if anything changes.

There is a matter of style which of two functions to prefer, because more complex tasks would require more complex lambdas and the whole thing would be less comprehensible than for-loop. Thus, use of reduce was discouraged and it was moved into functools.

On the other hand, for less complicated tasks there are such things as sum, all and any. Latter two also short-circuit, whereas reduce does not.


Sort pandas DataFrame first by subject ID then pick their corresponding values from other columns

What makes your code slow is the repeated calls to unique, and manually shunting all entries into lists repeatedly. Ideally you want to do it all in pandas for the most speed.

If I understand it correctly, you want to group by the subject ID, collect all hadm IDs and texts. In that case, you can just use pandas.DataFrame.groupby and pandas.DataFrame.aggregate to achieve (almost) the same result:

notes_1_df = notes_df.drop(columns=["ROW_ID"]) \
                     .groupby("SUBJECT_ID") \
                     .aggregate(list) \
                     .reset_index()

Which directly produces this output:

   SUBJECT_ID                HADM_ID                                               TEXT
0           4                   [89]                                 [Here is the text]
1          23  [433, 112, 773, 1212]  [Here is the text,and so on, Here is the text,...
2          65           [1212, 1210]    [Here is the text,and, Here is the text,and so]
3         914                 [2212]                       [Here is the text,and so on]

Whereas your code produces:

   SUBJECT_ID                        HADM_ID                       NOTES
0           4                         [89.0]            Here is the text
1          23  [433.0, 112.0, 773.0, 1212.0]  Here is the text,and so on
2          65               [1212.0, 1210.0]  Here is the text,and so on
3         914                       [2212.0]  Here is the text,and so on

This differs mainly in the notes. Here your code is a bit weird. Instead of doing what you did, let's just pick the first text from each subject for now.

I am assuming that having integers for the hadm ID is fine, otherwise you can be more specific and supply two different functions to aggregate, in which case you don't even need the drop anymore:

notes_1_df = notes_df.groupby("SUBJECT_ID") \
                     .aggregate({"HADM_ID": lambda x: list(map(float, x)),
                                 "TEXT": "first"}) \
                     .rename(columns={"TEXT": "NOTES"}) \
                     .reset_index()

   SUBJECT_ID                        HADM_ID                       NOTES
0           4                         [89.0]            Here is the text
1          23  [433.0, 112.0, 773.0, 1212.0]  Here is the text,and so on
2          65               [1212.0, 1210.0]        Here is the text,and
3         914                       [2212.0]  Here is the text,and so on

To see why I think your code produces weird results, let's replace the text with unique texts:

df["TEXT"] = "Text from subject " + df.SUBJECT_ID.astype(str) + ", hadm " + df.HADM_ID.astype(str)

Then my (last) code produces:

   SUBJECT_ID                        HADM_ID                             NOTES
0           4                         [89.0]      Text from subject 4, hadm 89
1          23  [433.0, 112.0, 773.0, 1212.0]    Text from subject 23, hadm 433
2          65               [1212.0, 1210.0]   Text from subject 65, hadm 1212
3         914                       [2212.0]  Text from subject 914, hadm 2212

Where each text is the first text from that actual subject. In contrast, your code produces:

   SUBJECT_ID                        HADM_ID                           NOTES
0           4                         [89.0]    Text from subject 4, hadm 89
1          23  [433.0, 112.0, 773.0, 1212.0]  Text from subject 23, hadm 433
2          65               [1212.0, 1210.0]  Text from subject 23, hadm 112
3         914                       [2212.0]  Text from subject 23, hadm 773

Note how the texts do not correspond to the same subjects anymore!


Going with your existing code, the promise part can be simplified.

var getStuff = function(){
  return !!$localStorage.stuff ? $q.resolve({ data: $localStorage.stuff })
                               : $http.get('data/sample.json').then(function(response){
                                   $localStorage.stuff = response;
                                   return response;
                                 });
};

You appear to check against undefined and a blank string for stuff, both falsy values. We can simplify by coercing them to a boolean using !!. Another improvement is using $q.resolve, which returns an already resolved promise, resolved value optional. In the same way, $http.get also returns a promise. We can simply just return them instead of creating a new promise wrapper.

myappservice.getStuff().then(function(result){
  $scope.test = result.data[950].Id;
  console.log("returned");
});

We can also chain the then to getStuff since getStuff returns a promise. Much easier to follow chained stuff than breaking them apart (might be personal preference, but chaining makes code appear like sentences instead of commands).

As for a pattern, I think this one is fine since this is a one-off request (call and get) and the controller has been shielded from knowing where the data came from.

However, if you decide to go stream this data in, like say from a websocket, or make your service poll for changes, or react to localStorage events, then the suggested Observer Pattern might be your best bet. Make your service collect callbacks and fire them when something interesting happens.


It seems a little peculiar to use a class to solve this problem. It's not like there's any need to maintain state. All you're doing, in the end, is making it more difficult to use - instead of:

auto result = pentagonal_number(n);

you have to write:

auto pentagonal_number = PentagonalNum{n};
auto result = num_Of_Dots();

or:

auto result = PentagonalNum{n}.num_Of_Dots();

You could throw out the whole class and just keep the num_Of_Dots() member function, let it take iteration as a parameter, and you'd be done. It would be much easier to use, too.

As for the code itself:

#include <stdio.h>

This is not valid in C++ anymore (though it used to be). You need <cstdio>, or better yet, use actual C++ I/O.

unsigned long long int PentagonalNum::num_Of_Dots()
{
    int result = 1;
    int num = 5;

    for (int i = 1; i < iteration; ++i)
    {
        result += num;
        num += 5;
    }
    return result;
}

It seems like this function can be both noexcept and constexpr (and, if it's going to be a class member, also const). Note that the function requires iteration to be greater than or equal to 1; if you're not checking that here so the function can be noexcept, then you should check it in the constructor.

The big question I have is why result is only an int if you intend to return a unsigned long long. Seems a bit of a waste of all that integer range.

You use some magic numbers and variables with mysterious names (num?). Your code would be clearer and easier to understand with more explicit variable names, like:

constexpr unsigned long long int PentagonalNum(int iteration)
{
    // might want to assert that iteration >= 1

    constexpr auto NUMBER_OF_SIDES = 5uLL;

    auto result = 1uLL; // start with 1 point
    auto points_to_add_on_next_iteration = NUMBER_OF_SIDES;

    for (auto i = 1; i < iteration; ++i)
    {
        result += points_to_add_on_next_iteration;
        points_to_add_on_next_iteration += NUMBER_OF_SIDES;
    }

    return result;
}

As an aside, I suspect the reason this challenge was marked as "hard" is because you are supposed to try and solve it without iterating. In other words, you are supposed to stop and think about the problem and derive an equation for the number of dots at iteration n, rather than just charging in and doing an iterative solution.


SELECT Surname
FROM Employee
JOIN Department ON Department.Director = Employee.EmployeeId;

Other than not requiring a subquery, this is generally a better thing to do because you can then easily access the matching Department table if you ever need to select a column from it.
Are you sure that this even works? You aren't joining the employee's department to the department ID. This should likely be:

SELECT Surname, Salary, City
FROM Employee
JOIN Department ON Department.DepartmentId = Employee.DepartmentId
               AND Department.City = 'Haarlem';

SELECT ProjectName, Budget, Surname
FROM Employee
JOIN Works ON Works.EmployeeId = Employee.EmployeeId
JOIN Project ON Project.ProjectId = Works.ProjectId
            AND Project.Budget > 100;

This should be functionally equivalent but uses cleaner syntax.


Whitespace. Use it. It makes code much clearer. Here's a list of places where you can add whitespace to make your code clearer.

(frame1,frame2,trackWindow) : \$\rightarrow\$ (frame1, frame2, trackWindow):
trackWindow1=[x0,y0,w,h] \$\rightarrow\$ trackWindow1 = [x0, y0, w, h]
( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 ) \$\rightarrow\$ (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
cv2.imshow("mask",mask) \$\rightarrow\$ cv2.imshow("mask", mask)

There are many other places like this in your code, so I'm going to recommend looking at PEP8, Python's official style guide, on how to correct these.

Finally, in all your if conditions, are just if conditions. If you're not using elif, then all of these conditions will be evaluated if they are true. Are you sure that you want this?


Matching Needle & Haystack values using alternate Ontology values

The whole thing needs restructuring if you are worried about performance.  First, you probably shouldn't be using an array for your haystack.  Considering that you will know with certainty what you are looking for in the haystack, it should not be an array which must be iterated in \$O(n)\$ to determine presence of an item.  An associative array with haystack values as keys or even a stdClass item with haystack values as properties would allow for \$O(1)\$ lookup to determine if a value is present.  That might look something like this (perhaps you have more meaningful full data that true to put at each key):

[
    'John' => true,
    'Alexander' => true,
    'Kim' => true,
    'Michael' => true,
    ...
]

The same can be said for the data structure around the alternative needles.  There is no reason to perform an \$O(n)$\ iteration on the alt needle array to see if an item has a lookup value.  Imagine an associative array like:

[
    'Alex' => [
        'Alexander',
        'Alexi'
    ],
    'Alexi' => [
        'Alex',
        'Alexander'
    ],
    'Alexander' => [
        'Alex',
        'Alexi,
    ],
    ...
]

This could give you \$O(1)\$ access to an array of alternate names.

So you code might be changes to look like:

$results = [];
foreach($needles as $needle) {
   $names = [$needle];
   if(array_key_exists($needle, $altNeedles)) {
       $names = array_merge($searches, $altNeedles[$needle]);
   }
   foreach($names as $name) {
       if(array_key_exists($name, $haystack)) {
           $results[$name] = true;
       }
   }
}

Given:
    m = needles array size
    n = number of alt needles per given name
    p = haystack size

This reduces overall worst case complexity from \$O(m*n^2*p)\$  to \$O(m * n)\$

In best cases (single needles, no alternate names) this solution degenerates to \$O(1)\$ complexity, whereas, yours still always requires at least \$O(p)\$.

Now, if you have the opportunity to really rethink you data structures, this can be improved even further.  For example, are what you really calling "alternate needles" really simply alternates on the haystack?  In other words, can the alternate names simply become a part of the haystack such that you can get \$O(1)\$ look up for each needle?


A few things:

Naming:

It's neither Fibonaci, nor febonani, nor fibonanci it's fibonacci. Please get your names to reflect what you're actually talking about and not some disfigured mutation of it :(

memoized OTOH is a relatively nice name, I'd probably prefer memoizedFibonacciNumbers, but that's a thing of preference

Calculating:

quoting wikipedia:

  By definition, the first two numbers in the Fibonacci sequence are \$1\$ and \$1\$, or \$0\$ and \$1\$, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

You on the other hand say:

  The value of Fibonacci for \$n <= 0\$ is \$0\$, and for \$n <= 2\$ is \$1\$, and each subsequent number is the sum of the previous two.

Wikipedia also mentions "negative Fibonacci numbers". Your definition does not match the actual Fibonacci sequence definition :(

instead your fibonacci method should look like this, if you exactly follow the rules for only positive fibonacci numbers:

private static BigInteger fibonacci(Integer n, HashMap<Integer, BigInteger> memoized) {
    if (n < 0) {
       throw new IllegalArgumentException("We assume the positive Fibonacci sequence only");
    }
    if (memoized.containsKey(n)) {
        return memoized.get(n);
    }
    if (n == 0) {
        memoized.put(n, BigInteger.ZERO);
        return memoized.get(n);
    }
    if (n == 1) {
        memoized.put(n, BigInteger.ONE);
        return memoized.get(n);
    }
    BigInteger fibonacci = fibonacci(n-1, memoized).add(fibonacci(n-2, memoized));
    memoized.put(n, finbonacci);
    return fibonacci;
}

Printing is slow:

I see you benchmarking your code. Please keep in mind, that writing something to the Console is quite slow. Your measured execution time is not matching the calculation time.

You should remove the System.out.println() in your fibonacci method.

Conditionals

Also you maybe have already realized, I removed the else in the fibonacci method.

This is because if your code reaches that area, all other branches have returned early, and the else is quite useless.


In general, labelled code is uncommon, but 'forbidden' is a bit harsh. Break, and Continue have better characteristics than GoTo, and should not be 'painted with the same brush'.

The logic in your code is convoluted though.... you are 'searching' the input set, and ensuring that all members of the input set match a condition. As you search, if the member matches, you remove the member. If one of the members does not match, you immediately return an empty result.

Note, that if a 'middle' member fails to match, you have already removed the first members, and yet you return an empty set.

Your logic could be significantly simplified if you extracted part of your method as a 'helper' function:

private myList searchAndRemove(String dep, Set<myList> candidates) {
    for (Iterator<myList> iterator = candidates.iterator(); iterator.hasNext(); ) {
        myList link = iterator.next();
        if (link.getLegDep().toString().equals(dep)) {
            iterator.remove();
            return link;
        }
    }
    return null;
}

private List<myList> sortLinks(SegmentType s, Set<myList> LinkSet) {

    List<myList> matched = new LinkedList<myList>();

    String dep = s.getDep().toString();
    int index = 0;
    while (!LinkSet.isEmpty()) {
        myList link = searchAndRemove(dep, LinkSet);
        if (link == null) {
            return Collections.emptyList();
        }
        matched.add(link);
        link.setLine(s.getLineCode());
        link.setNb(s.getNb());
        link.setSuff(s.getSuff());
        link.setIndex(index++);

        dep = link.getDest().toString();
    }

    return matched;
}

In addition to the above, note that your class names and variable names are really, really bad....

myList is a class, and should be CapitalCamelCase naming style, and have a different name.
LinkList is a variable name, and should be lowerCamelCase, and have a name like matchedSegments
LinkSet is also a variable name, and should be lowerCamelCase.

In general, with the name-pollution of having a class with 'Link' in the name (probably because it's not a horrible name', but it conflicts with LinkedList, so try to avoid Objects with Link as the name.

Additionally, note that your index variable was not an index in to the source data, but an index of the output segment. Including it as part of the original 'for' loop implied that it was used as an index in to that. The reality is that it is independent. I have edited it to make that clear.


From a once over:

Not sure why you are not parsing the querystring for GET requests? It seems wrong
if(data.length < postMaxSize && postTotalReceived < postMaxSize) could be if(data.length + postTotalReceived < postMaxSize)
Not sure what happens in your code after setting the 413, it seems you have some loose ends there. You could consider redefining callback to function(){}
I would not store the routes as an array, the lookup time is too slow in my mind, instead I would store the routes in an object like this:

api.addRoute = function(route){
  routes[route.method][route.url] = route;
}

I read your code several times, it seems as if even if the method of a route does not match you will still execute the route if the url matches through a regex. If so, then that is completely wrong.


Consider an iterative path compression design for root. The recursive version uses more memory for stack frames. Typical iterative versions follow the path one at a time. The path can be followed two at a time since the end loops back to itself. The root function could be refactored to be something along the lines of:

int root(int a, vector<int> &parent) {
    while (parent[a] != a)
      a = parent[a] = parent[parent[a]];
    return a;
}

Plus, consider adding a second vector to keep track of the sizes of each group. This will allow for more intelligent selecting of representatives during link. Something along the lines of the following:

void link(int i, int j, vector<int> &parent, vector<int> &sizes) {
  i = root(i, parent);
  j = root(j, parent);
  if (i == j) return;
  if (sizes[i] < sizes[j]) {
    parent[i] = parent[j];
    sizes[j] += sizes[i];
  } else {
    parent[j] = parent[i];
    sizes[i] += sizes[j];
  }
}

See this post for more information.

Consider allocating the vector using the constructor, resize, or reserve. Then initial values can be set using iota (ref).  For example,

vector<int> parent(n);
iota(begin(parent), end(parent), 0);

Consider using printf and scanf over cin and cout. Also, if you are going to use cin and cout, consider including ios_base::sync_with_stdio(false); and cin.tie(NULL);. See this question for more information.


def get_cg_resources(pref_label, count=10):
    r = request_that_has_the_xml

    ns = {'ns':"http://www.loc.gov/zing/srw/"}

    tree = ET.ElementTree(ET.fromstring(r.text))

You dont't need ElementTree to extract data from xml, Element is enough.

    root = ET.fromstring(r.text)

If 'str' tag is contained only in 'record' tag you don't have to find 'record'
tag first. You can simply look for 'str' tag. The iter method recursively
iterates over it's children.

There is a dict to represent 'namespace'. So you don't have to explicitly list
it's value, 'key:tag', dict is enough.

    for elem in root.iter('ns:str',ns):

If there are 'str' tags that are contained in other tags that you don't want,
then you have to first find 'record' tags.

    records =[]

    for elem in root.iter('ns:record',ns):

         record = {
        'title':'',
        'source': '',
        'snippet': '',
        'link':'',
        'image':'',
        'adapter':'CG'
        }

record can be initialized as follows,

        record =dict.fromkeys(['title','source','snippet','link','image'],'')
        record['adapter']='CG'

        for value in elem.iter('ns:str',ns):
            attr = value.attrib['name']
            if(attr == 'dc.title'):
                record['title'] = value.text
            elif(attr == 'authority_name'):
                record['source'] = value.text
            elif(attr == 'dc.description'):
                record['snippet'] = value.text
            elif(attr == 'dc.related.link' ):
                record['link'] = value.text
            elif(attr == 'cached_thumbnail'):
                img_part = value.text
                record['image'] = "http://urlbase%s" % img_part
        records.append(record)

    return  records

The above code means you want to extract value of the 'name' attribute of 'str'
tags which are contained in 'record' tags.

If you want a generator you can simply
replace records.append(record) wiht yield record and delete return records
and records = [] which will be efficient if the list is huge.


Separation of Concerns

The function should have only one concern--finding the indices. Printing out results is a separate concern that shouldn't be combined with finding the indices. Combining the two makes it difficult or impossible to use in a wide variety of situations.

Vacuous Declaration

Having the declaration followed immediately by the definition renders the declaration just extra visual noise.

Pointless Work

In your function, you initialize and increment j, but you never seem to make any use of it.

Inconsistent Types

The type normally used for indices into arrays is size_t, but you're returning a vector of int instead.

Intermixing Arrays and Vectors

Although it's not exactly an error, it is a bit strange to have an array as the input type, and a vector as the result type. Typically you'd want to pick one or the other, and use it consistently. The other obvious possibility would be to have the function itself work with iterators, so it doesn't have to specify the type of the collection itself at all (and can be written generically, so it can work with essentially any collection).

const Correctness

Since this function shouldn't modify the input array, it's better to pass that as a pointer to const (note: although your parameter definition uses array notation, what's passed is actually a pointer). If you use a vector as input, you'd probably want to pass it as a reference to const.


Since all you've been asked is to display output, a single simple nesting of two for loops without arrays should work just fine. Note that in all cases, you know in advance prior to performing a loop how many times the loop will iterate, and in this situation a for loop is cleaner than a while loop (though of course both would work):

// note that method namess should begin with a lower-case letter
public static void numberPattern(int rows) {
  for (int row = 0; row < rows; row++) {
     for (int col = 0; col < rows + 1; col++) {
        int number = 0;
        if (row % 2 == 0) {
           number = col < rows ? row + 1 : row + 2;
        } else {
           number = col == 0 ? row + 2 : row + 1;
        }
        System.out.print(number);
     }
     System.out.println();
  }
}

If you need to store the numbers to be used elsewhere, then yes, put them into an array.


More elegant way to show | hide in jQuery

You can shorten it down:

$('#shw_test').click(function() {
    $('#hde_test, #shw_test').toggle();
    $('.class1').show();
});
$('#hde_test').click(function() {
    $('#hde_test, #shw_test').toggle();
    $('.class1').hide();
});

Likely, you can shorten it to:

$('#shw_test, #hde_test').click(function() {
    $('#hde_test, #shw_test, .class1').toggle();
});

Just depends how the initial state of things are.


Java builder for user contact information, with optionals

My understanding from a builder is a bit different. In my opinition, the User should not have a dependency to the Builder (you have a bidirectional dependency which is usually bad anyway). With that said, use the User as member variable within your builder:

public class UserBuilder {
  private User user = new User();

  public UserBuilder withUsername(String username) {
    user.setUsername(username);
  }

  public User build() {
    return user;
  }
}

I also prefer a verb in my method names (they should have, actally, but in that case I think it's okayish), that's why I use 'with' as prefix; And I explicitly do not use not 'set' as prefix, to distinguish it from the setter of the User type.

If you do it like that, the 'actual building' of the user is within the builder and not in the User - and the User type is kept quite stupid.

It might seem a bit strange, that the 'build' method doesn't actually build, but non-persistent built types are often only used for unit testing. The sweet part about builders, you can expand them to persist your built types or other fancy requirements.


Creating a complex hierarchy for "Player Effects"

I'd like to suggest a completely different implementation strategy for the, er, effects of the effects. You have a thing with mutable state (Player) and operations that change that state (self.move_state = ...) based on timers. You've had to add a special system to make the timers coordinate with each other, and if you ever make a mistake in the ”off” methods you will have a broken effect that sticks around.

Instead, make the state of the player a function of the effects. Here's a simple implementation to illustrate (note: may be Python 2-ish because I'm not familiar with 3; also untested):

def apply_effects(effects, attribute, base_value):
    value = base_value
    for effect in effects:
        value = effect.modify(attribute, value)
    return value

class Player(game.core.Player):
    def get_frozen(self):
        return apply_effects(self._effects, 'frozen', False)

    def get_move_state(self):
        return apply_effects(self._effects, 'move_state', MoveStates.NORMAL)

class Effect(object):
    """Base class for effects."""
    def modify(self, attribute, value):
        return value

class FrozenEffect(Effect):
    def modify(self, attribute, value):
        if attribute == 'frozen':
            return True
        else:
            super(FrozenEffect, self).modify(attribute, value)

class HoverEffect(Effect):
    def modify(self, attribute, value):
        if attribute == 'move_state' && value != MoveStates.FLY:
            return MoveStates.HOVER
        else:
            super(HoverEffect, self).modify(attribute, value)

class FlyEffect(Effect):
    def modify(self, attribute, value):
        if attribute == 'move_state':
            return MoveStates.FLY
        else:
            super(FlyEffect, self).modify(attribute, value)

(Note: If all effects are this simple, then they could be just functions instead of classes. Making them classes allows adding more operations, for example ”get name and icon” to show the player what effects apply.)

Then you would still manage the lifetime of the effects much like you are now, but the effects do not need to know each others' names. The only special rule here is that the FLY move state takes priority over the HOVER move state, which is presumably a basic rule about that enumerated type. (An alternative implementation would be to define a sort order for effects, sorting the list of effects so that the fly effect is always applied after the hover effect, or divide effects into groups that are applied in a specific order.)

This architecture also allows you to easily implement additive or multiplicative effects that stack with each other (e.g. speed/damage boosts).

If you need to actually have something happen when an effect ends, then save the computed values of the attributes, and when an effect ends compute the new attributes and do the relevant thing if they're different. This means that the happening is completely dependent on the state of the player and not what effects just happened. (For example, suppose two hover effects wear off at exactly the same moment: you don't want to start a ”drowned because fell in water” event twice, only once. This strategy can't make that mistake.)


Advent of Code 2017 Day 2 (1) in Functional programming (FP)

Note: The code examples below split lines on 1+ whitespace character instead of tabs - perhaps the way it was pasted in your question converted tabs to spaces...
Removing the array of diffs
Because the overall equation for this problem would be a summation of differences, the two calls to .reduce() can be combined into one- instead of having one function to essentially push a difference into an array and then a separate function to sum those differences, just add the difference to the cumulative total. In addition to reducing the number of function calls by the number of lines, the elimination of the array of differences should drastically reduce memory consumption.
const CumulativeDiffs = (totalSoFar, val) => {
    const row = val.split(/\s+/);
    const max = Math.max(...row);
    const min = Math.min(...row);
    return totalSoFar + max - min; //add diff to cumulative total
};

const solution = INPUT.split(/\n/)
    .reduce(CumulativeDiffs, 0);

const INPUT =
  `6046   6349    208 276 4643    1085    1539    4986    7006    5374    252 4751    226 6757    7495    2923
1432    1538    1761    1658    104 826 806 109 939 886 1497    280 1412    127 1651    156
244 1048    133 232 226 1072    883 1045    1130    252 1038    1022    471 70  1222    957
87  172 93  73  67  192 249 239 155 23  189 106 55  174 181 116
5871    204 6466    6437    5716    232 1513    7079    6140    268 350 6264    6420    3904    272 5565
1093    838 90  1447    1224    744 1551    59  328 1575    1544    1360    71  1583    75  370
213 166 7601    6261    247 210 4809    6201    6690    6816    7776    2522    5618    580 2236    3598
92  168 96  132 196 157 116 94  253 128 60  167 192 156 76  148
187 111 141 143 45  132 140 402 134 227 342 276 449 148 170 348
1894    1298    1531    1354    1801    974 85  93  1712    130 1705    110 314 107 449 350
1662    1529    784 1704    1187    83  422 146 147 1869    1941    110 525 1293    158 1752
162 1135    3278    1149    3546    3686    182 149 119 1755    3656    2126    244 3347    157 865
2049    6396    4111    6702    251 669 1491    245 210 4314    6265    694 5131    228 6195    6090
458 448 324 235 69  79  94  78  515 68  380 64  440 508 503 452
198 216 5700    4212    2370    143 5140    190 4934    539 5054    3707    6121    5211    549 2790
3021    3407    218 1043    449 214 1594    3244    3097    286 114 223 1214    3102    257 3345`;

const CumulativeDiffs = (totalSoFar, val) => {
  const row = val.split(/\s+/);
  const max = Math.max(...row);
  const min = Math.min(...row);
  return totalSoFar + max - min;
};

const solution = INPUT.split(/\n/)
  .reduce(CumulativeDiffs, 0);
console.log("solution ", solution);

Sorting
I did consider sorting the array of values in each row using Array.sort(), which works, but the values all need to be converted to integers first (e.g. using parseInt(), or just a function that returns the number added to 0), which slows things down a little. But with that change there is no need to call Math.max() and then Math.min() - simply sort the numbers, then add the last element to the cumulative total and subtract the first element.
const CumulativeDiffs = (totalSoFar, val) => {
  //let row = val.split(/\s+/).map((num) => +num); //still slower than finding min and max
  let row = val.split(/\s+/).map((num) => parseInt(num, 10));
  row.sort((a, b) => a - b); //sort numbers in each row
  return totalSoFar + row[(row.length - 1)] - row[0]; // add difference
};

const INPUT =
  `6046   6349    208 276 4643    1085    1539    4986    7006    5374    252 4751    226 6757    7495    2923
1432    1538    1761    1658    104 826 806 109 939 886 1497    280 1412    127 1651    156
244 1048    133 232 226 1072    883 1045    1130    252 1038    1022    471 70  1222    957
87  172 93  73  67  192 249 239 155 23  189 106 55  174 181 116
5871    204 6466    6437    5716    232 1513    7079    6140    268 350 6264    6420    3904    272 5565
1093    838 90  1447    1224    744 1551    59  328 1575    1544    1360    71  1583    75  370
213 166 7601    6261    247 210 4809    6201    6690    6816    7776    2522    5618    580 2236    3598
92  168 96  132 196 157 116 94  253 128 60  167 192 156 76  148
187 111 141 143 45  132 140 402 134 227 342 276 449 148 170 348
1894    1298    1531    1354    1801    974 85  93  1712    130 1705    110 314 107 449 350
1662    1529    784 1704    1187    83  422 146 147 1869    1941    110 525 1293    158 1752
162 1135    3278    1149    3546    3686    182 149 119 1755    3656    2126    244 3347    157 865
2049    6396    4111    6702    251 669 1491    245 210 4314    6265    694 5131    228 6195    6090
458 448 324 235 69  79  94  78  515 68  380 64  440 508 503 452
198 216 5700    4212    2370    143 5140    190 4934    539 5054    3707    6121    5211    549 2790
3021    3407    218 1043    449 214 1594    3244    3097    286 114 223 1214    3102    257 3345`;

const CumulativeDiffs = (totalSoFar, val) => {
  //let row = val.split(/\s+/).map((num) => +num); //still slower than finding min and max
  let row = val.split(/\s+/).map((num) => parseInt(num, 10));
  row.sort((a, b) => a - b);
  return totalSoFar + row[(row.length - 1)] - row[0];
};

const solution = INPUT.split(/\n/)
  .reduce(CumulativeDiffs, 0);

console.log("solution ", solution);

Compare these approaches with yours in this jsPerf.
Naming Things
Like @Igor mentioned in this answer to one of your previous posts the variable names could changed to better describe the values, and functions could better describe what they do. For example - summer might be a better name than sum, since it provides a sum of values.


Getting B+ matrix (Warshall algorithm) in Matlab

This post may help you in removing a loop:
http://mathforum.org/kb/message.jspa?messageID=845980

Furthermore, one way to speed up your code is to use a short circuit logical operator:

B(i,k) || B(k,j);

Also it seems to have a small effect if you use a logical matrix as input rather than a double:

B = logical(b);

Last and least, it would be nicer to initialize Bm with the datatype that it will have:

Bm = false(n)


I would consider inverting the first if to make it simpler and quicker to be aware of the else.

I strongly suggest always leaving something inside a catch - if you have nothing else to put there at least leave a comment.

I would change

if (Bankkonto1.Rows.Count > 0)

to, using System.Linq; :

if (Bankkonto1.Rows.Any())

I would save reused values in scoped variables:

string objValue = obj.ToString();
...
int selectedRow = Bankkonto1.SelectedRow.Index;

I would consider refactoring the foreach

        foreach (UltraGridRow myRow in Bankkonto1.Rows)
        {
            if (myRow.Cells[STR_Id].Text != obj.ToString())
                continue;

into a Linq select:

        var row = Bankkonto1.Rows.FirstOrdefault( r => r.Cells[STR_Id].Text == objValue);
        if(row != null) {


Tic Tac Toe / Noughts and Crosses - First Program

Seems pretty nicely done. Most of the following are minor improvements, but if in case you do not get any of the following parts, do let me know. COnsidering the beginner tag, I have written a small appendix at the end. Suggestions for improvements:

The Format method: Instead of using the print() as you have written, it is better to use a format() method in general. For your purposes, it might be overkill, but in case you are incorporating some of the points below (especially 5), it might come in handy for a pretty output.
Alternative for if-elif-else: The entire block from try to the final else can be replaced by regexsearch (or any equivalent string search) to look for correct responses and club the not a number and incorrect number error messages into one. One suggestion for that is below.

Suggestion code:

# initialize with grid = ["0","1","2","3","4","5","6","7","8"]
if (p1_input not in grid) or (p1_input in ['x','o']):
    print('Combined Error Message')
else:
    grid[int(p1_input)]='x'
    draw_grid()

Checking for victory: Instead of listing down all possible victory positions, the bulky code can be avoided. Although I am currently unable to come up with anything simpler than the following code which uses numpy, you can at least contract the current code in a single function that can be called for both p1 and p2, reducing the bulk of that code by half. The benefit of using the numpy variant is, it is size-independent. You can update a for a 4x4 game and it should be directly usable.

Numpy Variant:

def p1_check():
    # a defines a list of all winning positions
    a = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
    # <= is the subset operator for sets. Additionally, the where statement finds the indices for all 'x'
    l = list(numpy.where(numpy.array(grid) == 'x')[0])
    if True in list(map(lambda x: (set(x) <= set(l)),a)):
        print('Victory')
        return "End Game"

Contraction of your code:

def check(player):
   a = ['x','o'][player-1]
   if grid[0] == a and grid[1] == a and grid[2] == a or \
         grid[3] == a and grid[4] == a and grid[5] == a or \
         grid[6] == a and grid[7] == a and grid[8] == a or \
         grid[0] == a and grid[3] == a and grid[6] == a or \
         grid[1] == a and grid[4] == a and grid[7] == a or \
         grid[2] == a and grid[5] == a and grid[8] == a or \
         grid[6] == a and grid[4] == a and grid[2] == a or \
         grid[0] == a and grid[4] == a and grid[8] == a:
            print([p1_name,p2_name][player-1] + " Wins!")
            return "End Game"
#call check(1) and check(2) appropriately

Earlier Ties: In order to account for configurations where a tie is definite, without all the boxes having been filled, you can work out if there is any winning chance considering only all the 'x' and the empty boxes (same for 'o'). To do this, one way is to use the numpy variant above with a slight modification. This matters very little in a 3x3 game but ismore relevant for larger games.

Suggestion code:

# a defines a list of all winning positions
def tie_check():
    a = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
    # using != instead of ==, 'or' combining the lists
    canwin = (True in list(map(lambda x: set(x) <= set(list(numpy.where(numpy.array(grid) != 'x')[0])),a))) or \
          (True in list(map( lambda x: set(x) <= set(list(numpy.where(numpy.array(grid) != 'o')[0])),a)))
    if not canwin:
        print("Game is a tie")
        return "End Game"

Multiple Games and statistics: To just improve the usability of the code, you can allow for specifying at the end whether to play another game or not. Provision for a best of 3/best of 5 can easily be incorporated in the play() function with an additional option of storing and printing the statistics for the game.

APPENDIX

Numpy is basically used for its arrays and array-methods which are very fast and convenient. For our purposes, only two of these are relevant. numpy.where just returns an array of indices corresponding to True. Whenever a numpy array is equated (==) to any value, an array of booleans is returned corresponding to element-wise matching. I urge you to try out with self-made arrays and it is very easy to get hang of, for 1-D case, which is the one used above.

Map is just a way to apply a function element-wise to a list and return a list of values returned for every such application. I assume you are familiar with lambda(a way to make functions on the fly) and set which are very similar to the mathematical entity.


Comparing each property to the same value

The question is: Why do you want to change it?

I bet you can get a shorter form with some use of xor, and, or etc. functions but I believe it's not worth it. For example:

public bool IsAllDayZero
{
    get
    {
        return
            (Today | Days1_2 | Days3_6| Days7_10 | Days11_15 |
             Days16_30 |  Days31_45 | Days46_60 | Days60Plus) == 0;
        }
}

It's indeed shorter but no way that it's more clear for some other person about what this code tries to achieve.

Or you can get a faster version that will revert the conditions and then execute only few conditions without a need to check them all but again I doubt that clarity of the code will worth such a changes.

However your current implementation is clear, complete and does exactly what it has to do without some extra noise and I just recommend not to change it.


Loop through array while creating one div.row and appending three div.col-lg-4

Currently your code accesses live DOM unnecessarily, which is slow. For example, it creates a row, then searches it by id in the document instead of returning directly. It's better to construct elements without attaching them to actual document, and attach when everything's done.

However, since you're using innerHTML there's no need to create DOM elements manually, just construct an overall HTML string and insert it in the document. The entire code boils down to:

createDiv: function() {
  document.getElementById("displayQuoteHere").insertAdjacentHTML('beforeend',
    this.finalDellEqArray().map(function(item, index) {
      var before = index % 3 > 0 ? '' : '
';
      var after = index % 3 < 2 ? '' : '
';
      return before + '
' + item + '
' + after;
    }).join('')
  );
},


Converting bytes to an escaped hexadecimal string

Use of assert

Some of the uses of assert here look semi-broken, at least to me. Part of the definition of assert is that when you compile with NDEBUG defined, assert becomes a nop. When it is enabled, a failed assertion immediately aborts the program. For testing inputs to a function, neither of those is generally desirable. For such purposes, I usually define an assure that always does its thing, and throws an exception when the test fails.

snprintf

At the very least, I'd try to wrap the ugliness of using snprintf up into a reasonably neat little function like to_hex that just converts a number into its hex representation:

std::string to_hex(int in) {
    // snprintf ugliness here
    return std::string(buffer);
}

Alternatively, since you're converting inputs to strings, and accumulating those together into a buffer anyway, consider using an std::ostringstream.

Logic

In a few places, the logic seems...less than pleasing, at least to me. For example:

if (column >= maxCols)

You've previously tested that maxCols % 4 == 0, and (assuming things work correctly) each item you add should be 4 more characters, so you should never see a result that's actually greater than maxCols--only less than maxCols, then equal to maxCols, then back to 0. This is harmless, and if you might want to support a maxCols that was not a multiple of 4, then it might even make good sense--but as things stand right now, it seems like there's a degree of...uncertainty about the real intent.

Reorganization

Right now you have code to ensure the maximum line length sprinkled liberally throughout the rest of the code. I'd be tempted to define a type that takes that as its single responsibility: when you create it, specify a maximum length. When you add characters to it, it tracks the length of the current "line", and when the maximum is reached (or exceeded) it adds a delimiter, and starts over. With this, the rest of the code gets a lot simpler in a hurry, and each piece of code has a much simpler, clearer purpose.


Some quick remarks:

Keep your controllers lean and mean:

Move all of the processing (that you seem to have removed by using the comment // db stuff) to dedicated classes,
bind it all together using MediatR,
validate incoming data with FluentValidation.

There are plenty of examples that show you how to combine these two, e.g. this Stack Overflow question. Jimmy Bogard also has plenty of examples on his own blog, e.g. this post.

Microsoft also promotes this kind of structure:"Implement the Command and Command Handler patterns". (In this case in the context of CQRS, which is something that you also could look into.)
Don't needlessly abbreviate (why "pass" instead of "password"?).
Don't use exceptions to control your logic. An invalid password should IMHO not throw an exception, it's an expected result. Even worse it that you seem to be "eating" your exceptions and don't even log them.
WRT your app's logic, you might want to look at the logic in similar applications, e.g. "Simple API for Authentication, Registration and User Management". Also think about things like "how many times can a user try to log in and fail before his account gets locked?" in order to avoid hackers who'll try to access the system by going through large lists of often-used passwords.


Creating custom random access iterator in C++ 2011

Sure but:

Sure:

   my_iterator ();
   bool operator != (my_iterator);
   pointer            operator -> ();
   my_iterator&       operator ++ ();
   my_iterator&       operator -- ();
   my_iterator&       operator += (difference_type);
   my_iterator        operator +  (difference_type);
   my_iterator        operator -  (difference_type);
   reference          operator [] (difference_type);
   bool               operator < (my_iterator);
   bool               operator > (my_iterator);
   bool               operator <= (my_iterator);
   bool               operator >= (my_iterator);

But most of the above can be defined in terms of each other and are basically forwarding functions to one definition.

The default versions of these look like they should work. So why are you defining them:

   my_iterator (const my_iterator &);
   my_iterator (my_iterator &&);
   my_iterator &operator = (const my_iterator &);
   my_iterator &operator = (my_iterator &&);

Do you really need a destructor?

   ~my_iterator ();

Three different version of operator* that only differ by return type!
That does not look valid.

   reference    operator * ();
   value_type   operator * ();
   my_iterator& operator * ();

Lots of operator++(int) that only differ by return type.
So again does not look valid

   void               operator ++ (int);
   reference          operator ++ (int);
   value_type         operator ++ (int);
   const my_iterator& operator ++ (int);
   reference          operator ++ (int);

Lots of operator--(int) that only differ by return type.
So again does not look valid

   const my_iterator operator -- (int);
   reference         operator -- (int);

Look here for a definition of what you need to support.


If you find yourself, doing something over and over again, loops are often the answer.

Your code rewritten with a loop:

import re

import requests
from bs4 import BeautifulSoup

urls = {
    "Charms": "https://us.pandora.net/en/charms/?sz=30&start={}&format=page-element",
    "Bracelets": "https://us.pandora.net/en/bracelets/?sz=30&start={}&format=page-element",
    "Rings": "https://us.pandora.net/en/rings/?sz=30&start={}&format=page-element",
    "Necklaces": "https://us.pandora.net/en/necklaces/?sz=30&start={}&format=page-element",
    "Earrings": "https://us.pandora.net/en/earrings/?sz=30&start={}&format=page-element"
}

for category, url in urls.items():
    soup = BeautifulSoup(requests.get(url.format(0)).text, 'lxml')
    total_items = ''.join(re.findall(r'\d', soup.select_one('span.products-count').text))
    print("Total {}: {}".format(category, total_items))

So what has changed? The URLs went into a dictionary where the category's name is the key. A simple list would also work here in your case. Now we can iterate over that dictionary. With for category, url in urls.items(): you get the key, i.e. the name of the category and the URL at the same time.

The loop body now does what you had written out by hand, namely getting the page, parse the content with BeautifulSoup and than again with a regex.

Since the URL came bundled with the category, we can no print all the results nicely without writing the same code over and over again.

You can also go a step further and make this into a function:

import re

import requests
from bs4 import BeautifulSoup

def get_total_items(url):
    """Parse the product count from the given pandora URL"""
    soup = BeautifulSoup(requests.get(url).text, 'lxml')
    return ''.join(re.findall(r'\d', soup.select_one('span.products-count').text))

if __name__ == "__main__":
    urls = {
        "Charms": "https://us.pandora.net/en/charms/?sz=30&start={}&format=page-element",
        "Bracelets": "https://us.pandora.net/en/bracelets/?sz=30&start={}&format=page-element",
        "Rings": "https://us.pandora.net/en/rings/?sz=30&start={}&format=page-element",
        "Necklaces": "https://us.pandora.net/en/necklaces/?sz=30&start={}&format=page-element",
        "Earrings": "https://us.pandora.net/en/earrings/?sz=30&start={}&format=page-element"
    }

    for category, url in urls.items():
        print("Total {}: {}".format(category, get_total_items(url.format(0))))

Now the intermediate variable soup is inside the function and does not clutter the global namespace. You could also now easily change the implementation of get_total_items(...) without the need to adapt the "application" code.

I also added the infamous if __name__ == "__main__":, which is basically Python's way to tell someone looking at the script: "This piece of code is supposed to be run if you use this as a script." Have a look at the official documentation or this Stack Overflow post if you want to learn more.

A more subtle change: I reorderd the imports to follow the recommendation of the official Style Guide for Python Code (often just PEP8), which is to have imports from the standard libraries first, then a blank line, and then all the third party libraries.

In general PEP8 is often worth a read, especially if you are not yet familiar with Python.


Is this timer efficient?

Yes, but there are two optimizations that I can see.  Get rid of the goto
and use a do-while loop.  I have noticed a slight performance
increase when it has been written this way in other programs.

This increase will become non-existent however if you have compiler
optimization settings enabled.  If they are enabled, they compile
into the exact same assembly code.  However, I also find a loop
more readable than a goto, so that is another reason to switch
over.
There other optimization I could see is by cleaning up your if-else a tiny bit (untested).  This should speed up your code a tiny bit (again, if optimizations on your compiler are enabled, your results will vary).

if(now < timer->tfinal)
{
    required_sleep = ms_to_timespec(timer->tfinal - now);

    // loop implementation
}
timer->tfinal += timer->step;

You may wonder why this will speed up your code.  The more branches you have, the more susceptible you are to a branch prediction failure and those failures can be expensive when it comes to efficiency.

A few other notes:

Use a designated initializer to initialize a structure (C99).

struct timespec temp =
{
    .step = ms / 1000,
    .tfinal = (ms % 1000) * 1000000
};

Group your #includes and #defines together in a more organized fashion.

#include <time.h>  // group library headers
#include <errno.h>
#include <stdio.h>
#include "timer.h" // group user defined headers

#define _POSIX_C_SOURCE 199309L  // group defines

Your != 0 comparision check in your if conditional could be removed since it is redundant (the if will always execute if the conditional isn't equal to 0).  However, this may increase readability to you, so it would be okay to keep it.


Where is your namespace?  If your are working in code bases that use namespaces, like Magento, you really should be namespacing your code as well.
The interface presented seems confusing to me.  Is it your expectation that the caller controls pagination through the result set?  If so, then how does the caller actually work with intermediate result sets, given that there is no interface to return the data set to the caller and your data in $this->data are overwritten with every iteration of load()?  How is caller supposed to assemble the results?  Also I would expect method names like getResultSet() to, you know, actually return a result set to the caller, not a string format used for pagination.  Why would this method need a public interface anyway?
I think you need make the determination as to whether this class should abstract away pagination activity from caller or not.  If you want the caller to have full control of pagination (and potentially assembling result sets based on pagination results), then I would think your class would need an interface that a) is more explicit around result set size and page numbers to be used b) actually return result set data to the caller.  This class likely does not need to maintain state the way you do now if you want caller to own pagination control.
You have a data mapping step in your load() function, where you change key for data set from data to items. I would suggest that this mapping function should exist in a separate method. In the class, so you can keep you mapping logic separate from your loading logic.


Acquiring an increasing sequence of numbers

I would suggest focusing on the nature of the answer. The requirement is to return the highest possible values, which also means the shortest sequence.

So I would suggest you start at n-1 and work your way down, checking increasingly long sequences until one sums to greater than n**2, in which case you can restart at n-2, etc.


Let's start with the procedure's signature:

Public Sub removeBlankEntriesFromRow(inputRow As Range, pasteLocation As String)

I like that you're explicitly making it Public - VBA procedures are Public by default, but in most other languages members are private if an access modifier isn't specified, which can make reading VBA code a bit confusing if you don't know this and you're switching languages (VB.NET, C#, etc.). Even if the only language you code in is VBA, being explicit about access modifiers is a very good practice, keep it! :)

I also like that your procedure has a meaningful name that's starting with a verb - procedures do something, and they should be doing something very specific. Giving a specific name to your procedures makes it easier to see what's doing what. By convention, removeBlankEntriesFromRow should be RemoveBlankEntriesFromRow though, as PascalCase is the recommended casing style for pretty much everything except local variables and parameters.

Parameters can be passed by value (i.e. method receives its own copy) or by reference (i.e. reassigning a parameter will affect the caller's copy too) - in other languages parameters are often passed by value by default, but VBA passes them ByRef unless you explicitly specify they're ByVal.

Hence, if you don't intend to reassign a parameter and have the calling code "see" that new value, you should always pass parameters by value, like this:

ByVal inputRow As Range, ByVal pasteLocation As String

Dim oldArray, newArray, tempArray

For better readability and maintainability, it's best to declare the 3 variables on 3 separate instructions:

Dim oldArray
Dim newArray
Dim tempArray

Now, these 3 variables are all implicitly Variant. If you intend them to be Variant, it's best to say so - and since a Variant can be just about anything in VBA, it will happily hold an array of variants - better declare them as their exact type - Variant():

Dim oldArray As Variant()
Dim newArray As Variant()
Dim tempArray As Variant()

And now we know what we're up against! :)

Dim j As Integer
Dim i As Integer

Typical loop counters, everybody calls 'em that. But it's probably better to name them after their usage, too - and Integer will probably fit most usages, but the day you need to run this on a range that has more than 32,767 cells it will overflow the 16-bit Integer type; I'd use a 32-bit Long here, just to be safe:

Dim oldIndex As Long
Dim newIndex As Long

If oldArray(i) <> "" Then

This is a minor point, but I have to mention it: the hard-coded "" string literal may look like it's just an empty string, but it's actually allocated a memory space of its own. Nothing to worry about, but it's usually better to use the built-in constant vbNullString instead.

Try this in the immediate pane (Ctrl+G):

?StrPtr(""), StrPtr(vbNullString)

You should see a bunch of numbers (a memory address) for the StrPtr("") call, and a 0 for the StrPtr(vbNullString) call: vbNullString is completely zero-footprint, give it the love it deserves!

'Catch Error

This comment is misleading: you're not handling any runtime errors that may occur here. To handle errors, your procedure body should be templated something like this:

Public Sub DoSomething()
    On Error GoTo CleanFail

    'method body goes here

CleanExit:
    'cleanup code goes here
    Exit Sub

CleanFail:
    'error-handling code goes here
    Resume CleanExit
End Sub

That said, I would remove all but the first comment. Comments shouldn't say what the code is doing - that's the code's job (and that's why code readability matters). Good comments say why the code is doing something.

Wherever you have a comment that says "this chunk of code does X", then you might have an opportunity to name that chunk of code, by extracting it into its own function. That can be done manually of course, but the Rubberduck VBE add-in I've written with @RubberDuck makes it easier than ever: just select a block of code, and then refactor / extract method and you're done!


CharacterEscaper - further optimizable? Bugs?

First I have to be honest and say that this code puts me into WTF-Mode very early on, but that must not be a bad thing. But what took me by surprise is the lack of comments, there are some edge-cases in there I can not make out why they're the way they're.

On the latter, changing, suggestions I did only perform minor profiling by simply running it in a loop with 1 million iterations and seeing if the time differs by much.

Rule of thumb: Never roll your own security!

Your indentation/brace-style is a mess. Java normally uses a modified K&R-Style, with the opening brace on the same line.

function test() {
    if (condition) {
        // Stuff
    } else {
        // Stuff
    }
}

You should fix that first.

Some of your names can be improved. F.e. queryCharArray might be better named escapedQuery.

You might want to extract all hard coded chars at least into static final variables for readability.

Your loop-beginning can be changed to:

char[] queryCharArray = new char[query.length() * 2];
int currentIndex = 0;
    for (int i = 0; i < query.length(); i++) {
        char c = query.charAt(i);

This improves readability by a lot.

Your loop can be optimized to this:

char c = query.charAt(i);
if (mustBeEscaped[c]) {
    queryCharArray[currentIndex++] = '\\';
    if ('&' == c || '|' == c) {
        if (i + 1 < query.length() && query.charAt(i + 1) == c) {
            queryCharArray[currentIndex++] = c;
            i++;
        }
    }
}
queryCharArray[currentIndex++] = c;

This removes unnecessary else-blocks.

if ('&' == c || '|' == c) {
    if (i + 1 < query.length() && query.charAt(i + 1) == c) {

You should leave a comment here explaining why these characters are special. Extracting them into another array might be a good idea.

if (skipNextOccurence[c]) {

Putting all this together (and renaming the constants to fit the Java naming conventions), I ended up with this in my tests:

private static final boolean[] MUST_BE_ESCAPED = new boolean[65536];
private static final boolean[] SKIP_NEXT_OCCURENCE = new boolean[65536];
private static final char ESCAPE_CHARACTER = '\\';

static {
    for (char c : "\\?+-!(){}[]^\"~*&|".toCharArray()) {
        MUST_BE_ESCAPED[c] = true;
    }
    for (char c : "&|".toCharArray()) {
        SKIP_NEXT_OCCURENCE[c] = true;
    }
}

private static String escape(String query) {
    char[] escapedQuery = new char[query.length() * 2];
    int currentIndex = 0;

    for (int idx = 0; idx < query.length(); idx++) {
        char c = query.charAt(idx);

        if (MUST_BE_ESCAPED[c]) {
            escapedQuery[currentIndex++] = ESCAPE_CHARACTER;

            if (SKIP_NEXT_OCCURENCE[c]) {
                // Check if the next char is the same, and if yes add it to
                // the escapedQuery and make sure that it is skipped.
                if (idx + 1 < query.length() && query.charAt(idx + 1) == c) {
                    escapedQuery[currentIndex++] = c;
                    idx++;
                }
            }
        }

        escapedQuery[currentIndex++] = c;
    }

    return new String(escapedQuery, 0, currentIndex);
}

To elaborate on the possibilities to use a StringBuilder, or a Set, or pretty much everything else I tried to come up with which looked more readable...damn that thing is fast! Even using a StringBuilder slowed it down considerably. So as long as you're aware that you are, a little bit at least, abusing memory with that 65k array (which will end up as 65k * 8Byte on most platforms) it's fine with me.

Also don't forget that you allocate twice the amount of whatever is passed into this function. So if somebody feels funny and passes a 1Mb query into that, it will at least consume 3Mb (1+1*2) on it's way. That is, if the JVM is not smarter then I think and does not allocate all that at once.

Just use more comments and JavaDoc.


Avoiding code duplication and retaining const correctness

First you have it the wrong way around.

You should not use the mutating version to supply data to the non-mutating function:

const int& MyClass::operator[](int index)const {
    return const_cast<int&>(const_cast<MyClass&>(*this)[index]);
}

What happens if operator[] is modified and does mutate slightly the internal state? By casting away the constness you have opened up your class to undefined behavior. You should NEVER cast away constness. If you must you can use const_cast to add constness, but removing it is so dangerous that this should be looked at as breaking code.

If you had written it the other way around:

int& MyClass::operator[](int index) {
    return const_cast<int&>(const_cast<MyClass const&>(*this)[index]);
}

This is better. Because if you change the operator[] so that it actually mutates the class it will generate a compiler error and thus prevent you from accidentally getting undefined behavior.

But personally I prefer to add another helper method and thus remove all athe casting:

private:
// NOTE: This is not a perfect solution for all situations.
//       But it works for 99% of situations and keeps the code clean
//       For the remaining situations switch back to use const cast
//       **BUT** always add never remove constness from an object.
// Never make public as it is const and gives away an internal reference.
// Only use via the public API
int& get(int index) const
{
    return stuff[index];
}

public:
// Keep the API simple/clean and DRY
// move all the work to private methods.
int&       operator[](int index)       { return get(index);}
int const& operator[](int index) const { return get(index);}

Answer to comment below:

I would not use it for const/non-const iterators

const_iterator begin() const {return const_iterator(<X>);}
iterator       begin()       {return iterator(<X>);}


Sorting an array of strings in C using insertion sort

Never read strings with scanf like this:

scanf(" %s", s[i]);

This allows the user of the program to enter arbitrarily long text which can overwrite all of the programs memory.
There are several options of how to do this safely, one would be to use fgets which allows to specify the maximum length the input buffer can store.
Make sure the input is terminated with '\0' if you do this.
Same goes for the number of strings to read: You never check the counter against LEN.
In sort elem is used as temporary storage, so a better name would be temp.
Last but not least: You perform an awful lot of copying. This is totally unnecessary - you should really read up about pointers in C (they are somewhat similar to references in Java). Allocate the input strings dynamically and then just swap pointers instead of copying all those strings around.
You won't be able to avoid learning about memory management and pointers in C so might as well dig into it.


I would like to know if there is a way to improve the code.

// Part to improve from HERE
r >>= 8
g >>= 8
b >>= 8
a >>= 8

r = uint32(math.Min(.393*float64(r)+.769*float64(g)+.189*float64(b), 255))
g = uint32(math.Min(.349*float64(r)+.686*float64(g)+.168*float64(b), 255))
b = uint32(math.Min(.272*float64(r)+.534*float64(g)+.131*float64(b), 255))

newColor := color.RGBA{
  uint8(r),
  uint8(g),
  uint8(b),
  uint8(a),
}
// to HERE

In Go, readability is paramount. I would write:

// Part to improve from HERE

rr := float64(r >> 8)
gg := float64(g >> 8)
bb := float64(b >> 8)
aa := a >> 8

newColor := color.RGBA{
    R: uint8(math.Min(.393*rr+.769*gg+.189*bb, 255)),
    G: uint8(math.Min(.349*rr+.686*gg+.168*bb, 255)),
    B: uint8(math.Min(.272*rr+.534*gg+.131*bb, 255)),
    A: uint8(aa),
}

// to HERE


I believe you have a bug in your generic implementation, especially in relation to floating-point style classes that have signed-zero values:

your code:

return (T{} < value) ? value : -value;

would be better as a T{} <= value (or rewritten as (T{} > value) ? -value : value;).

Your current logic will return -0.0 for an input value of 0.0, and that's not appropriate for an abs() function.

Additionally, I don't know how you would really test these things, because, if I am not mistaken, in floating-point comparisons with signed-zero values, -0.0 == 0.0 yet I would expect that abs(-0.0) would return 0.0.

How you resolve this issue though, I don't know.


Concerning

  which one is better

I would prefer the first one, as you can see your values from the beginning, then follow the if-else logic.

However, none if these are very readible!

Naming

Your variable and method names are very misleading. BlackList() looks like you call a constructor. Method names should be verbs (or start with one).

Your variable naming scheme would actually fit for your methods, as IsInBlackList() is the typical naming for methods that return boolean (true/false) values. The variables could then just be called var inBlackList = IsInBlackList().

Logic

It is not clear whether your validation cases are mutually exclusive. Can a captcha be valid and still the user be in the blacklist?

Concerning this code: if (isValidateCaptcha) ... IsSuccess = false, ...
Your variable name implies that it is true if the captcha is valid (which it should, however a better name might be isCaptchaValid). But then you set IsSuccess to false, which makes it seem like your method returns false if the captcha is true, making the logic very hard to understand without looking into the method.

Conciseness

Do you even need these variables? Your variable names are almost identical to your method names (semantically, considering the changes suggested above).

Consider this:

if (IsCaptchaValid()) // replaced the variable with the method call
{
    return Ok(new
    {
        IsSuccess = false,
        InvalidCode = LoginInvalidCode.CaptchaInvalid
    });
}

This way your code becomes shorter and more readible, and your method names should show their intent anyways.

Redundance

This part

return Ok(new
{
    IsSuccess = ...
    InvalidCode = ...
});

appears multiple times with very minor differences. You could increase readability by merging it into one.

For example

LoginInvalidCode invalidCode;
if (!IsCaptchaValid())
{
    invalidCode = LoginInvalidCode.CaptchaInvalid;
}
else if (IsUserDisabled()) {
    invalidCode = LoginInvalidCode.DisableAccountAndInDisableGroup;
}
else if (IsInBlackList()) {
    invalidCode = LoginInvalidCode.InLoginBlackList;
}

var success = invalidCode != null;

return Ok(new { IsSuccess = success, InvalidCode = invalidCode });


Finds all the prime numbers up to n using a strange pattern

The Sieve of Eratosthenes works by going through and marking all numbers that can be divided into, essentially.

Take your input "n", for which you want to find all the prime numbers up to it. The sieve starts at 2, and multiplies 2 by increasing amounts until the multiplication is about to exceed the value "n" - in your program, this is accomplished through the integer division and then iteration up to the calculated result. So, as it multiplies the values together, it marks the result as non-prime. Meaning that 2, 4, 6, 8, 10... etc are all set in the bitarray as 0 (meaning non-prime in this context). It moves on to the next value, so it starts at 3. The process repeats as it marks all multiples as non-prime. Time to move on to the next number - 4. As 4 has been marked as non-prime, it skips over 4 and moves on to 5. This continues until it finally reaches the number which is the value of its square root, so when you are using the sieve to get primes below 100, that means the algorithm checks the multiples of values from 2 to sqrt(100), so 2 to 10. It doesn't need to go past this value as all prime values above that share multiples which values that have already been checked. So, for example, if we moved past 10 to check multiples of 11, we'll get 22 (which is divisible by 2, so has already been marked non-prime) and 33 (divisible by 3). The values which remain with a value of 1 are prime.

tl;dr
The algorithm goes through all prime values below or equal to sqrt(n) and marks their multiples up to n as non-prime. The remaining numbers must be prime.

EDIT: The code above adds 1 to the div operation, which I didn't mention in my explanation.

EDIT 2: This specific modification of the sieve is essentially the same as the original sieve, however rather than removing square values during the normal removal process it removes them separately at the end.


Project Euler #357: Prime generating integers

def divisor_generator(n):
    '''Generates the divisiors of input num'''
    large_divisors = []
    for i in range(1, int(math.sqrt(n) + 1)):
        if n % i == 0:
            yield i
            if i*i != n:
                large_divisors.append(n / i)
    for divisor in reversed(large_divisors):
        yield divisor

I would rename this just divisors, but other than that it seems like a reasonable general-purpose divisor enumerator for very small numbers with a couple of caveats: the doc comment has a typo and uses the wrong name for the input, and if this is supposed to work in Python 3 (which I'm guessing it is from the use of range rather than xrange) then it should use integer division: n // i.

However:

This task doesn't call for a general-purpose divisor enumerator. IMO it would make more sense to return pairs (i, n // i).
To scale to larger numbers it's worth finding the prime factorisation and constructing the divisors from them. The best way I know to do that is to build an array like Eratosthenes' sieve, but instead of storing a Boolean to indicate prime/composite store a prime divisor. (I generally store the lowest prime divisor, but it depends on what you want to do with it). Then you can find the prime factorisation by chaining down the array.

def is_prime(n):
    '''simple prime tester'''
    if n == 2 or n == 3 :
        return True
    for i in range(2,int(n**(1/2))+1):
        if n % i == 0:
            return False
    return True

If you're going to be testing a lot of numbers from just over 0 to N for primality then you definitely want to use a sieve, effectively testing them in parallel and caching the results.

There are a couple of PEP8 violations in this function: space before colon, no space after comma.

def test_condition (divisor_array, num):

    ''' Testing the condition of d+n/d by taking the input as array of divisor and num'''

    if len(divisor_array) %2 != 0: # the divisors of num = d3 is [1,d2,d3], and d2*d2=d3 hence d2+d3/d2 = 2d2 which is not prime
        return False

Nice special case, but it can be generalised a long way. How can you restate the test "num can be split as i and num/i which are not coprime"?

Argue this through all the way and it gives you a completely different high-level algorithm which should be much more efficient. But since this is Project Euler, I'm not going to say more than that hint.

    if sum(divisor_array) %2 != 0: # the divisors of num = d4, [1,d2,d3,d4] (1+d4)=Prime and (d2+d3)==Prime hence sum([1,d2,d3,d4]) must be even
        return False

I don't think I follow this argument. Why does the sum of more than two factors matter?

    if len(divisor_array)%2 == 0:

This condition is unnecessary, because if it failed then we've already returned False.

        for i in range(len(divisor_array)//2):
            if is_prime(divisor_array[i] + divisor_array[-i-1]) == False:
                return False
        return True

It would be more Pythonic to use all(comprehension). Also, this highlights my point about returning pairs of divisors rather than using a general-purpose divisor enumerator.


How can I improve this Caesar encryption?

You are correct in suspecting that the try/catch is not necessary. Generally speaking, Caesar ciphers are implemented using modular arithmetic. We can determine if a character is alphabetical by simply checking if alphabet contains that character; anything else (whitespace, digits, punctuation, etc.) can just be copied as-is, so neither the second for loop nor the proposed switch are necessary either. Here's an example of how you could simplify your code:

public static string encryptTextEng(string plainText, int keyValue)
{
    string encText = "";
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

    foreach (char c in plainText.ToUpper())
    {
        if (alphabet.Contains(c))
        {
            encText += alphabet[Mod((Array.IndexOf(alphabet, c) + keyValue), 26)];
        }
        else
        {
            encText += c;
        }
    }

    return encText;
}

private static int Mod(int dividend, int divisor)
{
    int remainder = dividend % divisor;
    return remainder < 0 ? remainder + divisor : remainder;
}

I threw the Mod method in there because the modulo operator does not work as you might expect with negative numbers.

As mentioned by Bruno in the comments below, a more performant way of checking if the current character is in alphabet and getting the index of that character would be:

foreach (char c in plainText.ToUpper())
{
    int idx = c - 'A';
    if (idx >= 0 && idx < alphabet.Length)
    {
        encText += alphabet[Mod(idx + keyValue, 26)];
    }
    else
    {
        encText += c;
    }
}


Capacity
You don't use capacity, yet you pass it into both your Producer/Consumer classes.  Superficially, it looks like you should be passing the capacity in when creating your Producer semaphore.  This would allow 'capacity' items to be put into your list.  At the moment, you're restricting it to only putting a single item into the list, then reading it back out again.
Thread safety
As it stands, your program works, however, it only works because you have a single consumer and producer.  The way you're using the semaphores means that either a consumer can be running, or the producer can be running, they can't both be running at the same time.  As a consequence, only one thread is working with the list.  If you start supporting more than one producer/consumer however you'll have the potential for having more threads using the collection concurrently... in which case you should consider alternate protection or using a concurrent collection, I'd suggest one of the Queues.
Naming
Some of your names are a little confusing / misleading...
List<Integer> arrayList = new LinkedList<>();

Creates a linked list that's called arrayList...
This is obviously subjective, but I'm also not a fan of semaphoreProducer... I can't help but expect it to be something that produces semaphores.  producerSemaphore works better for me, but as I said...very subjective.
Exit Strategy
Your Consumer thread doesn't have a way to exit, it just keeps on running.  Consider adding some way of notifying the consumer that it's time to shutdown so that the thread can be exited cleanly without you needing to force it to terminate.  This will become more important if your consumer starts doing some processing that takes a while that you don't want to exit in the middle of...