Document iteration: what problems should I account for?

Well, overall, I'd worry first about your variable names :D d, w and t especially. A dev coming in seeing this would say "what sorcery is this?".

Now t.id isn't a guarantee. Not all elements may have an id attribute. You might encounter blanks while climbing up. Try filling it in with element.tagName.

Next would be your hard-coded document-body. Seems like document-body is something specific to your code. Losing it would mean an infinite climb. Why not compare against document for a more guaranteed way to hit the top?

Here's my take on it. Not optimal, but does the same thing.

function climb(element) {
  var elementName = element.id || element.tagName;
  return element === document ? [elementName] : climb(element.parentNode).concat(elementName);
}

document.body.addEventListener('click', function(e) {
  console.log(climb(e.target).join(' <- '));
}, false);
test


Spotify API data to vk.com user's status

Rather than os.environ.get you can do getenv.

In track_data, don't pass Content-Type, because you aren't passing any body with your request.

Otherwise, it's quite reasonable. You may want to expand error checking and reporting, particularly for track_data, since you aren't currently checking the status. raise_for_status is often a good thing to do.


Python program to find the subarray with maximum sum

You should always handle edge cases. For instance, if one were to provide an empty list (or None) to your find_max_subarray() function, alist[start] would throw an IndexError.


Calling lodash _.defaults() before Object.defineProperty()

I don't believe so _.defaults. The properties will be set on this but be enumerable. The call to Object.defineProperty  will just set those properties to not enumerable. If the property didn't exist then the value would be set as undefined and default descriptors.

Let's break out only the necessary.

Empty object.

var x = {};
console.log(Object.getOwnPropertyDescriptor(x, 'clientId'));

Object with clientId set.

var x = {
  clientId: 1
};
console.log(Object.getOwnPropertyDescriptor(x, 'clientId'));

Empty object.

var x = Object.defineProperty({}, 'clientId', {
  enumerable: false
});
console.log(Object.getOwnPropertyDescriptor(x, 'clientId'));

Note that the default descriptors are set.

Object with clientId set.

var x = Object.defineProperty({
  clientId: 1
}, 'clientId', {
  enumerable: false
});
console.log(Object.getOwnPropertyDescriptor(x, 'clientId'));

So if anything were to give you a problem then it would be this situation.

var x = Object.defineProperty({}, 'clientId', {
  enumerable: false
});
console.log(Object.getOwnPropertyDescriptor(x, 'clientId'));
x.clientId = 1;
console.log(Object.getOwnPropertyDescriptor(x, 'clientId'));


Simplifying the array of objects with comma separated values

Honestly, structure-wise, your code seems pretty good. I've just got a handful of minor code-cleanup suggestions:

Use === instead of ==, == does some magical type coercion, and can create unexpected results.
You've got some unenesary parentheses here: auditingInfo = (seriesDataSet).filter(w => (w.dns === '0' && w.pull === '0') && w.corrCd === 1) - you can take out the parentheses around (seriesDataSet) and (w.dns === '0' && w.pull === '0')
What's the reason for initializing auditingInfo to {}, then immediately setting it to a different value? Just do it in one go. For example:

// instead of
let auditingInfo = {};
auditingInfo = ...
// just do
let auditingInfo = ...;

You're using a .map() to extract and rename values from your data set, then the next thing you do is some .map()s again to extract out specific values. Why not take out the first .map() entirely?
After applying these suggestions, you'll be left with this:
let auditingInfo = seriesDataSet.filter(w => w.dns === "0" && w.pull === "0" && w.corrCd === 1);

let auditingDetails = {
  PersonIds: auditingInfo.map(x => x.personId).join(", "),
  BookLetCodes: auditingInfo.map(x => x.ansBook).join(", "),
  ExamNumbers: auditingInfo.map(x => x.examCode).join(", "),
  ExamTitles: auditingInfo.map(x => x.examShortTitle).join(", ")
};

Finally, you had also asked about improving performance. You're not doing anything slow algorithm-wise, so there's not a whole lot of performance gains you can squeeze out of this. I wouldn't bother unless you really need it, in which case, you can try out different micro-optimizations and run performance tests on your target platforms to see which optimizations help the most. (some optimizations could speed things up on one platform and slow them down on another). Any of these types of optimizations will reduce the readability of your code, so only apply them if they make a significant enough impact.
A couple of optimization ideas you can try out that may help out, or may make things worse:

Use a single for loop instead of using .filter() and multiple .map() calls.
Instead of array.join(), gradually build the string.
If you have a large dataset, see if you can gradually consume a stream of data, instead of loading the whole thing into memory, all at once.


Guess Number Game - Console based game using Java

Curious, this code looks a lot like the code in this question. I'm not saying that you have another account, but you don't happen to be in the same class or something?

Your formatting seems to be inconsistent, use an automatic code formatter (your IDE most likely has one).

private static final Scanner SC = new Scanner(System.in);

Don't shorten names just because you can, it makes the code harder to understand and maintain.
The usage of the scanner (or streams in general) should most likely be scoped. Streams are rather easily associated with native resources which must be destroyed explicitly to be freed.

    private static final Scanner SC = new Scanner(System.in);
    private static final Random R = new Random();
    private static int secret = R.nextInt(100) + 1;
    private static final int GIVEN_ATTEMPTS = 10;
    private int attempts = 0;

Some of your state is static, your methods are all instance. You most likely want to make all your state instance.

           if (guess < 1) {
                promptGuess();
            } else {
                return compare(guess);
            }

You're recursing here, so keeping to hit Return without entering something should at some point crash your game because of a stackoverflow.

if (attempts == GIVEN_ATTEMPTS) {

A check for greater-quals would be safer.

private int promptResult(int n) {

This does not prompt for a result, it displays whether the guess was correct or not, the method should be renamed.

        switch (n) {
            case 1:

Instead of using numbers here, you could either use constants or an enum. That way nobody would need to remember that 2 means "too high".

    private void printLine(String s) {
        System.out.println(s);
    }

Good idea, but you're gaining very, very little when it comes to readability with this method.

System.exit(0);

Something to keep in mind is that System.exit is not "exit the application" but "kill the JVM process". When invoking this not even finally blocks may run. In this case it does not matter, but something to keep in mind.

Your logic is all over the place. Instead of chaining the methods together like you did, you should consider having a main method which handles the flow and calls the methods as needed. That way you'd have the logic of your game in one place but the "details" are hidden away in functions, which would make it rather easy to not only figure out how the game works, but also makes it easier possible to change single functions.
Regarding on how to structure this more proper, there is not much to do except cleaning up the mixed state. What you can start with is to have the logic of the game separated from the logic to print to the terminal. So you'd have a Game class and that one would accept a GameUi interface as parameter, like this:
public interface GameUi {
    public abstract int getGuess();
    // ...
}

public class SimpleTerminalGameUi implements GameUi;

public class Game {
    public Game(GameUi gameUi);

    // Somewhere in your logic:
    int guess = gameUi.getGuess();
}

new Game(new SimpleTerminalGameUi());

That would allow you to decouple the presentation from the internal state of the game.
As further exercise, do the same with the secret provider.

I might be mistaken but I think this code is a bit of both styles, and if so, can someone help explain the distinctive differences?

Your code is not object-oriented at all, you're just using a single object as container. But to be fair, there isn't that much logic to shell out to different objects to begin with.


Count Acute, Right and Obtuse triangles from n side lengths

Sort your sticks by length; square them when already sorted. Then replace the innermost loop with 3 binary searches. In pseudocode,

        max_obtuse = upper_bound(A[j:n], A[i] + A[j])
        max_right = upper_bound(A_sq[j:n], A_sq[i] + A_sq[j])
        max_acute = lower_bound(A_sq[j:n], A_sq[i] + A_sq[j])

        obtuse += max_obtuse - max_right
        right += max_right - max_acute
        acute += max_acute - j

That reduces the execution time from \$O(n^3)\$ to \$O(n^2\log n)\$.

EDIT:

In the sorted array below, values marked as - are strictly less, and values marked as + are strictly greater, than X:

    -----XXXXXXXXXXXXXXXXX++++++++++
         ^                ^
         |                This is upper bound of X
         This is lower bound of X


Project Euler #10 -- Summation of primes takes forever

Well, let's start with a few optimizations for you:

Any i that is a multiple of 2 but not 2, is not a prime. Consider upping i by 2 at a time, and starting sum off at 2. i would start at 3.
If something is divisible by 4, it's divisible by 2. Therefore, it's a good idea to make j iterate through a list of already found primes - it's no use testing if something is divisible by 4 if it's not divisible by 2.
3*3 = 9. When you are checking whether a certain i is a prime, you can stop at the point where j*j is greater than the prime to test. For 7, you can stop at 3; 3*3 = 9, after all.


I would suggest using:

if 'auth_token' not in session:
    ...

Since your login function suggests that auth_token is not a key in session, unless the user has logged in.

Other that that, I can see no other improvements.


rock paper scissors game simplify in Python

I'm new to this community, but I'll give this my best shot:

Avoid single letter variable names. Names like k and j convey little about what values they represent, so replace them with something like:

a_player_name = input("Hello guys what are you names: ")
b_player_name = input("and yours? ")

This code:

a_player = input(f"{k} choose: rock, scissors, paper : ").lower()

creates the need to catch errors down the line and is repeated so I recommend replacing it with:

 def input_choices(string):
    while True:
        choice = input(string)
        if choice.lower() in list:
            return choice
        else:
            print('Please type correctly')

a_player = input_choices(f"{k} choose: rock, scissors, paper : ")

This avoids the need for:

    if b_player != list[1] and b_player!=list[0] and b_player!=list[2] or (a_player != list[1] and a_player != list[0] and a_player != list[2]) :
        print("Please type correctly")

Which I hope you agree is a vast improvement. Remember you can always format conditionals like this to improve readablity:

if (
    b_player != list[0] and b_player != list[1] and b_player != list[2]
    or a_player != list[1] and a_player != list[0] and a_player != list[2]
):
    print("Please type correctly")

Or even better use the in keyword

if (
    a_player not in list
    or b_player not in list
):
    print("Please type correctly")

As for the actual rock-paper-scissors logic:

    if a_player == list[1]:
        if b_player == list[0]:
            print(f" {k} wins: paper beats rock")
        elif b_player ==list[2] :
            print(f"{j} wins: scissors beat paper")

    elif a_player == list[2]:
        if b_player == list[0]:
            print(f"{j} wins: rock beats scissors")
        elif b_player == list[1]:
            print(f"{k} wins: scissors beat paper")

    elif a_player == list[0]:
        if b_player == list[2]:
            print(f"{k} wins: rock beats scissors")
        elif b_player==list[1]:
            print(f"{j} wins: paper beats rock")

I'm sure this can be improved with table-driven logic, but I'm sure there's no end of examples for you to skim through in the 'Related' tab.

Hope that helped :)


JavaScript dynamic element filtering functionality

I find that these all radio buttons are of same group , so you can use same name for all the radio button with different values .

<input type="radio" name="displayOption" value="1" checked> All
<input type="radio" name="displayOption" value="2"> Active....

Now in this case you dont have to add and remove active class for the radio buttons. It will handle it by itself.

and write a common function like

$("input[name='displayOption']").change(function(){
 if ($(this).val() === '1') {
      myFunction();
    } else if ($(this).val() === '2') {
      myOtherFunction();
    }
});


This part can be optimized a bit, in terms of length.

List<Integer> mapping = new ArrayList<>();
mapping.add(i+1);
mapping.add(j+1);

if(counts.containsKey(count)){
    List<List<Integer>> existingMappings = counts.get(count);
    existingMappings.add(mapping);
    counts.put(count, existingMappings);
}else{
    List<List<Integer>> newMappings = new ArrayList<>();
    newMappings.add(mapping);
    counts.put(count, newMappings);
}

Java 8 maps have computeIfAbsent. You can use this to "getOrCreate" the existing mapping like so:

List<Integer> mapping = new ArrayList<>();
mapping.add(i+1);
mapping.add(j+1);

counts.computeIfAbsent(count, k -> new ArrayList<>()).add(mapping);

Additionally, you do this:

    List<List<Integer>> existingMappings = counts.get(count);
    existingMappings.add(mapping);
    counts.put(count, existingMappings);

There is no need to put something back into the map when you have retrieved it, because you are retrieving a pointer to a list, and you're using it to add to a list. See this Ideone that lists you put and later retrieve from the map are the same lists.

Okay, so back to this snippet.

List<Integer> mapping = new ArrayList<>();
mapping.add(i+1);
mapping.add(j+1);

counts.computeIfAbsent(count, k -> new ArrayList<>()).add(mapping);

The new ArrayList constructor can take an initialSize argument. Since you're only going to be adding two integers to the list, you could provide this information and save memory space.

List<Integer> mapping = new ArrayList<>(2);

Your algorithm could be more optimized - there's no need to count topic knowledge for a team if they know 7 topics together and there's only 6 topics left to check and the top team currently knows 14 topics. Similarily, there's no reason to store how much topics each team knows, only the teams that know the largest amount of topics, and the largest amount of topics you have currently found.

However, I think that when we look at the loops, you can't really get rid of them.

You see, there's two loops needed to make the teams (iterating people over people), and one loop needed to check the topics (iterating over topics). There are clever tricks you could use where you take the binary string and convert it to an integer, but when you do that, you're looping over the characters in the binary string - it has to read the string, after all. You just don't use a for loop.

So we're doomed to have at least 3 loops. What you CAN do is take the counting loop and put it in a separate function. That would "get rid" of one of the loops. Your static analyzer is not built with the idea of such challenges in mind - to see a method with 3 nested loops usually means the method is doing too much work.


Project Euler Problem 12 in Python 3 (Find triangle number with 500 divisors)

As @vnp notes in the comments, the fact that triangular numbers are products of coprime numbers allow for very efficient factorization - see this thread for an illustration of the idea in Java, easily carryable over to Python - which I'll illustrate in my code too.

The idea here is that since the \$n\$th triangular number is the product of 2 numbers \$n\$ and \$\displaystyle\lfloor\frac{n+1}{2}\rfloor\$, which implies that if \$n\$ is even then \$\displaystyle\frac{n}{2}\$ and \$n+1\$ are 2 relatively prime integers, whereas if \$n\$ is odd then \$\displaystyle\frac{n+1}{2}\$ and \$n\$ are 2 relatively prime integers. This makes factorizing the resultant \$n\$th triangular number take less time as now a divide-and-conquer approach can be employed, making this part of the algorithm \$\mathrm{O}(\log_2n)\$ in time.

As I previously posted in my comment to the question, this StackOverflow thread is a good reference for efficient factorization, especially the first answer there.

The idea is that there can be no prime factors of a number greater than its square root, and factors are paired in the sense that each factor \$i\$ of a number \$\text{num}\$ has a complementary factor \$\displaystyle\frac{\text{num}}{i}\$. Thus we can use a sublinear time algorithm to factorize integers, which involves enumerating to only \$\lceil\sqrt{\text{num}}\ \ \rceil\ (\mathrm{O}(\text{num}^{\frac{1}{2}}))\$ instead of \$\text{num} - c\ (\mathrm{O}(\text{num}))\$, where \$c\$ is some constant factor.

That gives us the major time savings.

You adhere to the Python style guide, PEP8, quite well, so I have no stylistic comments for you, except for the fact that tri_nums could be a bit more descriptive, e.g., triangular_numbers (you're using an editor with autocomplete support, aren't you?)

Side notes:

The while loop searching for the required number can and should be extracted into a function, which receives the initial value of x as a parameter, instead of hard-coding it to 500.
The timing and actual execution should be moved into a main() function, which is called using the standard script idiom of if __name__ == "__main__".
The floor (or integer) division operator // makes all those casts to int redundant.
Use a proper benchmarking toolkit for timing execution, with recommended best practices, e.g. timeit.
Last but the most important - the while True: ... if <condition>: break ... idiom is frowned upon in the community, when an equivalent while not <condition>: ... can be used without control flow redirection. It makes reasoning about the code more linear.

Finally, here is the code (only minimally changed from your original to incorporate my suggestions):

# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be
# 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
# The first ten terms would be:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# Let us list the factors of the first seven triangle numbers:
#
# Omitted
#
# We can see that 28 is the first triangle number to have over five divisors.
#
# What is the value of the first triangle number to have over five hundred divisors?

import time
import math

def count_factors(num):
    # One and itself are included now
    count = 2
    for i in range(2, int(math.sqrt(num)) + 1):
        if num % i == 0:
            count += 2
    return count

def triangle_number(num):
    return (num * (num + 1) // 2)

def divisors_of_triangle_number(num):
    if num % 2 == 0:
        return count_factors(num // 2) * count_factors(num + 1)
    else:
        return count_factors((num + 1) // 2) * count_factors(num)

def factors_greater_than_triangular_number(n):
    x = n
    while divisors_of_triangle_number(x) <= n:
        x += 1
    return triangle_number(x)

def main():
    start = time.time()
    print('The answer is', factors_greater_than_triangular_number(500))
    print('Answer found in', time.time() - start, 'seconds')

if __name__ == '__main__':
    main()

This runs in about 0.01 seconds on my system (CPython 3.6.0 Windows x64, Windows 10 Pro 1703, Intel™ Core i7 6500U (Dual Core), 8GB RAM).

I cannot believe that on your system it really took over 10 hours to run - do comment with details of your system like I did above and let me know how much better this version does!


There seems to be no reason to define self.nFriends as an instance variable. Define it instead as a function local one.

Then you have no use for the self parameter, so consider making it a stand-alone function, or at least a staticmethod.

Stick to PEP 8. No reason not to. I'll be working with a PEP 8-ified version of the code.

Instead of initializing best and doing a manual reduction with max, instead make a count_three_friends iterable and use max to reduce it:

def count_three_friends(friends):
    n_friends = {}
    for i in range(0, len(friends)):
        ...
        n_friends[i] = count
        yield count

def most_three_friends(friends):
    return max(count_three_friends(friends))

n_friends is not used. Remove it.

You can flatten this a bit by taking account of early loop exits:

def count_three_friends(friends):
    for i in range(0, len(friends)):
        count = 0
        for j in range(0, len(friends[i])):
            if i == j:
                continue
            # direct friends
            if friends[i][j] == 'T':
                count += 1
                continue

            done_counting3 = False
            # check whether i and j have a friend k in common
            for k in range(0, len(friends)):
                if done_counting3:
                    break
                if k == i or k == j:
                    continue
                if friends[i][k] == 'T' and friends[j][k] == 'T':
                    count += 1
                    break
                for p in range(0, len(friends)):
                    if p == k or p == i:
                        continue
                    if friends[i][p] == 'T' and friends[p][k] == 'T' and friends[k][j] == 'T':
                        count += 1
                        done_counting3 = True
                        break

        yield count

Change range(0, ...) to just range(...).

Try to use enumerate and replace 'T'/'F' with booleans. I'll initially use enumerate and discard the second parameter to keep the transition small.

Then consider that your structure is

for each person:
    and each other person:
        if friends, count += 1
        or indirect friends, count += 1

The "or indirect friends" bit could be a separate function to avoid the done_counting3 variable:

def indirect_friend(friends, i, j):
    for k, _ in enumerate(friends):
        if k == i or k == j:
            continue

        # If  friends[i] is friends with friends[k]
        # and friends[j] is friends with friends[k]
        if friends[i][k] and friends[j][k]:
            return True

        for p, _ in enumerate(friends):
            if p == k or p == i:
                continue

            if friends[i][p] and friends[p][k] and friends[k][j]:
                return True

def count_three_friends(friends):
    for i, _ in enumerate(friends):
        count = 0

        for j, _ in enumerate(friends):
            # Don't look at self-friending
            if i == j:
                continue

            # Direct or once-indirect friend
            if friends[i][j] or indirect_friend(friends, i, j):
                count += 1

        yield count

def most_three_friends(friends):
    return max(count_three_friends(friends))

Note that

# If  friends[i] is friends with friends[k]
# and friends[j] is friends with friends[k]

seems to be wrong; this means

most_three_friends([[0, 1, 0], [0, 0, 0], [0, 1, 0]])

gives 2 despite no person's friend having any friends. This of course will only happen if the friendship graph is non-symmetric, but you've not required that it is.

I suggest reversing the second line to

# and friends[k] is friends with friends[j]

by changing friends[j][k] to friends[k][j].

Now, instead of getting deeper into how this could be improved, I'm going to express this as a matrix transformation. Consider the matrix X.

[[X, X, X],
 [X, X, X],
 [X, X, X]]

The kth person's list of friends is the list X[k, :] - take a single of the first dimension and the first of the second.

The matrix X[k, :, newaxis] in Numpy is thus the same with another dimension:

[[a],
 [b],
 [c]]

Now, this can be multiplied with the original as

[[a],     [[X, X, X],     [[a*X, a*X, a*X],
 [b],  *   [X, X, X],  =   [b*X, b*X, b*X],
 [c]]      [X, X, X]]      [c*X, c*X, c*X]]

This operation thus filters the friend list by the person's friends. You can then do an any along the y-axis to find once-indirect friends.

(friends[k, :, newaxis] * friends).any(axis=1)

The magic of Numpy's broadcasting lets us do all k at the same time by just taking a slice.

(friends[:, :, newaxis] * friends).any(axis=1)

This is a bit cryptic, but it's also an extremely powerful way of modelling the situation. For example, to calculate the transitive closure of friendship (find the number of people you are friends through any number of indirections), such a model becomes extremely helpful.

To use this, one could do

from numpy import array, identity, newaxis

def friend_problem(friends, iterations=2):
    # Include self-friendships for transitivity
    graph = arcs = friends | identity(len(friends), dtype=bool)

    # Apply search to graph
    for _ in range(iterations):
        graph = (graph[:, :, newaxis] * arcs).any(axis=1)

    # Subtract one for the self-friendship
    return graph.sum(axis=-1).max() - 1

And call it with

friends = array([[0, 1, 0], [0, 0, 0], [0, 0, 0]], dtype=bool)
friend_problem(friends)

Note that this works for any number of iterations; one can trivially do friends-of-friends-of-friends-of-friends-of-friends. This is not optimal for full transitive closure, but it's fine for small iteration counts. It's should also be a fair bit faster.


Storing data into an SQL table using multiple threads and queues

Single-Threading Style:

Managing resources:

You should be using using to manage your connection. It completely eliminates that... unsightly Try-Catch-Block. Compare following snippet from msdn with a similarly stripped version of your code:

Using connection As New SqlConnection(connectionString)
    connection.Open()
    ' Do work here; connection closed on following line.
End Using

Try
    SQLCon.Open()
    ' Do work here; connection closed on following line.
    SQLCon.Close()
Catch ex As Exception
    MsgBox(ex.Message)
    If SQLCon.State = ConnectionState.Open Then
        SQLCon.Close()
    End If
End Try

Naming

While SQLCon and SQLCmd are ... conventional names, they are a little short and have the air of systems-hungarian... I'd prefer connection and command.

Also Thread1 is really non-speaking, InsertingThread may be the better option.

Whitespace

I like to keep separate Subs clearly outlined by an empty line before starting with [Modifier] Sub ...

Comments and documentation

You may have removed it, but ... this code is extremely undercommented and underdocumented. A comment here and there can help a little wit easing the reading. Then again this code is rather simple and obvious by the names...

Multi-Threading Style:

First off, you currently only allow a single Thread to run... well almost, because of possible interleaving and nonatomic comparison operations.

Consider the following:

Thread 1                   Thread 2
- If Not deququeing
                           - If Not dequeuing
                               - dequeueing = True
    - dequeueing = True

Suddenly you have 2 threads running and that when you could've had everything easy.

The queue docs mention ConcurrentQueue(Of T) when you "need to access the queue across multiple threads"
This makes the failed attempt at synchronizing with a shared boolean unnecessary and overall improves the code quality.

End result:

After applying my critiques I end up with following code:

Private addLogQueue As New ConcurrentQueue(Of String)

Public Sub addLogHandler(ByVal machineName As String, ByVal LogTime As Date, ByVal EventLog As String, ByVal EventValue As String)
    addLogQueue.Enqueue("INSERT INTO ... some SQL CODE")
    Dim InsertingThread As New System.Threading.Thread(AddressOf addLog)
    InsertingThread.Start
End Sub

Private Sub addLog()
   Using (connection As New SqlConnection(connstring))
        connection.Open()
        Dim statement As String
        While addLogQueue.TryDequeue(out statement)
            command = New SqlCommand(statement, connection)
            command.ExecuteNonQuery()
        End While
    End Using
End Sub


Central ajax function in jquery

No. Just, no. It's tempting to handle how all AJAX operations are called in your app, but this is usually just for a handful of use cases. I've seen code time and again do this only to actually call $.ajax directly elsewhere because the "global" one just doesn't serve its needs.

var ajaxCall = function(_url, _type, _data, _successCallback, _errorCallback, isAsync, _completeCallback){

jQuery AJAX methods return a promise-like object. Use the standard promise interface to assign callbacks instead of using the old callback method. That means, use the then method. Using this also makes your code easily portable to standard APIs like fetch.

Additionally, there's no sense adding _ before variable names. It only adds noise. If you mean to avoid collisions, just use different variable names. Don't make it more complicated than it already is.

// Handling _url
if(!_url.trim()) throw new Error('Sucess callback is not defined');

// Handling _type
if(!_type.trim()) throw new Error('TYPE is not defined');

// Handling _successCallback
if(!_successCallback || typeof _successCallback !== "function") throw new Error('Success callback is not defined');

// Handling _errorCallback
if(!_errorCallback || typeof _errorCallback !== "function") _errorCallback = function() {};

// Handling _completeCallback
if(!_completeCallback || typeof _completeCallback !== "function") _completeCallback = function() {};

I also wouldn't do these param checks and preprocessing if I were you. A function should assume the arguments are correct. That way, it fails on bad input. It's also the duty of the consuming code to use the function correctly. Don't make it just catch the other code's fault. Let the function fail on bad input, let the browser throw an error or do a bad request. A visible error on the network or console is a bazillion times better than some function swallowing errors.

async: isAsync !== false ? true : false,

Synchronous XHR should never be an option. It freezes the UI and that's bad for UX. Learn how to write and deal with asynchronous code. Don't work around it.

try {
  _successCallback(data);
} catch (exception) {
  global.logger.i(TAG, 'Exception! ' + exception);
}

Lastly, your function should not be concerned about the callback. It's none of its concern. Let the callback handle its own errors. Also, globally swallowing errors is a bad idea. Errors are harder to trace. ANd if your logger is disabled, you will never know the callback failed.

In the end, the call you aim to globalize is nothing more than just the following. $.get is an explicit shorthand for $.ajax({ method: 'get' }) ($.ajax defaults to GET but you'd have to know jQuery by heart to know that). type can be omitted if your server returns the correct content type response headers for JSON so jQuery knows what to do with it.

$.get({
  contentType: 'application/json',
  data: { ... },
  url: '...'
}).then(function(res){
  // AJAX succeeded
}, function(err){
  // AJAX failed
});


Optimize jQuery code includes autocomplete function for different input box with different autocomplete content

Quick answer: Use arguments.

function initAutocomplete(selector, lookup) {
  $(selector).autocomplete({
    deferRequestBy: 0,
    autoSelectFirst: true,
    lookup: lookup,
    onSelect: function (value, data) {
      cdSubjectInput.val(value.value);
      $(".wikiSubmit").click();
    }
  });
}

initAutocomplete("#ctl00_ContentPlaceHolder1_txtAssociation", txtAssociation);
initAutocomplete("#ctl00_ContentPlaceHolder1_txtSubject", txtSubject);

Of course, it might be nice to decouple the markup and the code some more. Depending on how the lookup lists (their length and contents), you could do something like this in your HTML:

<input data-lookup="foo,bar,baz" ...>

and init every autocompleting input on the page in one go with:

$("input[data-lookup]").each(function () {
  var input = $(this),
      lookup = input.data("lookup").split(","); // get the lookup strings

  input.autocomplete({
    deferRequestBy: 0,
    autoSelectFirst: true,
    lookup: lookup,
    onSelect: function (value, data) {
      cdSubjectInput.val(value.value);
      $(".wikiSubmit").click();
    }
  });
});


Comments on your code

The access modifier for your constructor is missing.

function __construct...
public function __construct

Although no specified access modifier on methods means that PHP chooses public automatically (see PHP docs), I would add it for consistency.
Your autoloader does not cope with namespaces. You might want to read PSR-0, a specification stating how autoloaders should cope with namespaces, folders and filenames.
Do not add random newlines.

public function load($class)
{

    // expload the namespaces ex: foo\bar\tar array(foo, bar, tar)

public function load($class)
{
    // expload the namespaces ex: foo\bar\tar array(foo, bar, tar)

Do not add random spaces in comments.

// expload the namespaces ex: foo\bar\tar array(foo, bar, tar)
//get the last exploaded string and append .php so it becomes tar.php

Be consistent! I suggest using a space after //.
Be specific in variable names. $pathToClass lets me think that the string points to a specific class file. It does however point to a directory containing class files. I suggest using $classDir. $class is also an edge case since it does contain more than a single class name.
You don't need explode if you only wish to extract the class name.
Use strrpos():

$classFilename = substr($class, strrpos($class, '\\') + 1) . '.php';

Don't apply strtolower two times. Just save the result in a temporary variable. It makes your code DRY.
Since you declare pathToClass private anyway, consider marking the class final. Some arguments are provided in an article Final should be Default for Classes in Java (the same principles not only apply to Java, but also to many other languages including PHP).
Mark your load method private. It's an implementation detail, which shouldn't be accessible from outside the class.
Your load method is not required to return a boolean value. Returning true or false is not bad per se, maybe you will want to encapsulate the autoloading mechanism further and throw exceptions depending on the return value.

Elaborating on the PSR-0 specification

The spec defines mandatory requirements your autoloader must fulfill.

They provide example inputs your autoloader must accept:

\Doctrine\Common\IsolatedClassLoader => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php
\Symfony\Core\Request => /path/to/project/lib/vendor/Symfony/Core/Request.php
\Zend\Acl => /path/to/project/lib/vendor/Zend/Acl.php
\Zend\Mail\Message => /path/to/project/lib/vendor/Zend/Mail/Message.php

\namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php
\namespace\package_name\Class_Name => /path/to/project/lib/vendor/namespace/package_name/Class/Name.php

Roughly speaking, your code is missing the following aspects:

Taking the namespace into account and using it to build a directory hierarchy.
Transforming underscores in class names to a directory hierarchy as well.


Generator expression in combination with StopIteration: kind of a hack?

I would discourage this particular usage. Not exactly because it's a risk or a hack—in other circumstances it might even be the right choice for good performance—but because I find it quite obfuscatory. (This happens to echo the usual guidance to avoid using exceptions for flow control, although it's harder to apply that guidance around Python's iterators.)

Instead I would suggest trying to make it clear what you are doing. I believe in this case you are trying to find the "first" key that maps to a list of values containing short_name in index 0. (I say "first" because it's in dictionary order, which isn't a particularly meaningful; it's probably more useful to say an arbitrary key.) If such a key does not exist, you wish to fall through to your except case. A reader is going to find that motive hard to discern. Here is an alternative way to write the first couple lines using itertools:

from itertools import islice

short_name = short_name.upper()
# find a key of an item containing short_name, if available
m = list(islice((k for k,v in c.countries_dict.iteritems() if v[0] == short_name), 1))
if not m:
    # due to bad data, not all short_name values are mapped correctly; try another way
    # code from original except StopIteration

For bonus readability you might split that up into a named generator function that finds all matches, and then filter to the first match with islice or another helper. Clearly performance isn't your goal here, as you're scanning a dict by value. (If you have a lot of these to look up, you may want to create the reverse dict instead of scanning multiple times.)

I'm far from certain that this code is what you intended. Since in the fallback case you build up a list of potentially multiple values, it seems surprising that in the primary case you explicitly exclude alternate keys. If you wanted to include all keys, you can skip islice and use a simple list comprehension: (Note that by slicing the list comprehension with [:1], it would yield the same value for m as the previous approach, and is more readable, although it potentially does more work.)

short_name = short_name.upper()
m = [k for k,v in c.countries_dict.iteritems() if v[0] == short_name]
if not m:
    # due to bad data, not all short_name values are mapped correctly; try another way
    # code from original except StopIteration


If what worries you is readability use a function that takes care of the exception:

boolean error = false;
for(String file_name : files_to_move){
    error |= moveTheFile(...);
}
if (error) {
    // throw your exception here
}

The function would be something like:

private boolean moveTheFile(...) {
    try {
         Script.move(QNFiles.getProject(), file_name, calcDir);
    } catch (Exception ex) {
        Logger...blah.blah.blah;
        return true;
    }
    return false;
}


Using reflection to connect to an arbitrary backend

You're loading every DLL in the directory even if you find what you want in the first one.

I'd guess that loading an assembly is what takes more time and resources than looking for what you want in the assembly-after-it's-loaded.

You code will fail if there's a type which implements IDataAccess but which doesn't have an Instance property.

You might want to load into a different AppDomain if you want to unload the assembly which you loaded.


Solution for sum of all fizzbuzz numbers in a given range

I don't have much to say for the code itself, it is concise, readable and does what you want it to do. That's a good start. My only critique is that you handle input and output in the same place, if you plan on reusing the code maybe consider making a method.

So since the code is on point, we can look at the algorithm you are using. The only time the sum will change is when the sequence passes a multiple of 15. So lets see if we can find which multiples of 15 are between our starting point (x) and our ending point (y).

If we start at x, the first multiple of 15 we will encounter will be

$$15 \lceil \frac{x}{15} \rceil$$

To give you some intuition as to why this is the case, my argument is as follows. When you divide a number by 15, you get a whole part (how many 15s you can make from x) and a remainder (how many are left over when you make as many 15s from x as you can). The next multiple of 15 after (or including) x will be the first number you get when counting upwards who's remainder is 0. In other words, the remainder is a progress bar of how close to 15 we are. By taking the ceiling of x / 15, we are setting the progress bar to full, so when we multiply by 15 we get the next multiple.

What is the last multiple before (or including) y? We can use similar logic to get

$$15 \lfloor \frac{y}{15} \rfloor$$

And now we can directly loop over multiples of 15, no need to do any mods.

int start = 15 * (int)Math.Ceiling((double)start_range / 15);
int end = 15 * (int)Math.Floor((double)end_range / 15);
int sum = 0;
for (int i = start; i <= end; i += 15) {
    sum += i;
}

We don't have to stop there. This is a straightforward enough sum so we can somewhat simplify it.

$$start + (start + 15) + (start + 30) + ... + end$$

We can write start and end as multiples of 15 (where a and b are just integers).

$$15a + (15a + 15) + (15a + 30) + ... + 15b$$

We will now factor out 15 term.

$$15(a + (a + 1) + (a + 2) + ... + b)$$

int a = (int)Math.Ceiling((double)start_range / 15);
int b = (int)Math.Floor((double)end_range / 15);
int sum = 0;
for (int i = a; i <= b; i++) {
    sum += i;
}
sum *= 15;

I think the sum is simple enough now that we can do it without a loop. I'm going to "cheat" a little and just introduce the identity we will use without much explanation. There are some nice visualizations and proofs online if you want to look them up yourself.

$$ a, b \in \mathbb{N}; \sum_{i=a}^{b}{i} = \sum_{i=0}^{b}{i} - \sum_{i=0}^{a-1}{i} $$

The sum of numbers from 0 to n is well known

$$ \sum_{i=0}^{n}{i} = \frac{n^2+n}{2} $$

So we can use this equation to derive

$$ \sum_{i=a}^{b}{i} = \frac{b^2+b}{2} - \frac{(a-1)^2 + a - 1}{2} $$

$$ = \frac{b^2+b}{2} - \frac{a^2 - 2a + 1 + a - 1}{2} = \frac{b^2+b}{2} - \frac{a^2 - a}{2} $$

$$ = \frac{b^2+b - a^2 + a}{2} $$

This is only a couple of lines of code now, and should run in constant time.

int a = (int)Math.Ceiling((double)start_range / 15);
int b = (int)Math.Floor((double)end_range / 15);
int sum = 15 * (b*b + b - a*a + a) / 2;

Final remarks, in many languages integer division will floor the result (once the numbers are both positive). This means we can avoid Math.Floor if we assume end_range >= 0 (which seems like a fair assumption).

We also have the constant 15 strewn around the code, let's make it a variable.

int num = 15;  // A magic number specific to our problem
int a = (int)Math.Ceiling((double)start_range / num);
int b = end_range / num;
int sum = num * (b*b + b - a*a + a) / 2;

We could also avoid the Math.Ceiling call but the code may lose it's readability. The code also doesn't account for bugs like overflow, and it could be reworked to delay those issues. Currently, I don't think either of these changes would be worth it.


Pretty hard to pick on this, looks pretty nice already!

You have this duplicated pattern though:

if (-not(Test-Path $filepath)){
    New-Item -ItemType file -Path $filepath -Value $i
}
# ...
if (-not(Test-Path $queue_filepath)){
    New-Item -ItemType file -Path $queue_filepath -Value $value
}

You could create a function that takes $path and $value and use it twice instead of duplicating code.

And the comments are pointless, your code already speaks for itself (nice!), so just delete them!

Other than these nitpicks, I don't see a better way to do what you want.


Some minor stuff -

your member functions and properties should be lower-case by PEP8
you should add a property to get the discriminant, particularly since you use it in multiple places
I don't know what time_dependent and x_plus_3 do, nor why they're here. They seem like specific applications of the quadratic formula for a narrow situation. Given that, they should not be in this class.
The returns from vietas_formula should not be strings; you should return a tuple of floats. Similar for vertex. Currently this is premature stringizing. Your roots already does this correctly.
If you wanted to be thorough, d < 0 should not raise a ZeroError and instead should return complex roots. Python has built-in support for complex numbers.
self.x does not belong as a member on the class.
Have you renamed DeltaError to ZeroError?
Exception.__init__ should be changed to use super()
The error message Delta must be greater than 0! is not strictly true, and should be greater than or equal to zero.
Why must a, b, c be int? You should accept float.

Some major stuff: have you checked this for correctness? I see at least three algebraic errors, including that d = sqrt(b * b - 4 * a * c) is calling sqrt too early to catch failures, and -b / 2 * a has incorrect order of operations. Unit testing for this kind of code is both easy and important; while translating your code I ran into test failures and had to make corrections almost every step of the way.
Suggested
I still don't understand why your code needs to take a break (it's actually pretty funny. Maybe it's unionized?), but so be it:
from cmath import sqrt, isclose
from datetime import datetime, time
from numbers import Complex
from typing import Union, Tuple

RootTypes = Union[
    Tuple[Complex],
    Tuple[Complex, Complex],
]

WORK_HOURS_START = time(8)
WORK_HOURS_END = time(16)

class Quadratic:
    def __init__(self, a: float, b: float, c: float):
        self.a, self.b, self.c = a, b, c

    def y(self, x: Complex) -> Complex:
        a, b, c = self.a, self.b, self.c
        return a*x*x + b*x + c

    def dydx(self, x: Complex) -> Complex:
        a, b = self.a, self.b
        return 2*a*x + b

    @property
    def discriminant(self) -> float:
        a, b, c = self.a, self.b, self.c
        return b*b - 4*a*c

    @property
    def roots(self) -> RootTypes:
        a, b, c, d = self.a, self.b, self.c, self.discriminant
        if d == 0:
            return -b/2/a,

        sqrt_d = sqrt(d)
        return (-b + sqrt_d)/2/a, (-b - sqrt_d)/2/a

    @property
    def vietas_formula(self) -> Tuple[
        float,  # sum
        float,  # product
    ]:
        a, b, c = self.a, self.b, self.c
        return -b/a, c/a

    @property
    def vertex(self) -> Tuple[
        float,  # p
        float,  # q
    ]:
        a, b, c, d = self.a, self.b, self.c, self.discriminant
        return -b/a/2, -d/a/4

    def describe(self) -> str:
        v1, v2 = self.vietas_formula
        return (
            f'Roots: {self.roots}\n'
            f'Vieta constants: x1+x2={v1}, x1*x2={v2}\n'
            f'Vertex: {self.vertex}'
        )

def time_problem() -> None:
    if WORK_HOURS_START <= datetime.now().time() < WORK_HOURS_END:
        a, b, c = 1, 5, 6
        quad = Quadratic(a, b, c)
        print(quad.describe())
    else:
        print("I'm on a break for some reason.")

def abs_close(x: Complex, y: Complex) -> bool:
    return isclose(x, y, abs_tol=1e-12)

def test_two_real() -> None:
    q = Quadratic(1, 5, 6)

    x1, x2 = q.roots
    assert abs_close(0, x1.imag)
    assert abs_close(0, x2.imag)
    assert abs_close(0, q.y(x1))
    assert abs_close(0, q.y(x2))

    v1, v2 = q.vietas_formula
    assert abs_close(v1, x1 + x2)
    assert abs_close(v2, x1 * x2)

    vx, vy = q.vertex
    assert abs_close(0, q.dydx(vx))
    assert abs_close(vy, q.y(vx))

def test_one_real() -> None:
    q = Quadratic(9, -6, 1)

    x, = q.roots
    assert abs_close(0, x.imag)
    assert abs_close(0, q.y(x))

    # In this case Vieta's formula can be interpreted as two identical superimposed roots
    x1, x2 = x, x
    v1, v2 = q.vietas_formula
    assert abs_close(v1, x1 + x2)
    assert abs_close(v2, x1 * x2)

    vx, vy = q.vertex
    assert abs_close(0, q.dydx(vx))
    assert abs_close(0, vy)

def test_two_complex() -> None:
    q = Quadratic(4, -4, 3)

    x1, x2 = q.roots
    assert not abs_close(0, x1.imag)
    assert not abs_close(0, x2.imag)
    assert abs_close(0, q.y(x1))
    assert abs_close(0, q.y(x2))

    v1, v2 = q.vietas_formula
    assert abs_close(v1, x1 + x2)
    assert abs_close(v2, x1 * x2)

    vx, vy = q.vertex
    assert abs_close(0, q.dydx(vx))
    assert abs_close(vy, q.y(vx))

def test() -> None:
    test_two_real()
    test_one_real()
    test_two_complex()

if __name__ == '__main__':
    test()
    time_problem()


Project Euler 28: sum of spiral diagonals using recursion

Performance is okay (linear), but I think the code can be simplified by using a loop instead of recursion, and by going from the inside-out instead of from the outside-in.

Here's how I did it, in pseudo-code:

sum = 1   # running sum
last = 1  # last number
delta = 2 # delta between numbers

for layer in 1 to (sidelength - 1) / 2:
    for num in 1 to 4:
        last += delta
        sum += last
    delta += 2 # increases by two with each layer

return sum

Also, I think this is one of those probems that can actually be calculated directly using pencil and paper, without any loops. Why don't you check out the problem forum there?


JavaScript coding style for initializing variables

As you are not using ; consistently I would say that your init style is dangerous as it will block automatic colon insertion.

For example the following lines will throw a syntax error SyntaxError: Unexpected token '{'

 var a = foo{
    // init stuff
 }

Or syntax error Missing initializer in destructuring declaration

 var a = 0,{
    // init stuff
 }

In a sea of code this type of typo is easily overlooked. Though it is a syntax error so will not lay in wait (in most normal situations)

When you allow the ; to be inserted by moving the { to a new line it is safer.

 var a = foo
 {
    // init stuff
 }

however the concern is that you are doing more than simple assignment within the block which could lead to situation such as

 var a = {}
 {
     let a.bar = foo  // was meant to be a.bar = foo
 }

The let is a typo but will not get caught until the code is run.

If you do continue to use this style I would recommend you use semicolons and be very strict in regards to the extent of the setup code within the block.

Personally I think its ugly.


UI error display window with task async in WPF

This is a good fit for async await:

public async void RunProgramLogic()
{
    if (!IsRunning)
    {
        IsRunning = true;
        try
        {
            await Task.Run(() => ProgramLogic())
                      .ConfigureAwait(true); // schedules back to the synchronization context the method was called from.
        }
        catch (Exception e)
        {
            logger.Error(e); // Log or LogError feels like better names
            windowManager.ShowDialog(new ForceCloseViewModel(e.Message), null, null);
        }
        finally
        {
            IsRunning = false;
        }
    }
}

Regarding async await
As you can see using async and await removes quite a bit of noise from the code.
In general async void is smelly and should only be used for eventhavndlers.
In your case it feels like a decent fit since you handle the exceptions. Async void means it cannot be awaited.

Regarding command:
While I agree that this looks like a fit for a RelayCommand it is not trivial due to the async.

Here is a good read on commands for async scenarios.

Most RelayCommand implementations handle raising CanExecuteChanged poorly by calling CommandManager.InvalidateRequerySuggested which is very inefficient.

Here is a nice implementation.

Regarding scheduling
Always be explicit with .ConfigureAwait(true|false) when awaiting. The default is true which means that the code continues on the synchronizationcontext it came from. This is a strange default in my opinion and ConfigureAwait is a poorly named method.
In your case I think the logger and windowManager should be thread agnostic enabling .ConfigureAwait(false)
Suggested implementation:

public class WindowManager
{
    public void ShowDialog(object viewModel, ...)
    {
        if (Dispatcher.CurrentDispatcher.CheckAccess())
        {
            ShowDialogCore(viewModel, ...);
        }
        else
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => ShowDialogCore(viewModel, ...)));
        }
    }

    private void ShowDialogCore(object viewModel, ...)
    {
        ...
    }
}

The upside with implementing it like this is that the caller will not need to remember to call it on the UI thread. It is the job of the windowmanager to schedule if needed. Hence fixing many potential bugs in one place.

Regarding the pattern Using a flag like this is fine and will work well if you refactor to relaycommand. A try-finally block makes it clear in my opinion.


Here's how I would have written the slider. For a small project like this, you probably don't need to use Prototypal Inheritance. However, if you wanted to scale or add new functionality it would be a walk in the park. As you dive into larger projects, taking time to plan how you're going to structure your code will greatly improve your ability to write the same. Keep in mind if any part of this is confusing or unclear, I'll be happy to walk you through it. I've included the code in this fiddle, but I'll do most of the explaining in the commented code below.
Now onto the fun stuff. You can place the following code in a separate .js file.
function Slider ( container, nav ) {
    //Get the elements passed in
    this.container = container;
    this.nav = nav;

    this.divs = this.container.find('div'); //Select the divs in the container
    this.divWidth = this.divs.width(); //Width of each div
    this.divsLen = this.divs.length; //Count how many divs there are

    this.current = 0; //Set the counter to the first div
};

//This function does all the animation
Slider.prototype.transition = function( speed ) {
    this.container.animate({
        //Set the margin to a negative, hence the "-" in front.
        //Get the current div, multiply by its width, and multiply by 3.
        //This makes the animation move three divs at a time.
        //If you changed the width in the CSS, this code would work just fine.
        'margin-left': -( this.current * this.divWidth * 3 )
    }, speed); //Here I get the speed from the click event set up in your html file.
};

//Here is where it might get tricky.
//This function controls the current set of divs being displayed.
Slider.prototype.setCurrent = function( dir ) {
    var pos = this.current; //Cache the current div

    //Okay. Take a breather right here :)
    //Get the current div and add to it depending on what is returned.
    //We test to see if the clicked button was 'next'.
    //If true, it returns '1' and adds that to 'pos'.
    //If false, that means you clicked 'prev'. It then returns a '-1' and adds to 'pos'.
    pos += ( ~~( dir === 'next' ) || -1 );

    //Now if we kept clicking 'prev', we would end up with a negative number after a while.
    //This tests to see if 'pos < 0'.
    //If yes, take the total divs, divide by 3, and subtract one.
    //This will make it display the last three divs. It kinda goes 'backwards'.
    //If pos isn't < 0, then take modulus of pos and the total / 3
    //Modulus is a math operator and if you're not clear on it, there's a link in the bottom.
    this.current = ( pos < 0 ) ? (this.divsLen / 3) - 1 : pos % (this.divsLen / 3);

    return pos;
};

This part comes after your script in the previous .js file. It can be in your html page at the bottom. I set up the previous piece of code so that we can refrain from referencing any DOM elements or specific values, keeping the logic separate. This part now sets all the configurations we and values to be sent to the slider.
//First off, if your user doesn't have JS on, your plugin will fail.
//I've set the wrapper overflow to scroll in the CSS, so if there is no JS, the
//user can still scroll and see all the divs.
//Here we set the overflow to hidden and select our container element.
var container = $('.wrapper').css('overflow', 'hidden').children('.container');

//Set up the Slider constructor function, and pass in the elements we want.
var slider = new Slider( container, $(".nav_wrapper") );

//Again, if there's no JS, there's no point in having buttons.
//The buttons are hidden in the CSS, and here we display then with .show().
//Then we select and set up the click event on the actual div button.
slider.nav.show().find('div').on('click', function() {
    //When clicked, we call the functions from our previous code, passing in our configurations.
    //By doing this, if we want to change anything, it can be done here and only done once.
    //Calls setCurrent and passes the clicked div class. It's either 'prev' or 'next'.
    slider.setCurrent( $(this).attr('class') );

    //After the current div is all figured out, we just animate.
    //Call transition and pass in the speed we want.
    slider.transition( 1000 );
});

Hopefully this all made sense to you. If you're a beginner in JS, this might be a little over your head, but that's perfectly ok! Try reading as many articles as you can find on the subjects here and you'll catch on soon.
Article explaining modulus: http://mathforum.org/library/drmath/view/54363.html


You don't have to use a SemaphoreSlim because a Task is not equivalent to a Thread. It is a more abstract kind of "working item" that will be spreaded to real threads by the TPL. If you start 1000 tasks it does not mean that you create 1000 threads. When starting a task like you did (without option TaskCreationOptions.LongRunning), it will be executed on threads from the TreadPool. Therfore, the Threadpool is managing the number of threads for you and you can just start 17.901 tasks at once.

What is await Task.Delay(1) for?

If there is no reason for it, it just produces unnecessary overhead

var source =  Task.Run( () => this.GetSource(itemUrl) );

You don't need to wrap the returning taks in a new task. The following has less overhead and is functional equivalent:

var source =  this.GetSource(itemUrl);

Move the code from the finally block to the call of GetSourceAsync. There is no need to attach it via ContinueWith in the finally block.

All the points above applied yields to something like:

async Task FetchItemsDataAsync()
{
    var itemsTask = new List<Task<string>>();
    var itemParser = new ItemSourceParser();

    while (this.queue.TryDequeue(out itemUrl))
    {
        var task = Task.Run(async() =>
        {
            var result = await this.GetSourceAsync(itemUrl);
            itemParser.InitializeNewItem(result);
            itemParser.TryToParse();
            Console.WriteLine(itemParser.data["Id"]);
            this.database.InsertItem(itemParser.data);
            itemParser.RefreshData();
        }
        itemsTask.Add(task);
    }

    return Task.WhenAll(itemsTask);
}


Project Euler #2 with a fibSequence and result

Welcome to coding! You've put together a solution that works, but as you get more experienced in both programming, and Project Euler you will discover that there's almost always a better way.... (tm)

On the programming side, you need to realize that you don't need to remember previously computed values in the Fibonacci sequence (no need for the array), and in the Project Euler space, you need to realize that every 3rd value is even. Another project euler optimization is that the sequence can be thought to start from 0, 1, ...., not from 1, 2, ..... If you start at 0, 1, ... you get the sequence 0, 1, 1, 2, 3, 5, 8, ..... (this helps because the first value 0 can be treated as being even....)

Finally, it is almost always a good idea to have a single function that represents the task at hand. You have created a global variable result to store your computation, but really that should be encapsulated in a function of its own. This makes the logic obvious, and also reusable.

Putting these two aspects together, it becomes really a case of simplifying the process down to:

function evenFibSum(limit) {
  let current = 0;
  let next = 1;
  let sum = 0;
  while (current < limit) {
    // add in our current even value (started at 0)
    sum += current;
    // advance to the next even fib number
    // we already have next, so use tmp for the value after next
    const tmp = current + next;
    // the new current is the sum of the previous 2 values
    current = next + tmp;
    // the new next is the new current plus the previous value.
    next = tmp + current;
  }
  return sum;
}

With the above code, you can easily have:

console.log(evenFibSum(4e+6));

Note how with the above code, there's no global values, there's no slow array (adding new members to the array is time consuming and takes space), and also note that the function is reusable with multiple different input values.


Classifying files in a directory by file extension

Each MAP["resolved"] has to perform a hash on "resolved", and then check up the value in the dictionary's internal structure.
This is more costly then looking up a single variable.

Just like in the first, you can assign a local variable, resolved, but you can assign to the dictionary at the same time:

resolved = MAP["resolved"] = []

If you only mutate resolved, then you mutate MAP["resolved"] too. So you can't overwrite resolved with resolved = ['new list'], for example.
Which can get you:

MAP["resolved"] = resolved = []
MAP["rejected"] = rejected = []
for file in files_within("./_input/"):
    file = File(file)
    if file.extension.lower() == "gdb":
        resolved.append(file)
    else:
        rejected.append(file)

I am also unsure on what your functions are, I don't remember them being in the standard library, and so I won't suggest any changes to them.


Production code to be good for unit testing

You're off to a bad start.  You don't have a definition of what your getKeywords() method is supposed to do, which means you can't even begin to test it.  On top of that, it seems to be named backwards - getKeywords() calls addKeyword().


Pattern finding function for years between 1998 and 2017 with several test cases

You're asking for elegance and conciseness. Elegance doesn't always mean short/hackish, and neither does conciseness. You should never sacrifice readability for brevity unless you're codegolfing. As per your comment, just because you can read it doesn't mean the next maintainer or developer can. Someone (maybe you) revisiting this in 5 years should know what the code does without having to pick through it. Let's start by breaking apart the code into its components.

function parseRange2(string) {
  var expr = string.split(',').map(range => range.includes('-') ? range.split('-').map(num => +num) : +range)
  expr = expr.filter(set => Array.isArray(set) ? set[0] <= set[1] : set > 1998 && set <= new Date().getFullYear())
  expr = expr.reduceRight((arr, val) =>
      arr.concat(Array.isArray(val) ? Array(val[1] - val[0] + 1).fill().map((_, num) => val[0] + num) : val), [])
  return [...new Set(expr)].sort()
}

This looks a little more readable. However, someone reading this for a production codebase would have to actually figure out what each expression did. Let's rename some variables and make this easier to digest.

function parseRange2(string) {
  // This expression is still kind of pushing it in terms of readability.
  // Split string in ranges and values
  var ranges = string.split(',').map(range => range.includes('-') ? range.split('-').map(num => +num) : +range)
  // Remove invalid ranges
  var validRanges = ranges.filter(set => Array.isArray(set) ? set[0] <= set[1] : set > 1998 && set <= new Date().getFullYear())
  // Expand range arrays
  var expandedRanges = validRanges.reduceRight((arr, val) =>
      arr.concat(Array.isArray(val) ? Array(val[1] - val[0] + 1).fill().map((_, num) => val[0] + num) : val), [])
  // Return sorted and unique years
  return [...new Set(expandedRanges)].sort()
}

Now let's refactor some of this stuff into helper functions.

const getYearRange = (start, end) => {
  return Array(end - start + 1).fill().map((_, num) => start + num)
}

const isValidEntry = entry => {
  return Array.isArray(entry) ? entry[0] <= entry[1] : entry > 1998 && entry <= new Date().getFullYear()
}

const parseRange2 = string => {
  // This expression is still kind of pushing it in terms of readability.
  // Split string in ranges and values
  var ranges = string.split(',').map(range => range.includes('-') ? range.split('-').map(num => +num) : +range)
  // Remove invalid ranges
  var validRanges = ranges.filter(isValidEntry)
  // Expand range arrays
  var expandedRanges = validRanges.reduceRight((arr, val) =>
      arr.concat(Array.isArray(val) ? getYearRange(val[0], val[1]) : val), [])
  // Return sorted and unique years
  return [...new Set(expandedRanges)].sort()
}

You get the point. You should refactor further to make the code easier to maintain and develop.

Now on the other hand, if you're looking to use every JavaScript hack in the book to golf your code, you could use reduce() instead of reduceRight().

For -2 characters, you could use the following to generate your date range:

[...Array(val[1] - val[0] + 1)].map((_, num) => val[0] + num)

as opposed to:

Array(val[1] - val[0] + 1).fill().map((_, num) => val[0] + num)

You can use the truthiness of arr[0] instead of Array.isArray(arr) to check if an object is an array, which yields the following code:

function parseRange2(string) {
  return [...new Set(string.split(',').map(range => range.includes('-') ? range.split('-').map(num => +num) : +range)
    .filter(set => set[0] ? set[0] <= set[1] : set > 1998 && set <= new Date().getFullYear()).reduce((arr, val) =>
      arr.concat(val[0] ? [...Array(val[1] - val[0] + 1)].map((_, num) => val[0] + num) : val), []))].sort();
}

Addendum: Have you tried '1-10, 1999, 2002-2005, 2002-2005, 2002 - 2005, 2010' as a test case?

Result: [ 1, 10, 1999, 2, 2002, 2003, 2004, 2005, 2010, 3, 4, 5, 6, 7, 8, 9 ]


Your method of generating primes is horribly slow. Running your code takes on the order of 5 minutes on my machine.

Consider as an alternative a prime sieve, even a simple one like the Sieve of Eratosthenes will do (you don't need to go full Atkinson on it):

def prime_sieve(limit):
    a = [True] * limit
    a[0] = a[1] = False

    for i, isprime in enumerate(a):
        if isprime:
            yield i
            for n in xrange(i * i, limit, i):
                a[n] = False

if __name__ == "__main__":
    prod = 1
    for p in prime_sieve(240000):
        prod *= (1 - 1.0 / p)
        print prod
    primes_less_than = p - 1
    amta = 1 - prod

    print "The convergence:", primes_less_than
    print "All the way up to the number:", amta
    print "The amount of active inhibitors are:", prod * primes_less_than

This runs in less than a second.

Accuracy

In your question you said you want to calculate $$n \cdot \left(1-\left(\prod_{i=1}^n(1-p_i)\right)\right)$$ But in your code you implemented $$n \cdot \left(1-\left(\prod_{i=1}^n(1-1/p_i)\right)\right)$$.

You do amta = 1 -old and then later (1 - amta) * primeslessthan. Here you are needlessly loosing precision, because 1 - (1 - x) != x due to floating point precision. Better use old directly in the output.

Review:
Python has an official style-guide, which programmers are encouraged to follow, PEP8.

Your code violates it in the following points:

Always put the expression after an if in a new line
Use spaces around operators
Use lower_case names for variables and functions
old is a bad name for a variable, amta even worse

In addition, the following are discouraged for iterating in python:

l = [1, 2, 3, ...]

for i in range(len(l)):
    print l[i]

i = 0
while True:
    if i > len(l) - 1:
        break
    print l[i]
    i += 1

Just use this simple syntax:

for x in l:
    print x

Note that the if does not need any parenthesis.

Finally, the print statement can take multiple expressions, separated by commas. Alternatively, you can use str.format:

print "The convergence: {}".format(primeslessthan)
print "All the way up to the number: {}".format(amta)
print "The amount of active inhibitors are: {}".format((1 - amta) * primeslessthan)


First of, for someone learning jQuery and JavaScript, you've done a great job of avoiding the pitfalls of most new developers to JavaScript;

You're not passing strings to setTimeout, which a lot of people do.
You've got a good grasp on closures (no matter how long they took you to learn :)).
You're using strict equals (===) rather than equals.

... so, if you want me to be really, really picky;

I don't see much point in adding your code to the jQuery namespace. It would work just as well to be added to your own namespace. A lot of people fall into the habit of defining everything on $, and are scared of declaring your own namespace; don;t be:

var ME = {};

ME.notify = function (title, msg, duration) {
    return new notification(title, msg, duration);
};

It's a code convention to use a capital letter for constructors (e.g. functions you need to call new on); change function notification to function Notification.
You could make use of prototypical inheritance. As it stands, you're defining and adding a hide function on every instance of a notification you create. Obviously this has a negligible memory impact. Instead, use prototypical inheritance, and declare the function once;

function Notification (blah, blah, blah) {
   // blah blah blah
}

Notification.prototype.hide = function () {
    var self = this;

    this.element.fadeOut(1000, function () {
        self.element.remove();
    });
}

... you'd then have to change your double click handler to use the anonymous function approach I recommended in my answer, as this will no longer be the correct this.
You've got a potential XSS exploit. For example, given the message:

This will be injected, and evaluated in your page. You can fix this by setting the h3 and p using text() explicitly;

this.element = $('

(double click to hide)

');

this.element.find('h3').text(title);
this.element.find('span.text').text(message);

... but again, I want to re-iterate that I'm being very, very picky. What you've got is well written, functioning JavaScript.


Just executing the code, I'd receive 4 different inputs like this:

DB user password:
DB user password again:
DB user password:
DB user password again:

which would make me think that some thing went wrong in the first time, and I'd input the same password again. You are not making it obvious for the user to input root password first.

echo "Enter root user credentials"
read -sp "root user password:" dbrootp_1       && echo
read -sp "root user password again:" dbrootp_2 && echo
echo "Enter new user credentials"
read -sp "new user password:" dbuserp_1       && echo
read -sp "new user password again:" dbuserp_2 && echo

makes it slightly better.

if [ "$dbrootp_1" != "$dbrootp_2" ]; then echo "Values unmatched" && exit 1 fi
if [ "$dbuserp_1" != "$dbuserp_2" ]; then echo "Values unmatched" && exit 1 fi

You may wish to convey exactly which set of password was mismatched. It is more a UX debate though. You might not want to do that as it might cause some security vulnerability! However, look at

function error_quit() {
    local EXITCODE=$1
    local MESSAGE="$2"
    >&2 echo $MESSAGE
    exit $EXITCODE
}

[[ "$dbrootp_1" != "$dbrootp_2" ]] && { error_quit 1 "Values unmatched" }
[[ "$dbuserp_1" != "$dbuserp_2" ]] && { error_quit 1 "Values unmatched" }

Splitting into a function gives you an added benefit so that in future you might expand the script, and use the same minimal exit setup instead of copying it everywhere.

The >&2 directs the error to stderr stream.


Since (a < 0 and b > 0) or (a > 0 and b < 0) can be summarized as a*b < 0, moreover * and < work on vectors, we get the one-liner:
plt.scatter(X[0], X[1], c=X[0]*X[1] < 0)


Grab Facebook Graph share count and abbreviate it

My first remark is that you're explicitely requiring jQuery for your code to execute but only use it for jQuery.getJSON(), while it may be used elsewhere.

So instead of:

        } else {
        var c = document.getElementsByClassName('box-counter');
        numb = c.length;
        for (var i = 0; i < numb; i++) {
            var tempURL = c[i].parentNode.attributes['data-url'].nodeValue;
            jQuery.getJSON('http://graph.facebook.com/'+tempURL,function(data) {
                theShares.push(data.shares);
                insertDuring();
            });
        }
    }

you may simply write:

        } else {
        jQuery('.box-counter').each( function(i) {
            jQuery.getJSON(
                'http://graph.facebook.com/' + this.parent().data('url'),
                function(data) {
                  theShares.push(data.shares);
                  insertDuring();
                }
            );
        }
    }

You may also replace this:

function insertDuring(){
    if(numb == theShares.length){
        var c = document.getElementsByClassName('box-counter');
        for (var i = 0; i < numb; i++) {
            // your internal code here...
        }
    }
}

by this simpler code:

function insertDuring(){
    jQuery('.box-counter').each( function(i) {
        // your internal code here, unchanged...
        this.innerHTML = theNewShares[i];
    }
}

Now regarding your abridgeNumbers() function:

function abridgeNumbers(theString,theLimit,theAbbrev,i,k){
    for (var j = 0; j < theLimit; j++) {
        if(typeof theNewShares[i] === 'undefined'){
            theNewShares[i] = theString.charAt(j);
        } else {
            if(k == true){
                theNewShares[i] = theNewShares[i] +"."+theString.charAt(j);
            } else {
                theNewShares[i] = theNewShares[i] + theString.charAt(j);
            }
        }
    };
    theNewShares[i] = theNewShares[i] + theAbbrev;
}

You can simplify the code using the ternary operator, so improving readability, like this:

function abridgeNumbers(theString, theLimit, theAbbrev, i, k) {
    for (var j = 0; j < theLimit; j++) {
        if(typeof theNewShares[i] === 'undefined') {
            theNewShares[i] = theString.charAt(j);
        } else {
            theNewShares[i] += (k ? "." :"") + theString.charAt(j);
        }
    }
    theNewShares[i] += theAbbrev;
}

(BTW you may notice that the ";" is not needed at the end of the for block)

In a more advanced way you may also increase performance. In the code above, each step executes the test about theNewShares[i], while it is useful only once. So you may deport it before the loop, using a short notation which ensures to define theNewShares[i] as empty string when it is yet undefined.

function abridgeNumbers(theString, theLimit, theAbbrev, i, k) {
    theNewShares[i] |= '';
    for (var j = 0; j < theLimit; j++) {
        theNewShares[i] += (k ? "." :"") + theString.charAt(j);
    }
    theNewShares[i] += theAbbrev;
}

Finally beyond those purely technical aspects you may look at my second answer below about how to enhance the "conversion" strategy to get friendly representation of the numbers.


I think the proposed solution is bad. There is no room for lazy loading. All dependencies need to be defined for this 'registry' class. The registry class thus becomes all knowing. All other classes extend Registry, thus are all knowing as well. If you think that is no problem? then stop reading and continue

Another problem: objects are passed around by reference, vars are copied. Is this desired?

What if the $class needs different parameters set depending on where it is used?

Lets look at the following situation:
Both the database and the mailer need a LoggerInterface. So they have a dependency of 'LoggerInterface'. The database however logs to a file, and the Mailer logs to the database. How do you solve this? Have the Mailer depend on a DatabaseLogger?

So to be able to use your Registry, we can no longer hint for generic interfaces, but we hint for concrete classes.


you need to add some spaces in between operators and format the code properly

all I did here was

added spaces between operators
moved the curly braces to their appropriate locations for Egyptian Style Bracing
set indentation to standard, you had some lines that were indented and they shouldn't have been

public static void main(String[] args) {
    int[] array = randomIntArray(30); //declares the dimensions of the array "randomIntArray"
    System.out.println("Scores:");
    printArray(array); //calls the scoreHist method to print the "array variable
    System.out.println("\n" + "count: ");
    printArray(arrayHist(array)); //calls score hist, to call arrayHist, to count "array"
    System.out.println();
}
public static int randomInt(int low, int high) { //the prng
    double e;
    double x=Math.random();
    e=low+x*(high-low);
    return (int)e;
}
public static int[] randomIntArray(int n) { //generates an array of random numbers based on an upper and lower bound
    int[] a = new int[n];
    for(int i = 0; i < a.length; i++) {
        a[i] = randomInt(-5, 15);
    } //"-5&15 are the lower and upper bounds of the random number array
    return a;
}
public static int inRange(int[] a, int low, int high) { //checks if the numbers of the random number array are in certain constraints.
    int count = 0;
    for(int i = 0; i < a.length; i++) {
        if(a[i] >= low && a[i] <= high) count++;
    }
    return count;
}
public static int[] arrayHist(int[] scores) { //counts how many of each number occurs in "randomIntArray"
    int[] counts=new int[11];
    for(int i=0;i<10;i++) {
        counts[i] = inRange(scores, i, i++);
    }
    return counts;
}
public static void printArray(int[] a) { //prints any array, with only one traversal.
    for(int i = 0; i < a.length; i++) {
        System.out.print(" " + a[i]);
    }
}

I noticed that you are using a For loop, and I think that you should be using more foreach loops.  I am going to use this code as an example

public static int inRange(int[] a, int low, int high) { //checks if the numbers of the random number array are in certain constraints.
    int count = 0;
    for(int i = 0; i < a.length; i++) {
        if(a[i] >= low && a[i] <= high) count++;
    }
    return count;
}

so what you get is now this

public static int inRange(int[] a, int low, int high) {
    int count = 0;
    for(int i : a) {
        if(i >= low && i <= high) count++;
    }
    return count;
}

which is slightly cleaner than the OP.

I also removed the comments on this method, mainly because they were unnecessary. you have a lot of comments in this code some of which are not needed at all, probably all of them.  most of your variables are named appropriately so you don't have a doubt what they stand for.  nothing is too complex here that you would need to explain what is going on.

here are the comments I would get rid of

//declares the dimensions of the array "randomIntArray"
//declares the dimensions of the array "randomIntArray"
//the prng

Here is the only comment that I would keep

//counts how many of each number occurs in "randomIntArray"

on the ArrayHist Method. because the Method name doesn't really tell me that right away.

All Methods should be named in PascalCase, variables in camelCase.


Pass your parameters by const reference to avoid a copy:

std::vector<int> merge2Sorted(std::vector<int> const& left, std::vector<int> const& right)
//                                             ^^^^^^                        ^^^^^^

You are not reservng enough

result.reserve(std::max(left.size(),right.size()));

The result size will eventually be the size of the sum of the two input arrays.

result.reserve(left.size() + right.size());

Your test for left and right can be simplified:

if ( *itLeft < *itRight )
  result.push_back( *itLeft++ );
else
  result.push_back( *itRight++ );
}

// Simplified
// Though I am 50/50 on this one.
result.push_back( ( *itLeft < *itRight ) ? *itLeft++ : *itRight++);

No point in flushing the stream after every print:

std::cout << i << std::endl;

                  ^^^^^^^^^^  prefer '\n' unless you really want to force a flush.

std::cout << i << '\n';


Object Oriented

I wouldn't call your code object oriented. And yes, using static in too many places can be a hint that you are not using OOP correctly.

But your program is so small and specific that this isn't really a bad thing. If you actually have some extension in mind, a different approach might be better, but right now, I would leave it as it is.

But for example, lets say you plan to write a program in the future which prints every odd Fibonacci number, or every Fibonacci number dividable by 3. With your code, this might be harder to do.

If your approach was like this:

public class Fibonacci {
    static void fibonacci(NumberCheck numberCheck) {
        [...]
        // instead of Prime.prime(k); call:
        if (numberCheck.meetsContition(k)) {print(k)}
    }
}

interface NumberCheck {
    boolean meetsContition(int number);
}

public class Prime implements NumberCheck {
    @Override
    boolean meetsContition(int number) {
        // check if number is prime, return true or false
    }
}

public class Odd implements NumberCheck {
    @Override
    boolean meetsContition(int number) {
        // check if number is odd, return true or false
    }
}

It would be easily extendable. But as I said, if you are not planning on extending your code, you don't really need OOP in this case. I wouldn't even create the Fibonacci and Prime classes, they are more confusing than they are helpful, just put the methods in App.

Naming

prime should better be called isPrime, and I would find it easier to read if it then returned true or false (move the printing to fibonacci).

Other

I would pass an argument to fibonacci for up to which number it should run. Just hardcoding 1E17 is bad style.


A couple of things I noticed:

Using a TreeMap, instead of converting a StringBuilder to a char[] and creating the map, is much more efficient.

You don't test for an empty argument list.

Telling the user they have to use .txt in the filename is inaccurate as your code doesn't test for that.

When you're printing multiple values on one line, it is more efficient and easier to maintain to use printf, rather than concatenating strings;

Something like this will work:

public static void main(String[] args) throws IOException {
    if (args.length < 1 || args[0].equals("help")) {
        System.out.println("usage: java Main filename");
        return;
    }
    fileToChars(args[0])
            .forEach((k, v) -> System.out.printf("%1$s: %2$d\n", k, v));
}

private static TreeMap<Character, Integer> fileToChars(String fileName) throws IOException {
    final char EOF = (char) -1;
    File file = new File(fileName);
    TreeMap<Character, Integer> builder = new TreeMap<>();
    try (FileReader reader = new FileReader(file)) {
        Character input;
        while ((input = (char) reader.read()) != EOF) {
            Integer count = builder.getOrDefault(input, 0);
            builder.put(input, ++count);
        }
    } catch (IOException e) {
        throw new IOException("Problem reading file");
    }
    return builder;
}

This gives a sorted output of the mapped Characters.  If an 'as is' output is wanted, change the TreeMap to a HashMap.


Excellent comment in the header.  It's very important to be clear who owns the returned memory and how to release it.  It ought to mention that both newline and \0 are considered as end-of-line characters.
Good realloc() usage - we don't leak when allocation fails.
Some small improvements:

#define EXPAND_RATIO 2

Why do we need a preprocessor macro for this?  I would use a simple static const size_t.

size_t arr_size = sizeof(char);

sizeof (char) is 1 by definition (since sizeof yields the number of char required for its argument).  I wouldn't start with such a small buffer anyway, since almost every line will need several realloc() calls.  Start with something sensible, such as 40 (half the width of a standard terminal).

p_tmp = realloc(line, arr_size);
if (p_tmp == NULL) goto err_cleanup;
line = p_tmp;

Since we know that line is null at this point, we should just use malloc() to be clearer, and eliminate a window where *line is invalid:
char *line = malloc(arr_size);
if (!line) return line;

    if ((i * sizeof(char)) == arr_size) {

We can remove the multiplication by 1 from this:
    if (i == arr_size) {

        if (arr_size == SIZE_MAX) {

Ooh, that's very thorough.  We're unlikely to have managed to allocate that much memory in a single chunk!

            // Assuming SIZE_MAX % sizeof(char) == 0.

Again, any number modulo 1 is zero, so that's a truism, not a mere assumption.

#undef EXPAND_RATIO

Arguably overkill, given that this is the very end of the translation unit anyway.


I'd suggest turning the problem around. A dictionary is really good for looking up the key, but not for finding a key for a specific value.

First, you need to convert your dictionary to a dictionary in reverse:

with open("/home/yan/data.txt") as f:
    kv_dict = json.load(f)

vk_dict = {}
for k, vs in kv_dict.items():
    for v in vs:
        vk_dict.setdefault(v, []).append(k)

with open("/home/yan/data_rev.txt", "w") as f:
    json.dump(vk_dict, f)

Then, in your code, you can just write

with open("/home/yan/data_rev.txt") as f:
    d = json.load(f)

for w in list:
    for k in d.get(w, [])
        print(k)

The advantage: building data_rev.txt only needs to be done when data.txt changes, which is hopefully not that often.


Ising model simulation using metropolis algorithm

I cannot yet comment due to my reputation, so I'll write this as an answer to your comment on Andrew's answer, and delete if someone comments this information or Andrew updates his answer.

Saying that numpy's random is not a good random number generator does not seem right to me.
From numpy's reference :

  By default, Generator uses bits provided by PCG64 which has better statistical properties than the legacy MT19937 used in RandomState.

So to me it seems that :

numpy uses the PCG64 random generator which, according to numpy, has better statistical properties than legacy MT19937
numpy used to use MT19937
you can still chose to use the MT19937 random number generator

from numpy.random import Generator, MT19937
rg = Generator(MT19937(12345))
rg.random()

Maybe there is something I'm missing, and maybe it is in this part of your comment

  It produces 53-bit precision floats and has a period of 2**19937-1

If so, I'd be interested to know how numpy's random would still be flawed for a Monte-Carlo analysis.


Sure this generates a random number from 1 -> 100.

int compNumber = rand() % 100 + 1;

BUT not all the numbers have an even probability. Assuming RAND_MAX is 32768 (a common value). Then the number 1->68 have a slightly higher probability than the number 69->100.

To get an even distribution you need to compensate for this:

int compNumber
do
{
    compNumber = rand();
}
while (compNumber > (RAND_MAX / 100 * 100));
compNumber = compNumber % 100 + 1;

Better yet learn to use the modern random number generator that is built into C++.

// I have not tested this.
// Just copied and pasted from: http://stackoverflow.com/a/19666713/14065
// This is the modern equivalent of srand()
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<int> dist(1, 100);

// Then usage is.
// equivalent of rand().
std::cout << dist(mt) << "\n";

This does not look correct:

    if      (compNumber > yourNumber)
    {}
    else if (compNumber > yourNumber)
    {}

The conditions look the same to me.

This does not look like guessing.

        do
        {
            --compNumber;
        } while (compNumber != yourNumber);

This looks like the computer counting down until it reaches your number.


This is shorter, but not necessarily better or more readable.

$jira = json_decode(trim($jira_value->data), true);

$this->displayName = $jira['user']['displayName'];
$this->issueID = $jira['issue']['id'];
$this->issueKey = $jira['issue']['key'];

foreach ($jira['issue']['fields'] as $key => $val) {
   $key = ucfirst($key);
   $this->{"issueField$key"} = $val;
}


from random import randint
from itertools import groupby
import unittest

def rank_players(playerList, die):

Python convention is to use names like player_list for arguments/local variables

    tree = [playerList]

This isn't really used to hold a tree. Its only ever two levels deep, so its a list of lists. You also shouldn't name variables after datastructures, you should name after the meaning in the code.

    nextGeneration = []

You should move this into the loop. That way you won't have to repeat it later

    keepPlaying = True
    while keepPlaying:
        keepPlaying = False

Its best to try and avoid boolean logic flags. They tend to make code harder to follow. If you can, try to structure code to avoid their use.

        for node in tree:
            if len(node) == 1:
                nextGeneration.append(node)
            else:
                keepPlaying  = True
                rolls = [die.roll() for i in range(len(node))]

I'd have done:

  rolls = [ (die.role, item) for item in node]

This avoids the pointless call to len/range, and also handles the zipping in the next line

                turn = sorted(zip(rolls,node), reverse=True)
                print 'players roll:', turn
                for key, group in groupby(turn, lambda x: x[0]):
                    nextGeneration.append(list(i[1] for i in group))

Joel's recursive solution is much nicer, I think.

        tree = nextGeneration
        nextGeneration = []
    return [item for sublist in tree for item in sublist]

class Die:
    def __init__(self,rolls=[]):

In general, don't assign mutable objects as defaults. Here I don't even see why you would have a default since the object is useless with the default constructor.

        self.i = -1

I'd use index, just to be more explicit

        self.rolls = rolls

    def roll(self):
        self.i = self.i + 1
        return self.rolls[self.i]

But here's how I'd write your function

def rank_players(player_list)
    random.shuffle(player_list)

All you are doing in the end is shuffling the list of players, and python has a function for that. Unless you really want to simulate dice, there isn't a lot of point in doing it.

Another approach, I'm not sure a good one, would be:

class Die(object):
    def __init__(self, player):
        self.player = player
        self.rolls = []

    def __getitem__(self, index):
        # if you don't provide an __iter__
        # python will use __getitem__

        # whenever an attempt is made to access
        # past the end, we just roll a new number
        if index == len(self.rolls):
            roll = random.randrange(6)
            print "Player: %s Rolls a: %d" % (self.player, roll)
            self.rolls.append(roll)
            return roll
        else:
            return self.rolls[index]

    def __cmp__(self, other):
        # the only Die I am equal to is myself
        if self is other:
            return 0

        # look at the rolls in both die to
        # find first one that's different
        for a, b in itertools.izip(self, other):
            if a != b:
                return cmp(a,b)

        assert False

def rank_players(player_list):
    decorated = [(Die(player), player) for player in player_list]
    decorated.sort(reverse = True)
    print [die.rolls for die, player in decorated]
    return [player for die, player in decorated]


Noughts and Crosses winner declaration in a game of variable square board size

About the logic of assessing victory:

After each player's turn there can only be one winner, so no matter how you want to write the functional parts it would be best practice to write a return as soon as a victor is found so that you don't do any surplus processing.

The sample $state data:

You have provided a 4x4 grid, with only one player's marks on it -- which is not realistic.
You use - to identify unmarked cells -- I think blanks would be simpler/clearer.
Player X has a diagonal sequence of 4 marks, even though victory (by your rules) is attained by 3 consecutive marks on a 4x4 grid.

Some missing diagonal checks:

$diUp and $diDn have $count values of 1.  This is accurate on 3x3 grids only.

Because $lengthToWin is sqrt(count($state))-1, all grids larger than 3x3 will have 4 winning diagonal sequences in each orientation (running down-to-the-right & down-to-the-left).

Considering a 4x4 grid, the winning sequences from upper-left to lower-right are:

[ 0 , 5 , 10 ]
[ 1 , 6 , 11 ]
[ 4 , 9 , 14 ]
[ 5 , 10 , 15]

The first and last sequences share the internal cells with indexes of 5 & 10.

Here is a visual:

The same logic is applied to the sequences that start from the upper-right corner.

To crystallize... a 3x3 grid will have a total of 2 diagonal sequences, all other grids will have a total of 8 diagonal sequences.  The diagonal sequences obey a simple pattern, so you will have no trouble in generating the correct path for your function.

My tinkerings:

I experimented a little with what I understood of your concepts and tried to employ array functions rather than for loops (though they are sometimes slower, I think they are better descriptors of action).  It is not a very tidy snippet (consider it a "napkin" draft), I didn't bother refining it because I am not 100% sure of your usage nor what is the best way to display the result.

function hasWon(array $vals,$mark){
    return empty(array_diff($vals,[$mark])); // retain opponent's mark and blanks, if empty = victory / true
}

function findFirstWinningSequence(array $state,$width,$mark){
    $lengthToWin=($width>3?$width-1:$width);
    // process horizontal and vertical sequences:
    $chunks=array_chunk($state,$width);
    foreach($chunks as $i=>$chunk){
        // full-length/width checks:
        if(hasWon(array_slice($chunk,0,$lengthToWin),$mark)){ // scan rows from left
            return "$mark wins via row ".++$i." from left";
        }
        $column=array_column($chunks,$i);  // cache column elements
        if(hasWon(array_slice($column,0,$lengthToWin),$mark)){ // scan cols from top
            return "$mark wins via column ".++$i." from top";
        }
        // length/width-1 checks
        if($width>3 && hasWon(array_slice($chunk,-$lengthToWin),$mark)){ // scan rows from right, if needed
            return "$mark wins via row ".++$i." from right";
        }
        if($width>3 && hasWon(array_slice($column,-$lengthToWin),$mark)){ // scan cols from bottom, if needed
            return "$mark wins via column ".++$i." from bottom";
        }
    }
    // process UpperLeft-to-LowerRight diagonal sequences:
    $starts=[0];  // index of first element in set
    if($width>3){
        $starts+=[1,$width,$width+1];
    }
    $increment=$width+1;  // the increment between each cell in sequence
    foreach($starts as $start){
        $keys=array_fill_keys(range($start,$start+$increment*($lengthToWin-1),$increment),null);
        // if $start=0 & $width=4, $keys=array_fill_keys(range(0,0+5*(3-1)=10,5),null); producing: [0=>null,5=>null,10=>null]
        if(hasWon(array_intersect_key($state,$keys),$mark)){
            return "$mark wins via diagonal from ".++$start." running down and to the right";
        }
    }
    // process UpperRight-to-LowerLeft diagonal sequences:
    $starts=[$width-1];  // index of first element in set
    if($width>3){
        $starts+=[$width-2,2*($width-1),2*($width-1)+1];
    }
    $increment=$width-1;  // the increment between each cell in sequence
    foreach($starts as $start){
        $keys=array_fill_keys(range($start,$start+$increment*($lengthToWin-1),$increment),null);
        // if $start=3 & $width=5, $keys=array_fill_keys(range(4,3+4*(3)=15,4),null); producing: [3=>null,7=>null,11=>null,15=>null]
        if(hasWon(array_intersect_key($state,$keys),$mark)){
            return "$mark wins via diagonal from ".++$start." running down and to the left";
        }
    }
}
$state=['X','','','','','X','','','','','X','','','','O','O'];
$width=sqrt(sizeof($state));
$mark='X';
echo findFirstWinningSequence($state,$width,$mark);

To conclude, your coding structure seems suitably segmented/clean.  It only requires the logical tunes ups that I mentioned before my snippet.


Posting data via fetch and handling network errors

I personally think that You can easily handle part of the error handling logic in the catch block however at the moment You are listening for the specific response status do specify what went wrong during the API connection process.
MDN says:

You can use a catch block to handle all exceptions that may be generated in the try block.

try/catch works in a way that if anything fails on the try block, then the rest of the code (in the try block) is ignored and the script execution goes to the catch block. If something goes wrong then the error object is created and passed to the catch block as a parameter .catch(err). From this object You might be able to handle part of the error handling logic. Take a look at the below links:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
https://javascript.info/try-catch
Moreover:

data variable can be a const
Instead of writing .style.display = "none"; use YourElement.classList.add('YourNewSexyClass') and use CSS for styling :)
innerHTML is not a good practice. Take a look here -> https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations
url variable should a const
data variable should be a const

let data = {
    "Username": emailAddress,
    "Password": Password,
  }

can be changed like so (get rid of capital letters here)
let data = {
    username: emailAddress,
    password: password
  }

so that You can change it to
let data = {
    username: emailAddress,
    password
  }


It looks OK, but I would just return the promise from the api module, and handle the errors, success and so on in the place where redux lives.. namely in reportPositionPeriodically

This way your API-module will be smaller and more reusable, for instance:

  I find redux very hard and I'm having a hard time finding out how to do things properly.

you could replace it later, but the api methods would still work ;)
If you do so, you also have a better overview of your state and whats happening to your store