Random password cracker using brute force I created a fun password cracker using literal brute force, searching each character to see if it matches an ASCII character 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. The password is randomly generated and will vary from 100,000 to 250,000 characters long. I use a wrapper timeit function to time the function and the output is a basic print statement using .format():

import random
import time

password = ""
attempted_password = ""
list_of_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in range(0, random.randint(100000, 250000)):
    password += list_of_chars[random.randint(0, 61)]

def timeit(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print "The function {.__name__} took {:.15f} seconds to finish.".format(func, time.time() - start)
        return result
    return wrapper

@timeit
def solve_password(word):
    global attempted_password
    for character in word:
        for entry in list_of_chars:
            if character == entry:
                attempted_password += character
                continue
    return attempted_password

print "The password: {0:}\nLength of password was: {1:}\nIs correct? : {2:}".format(solve_password(password),
                                                                                len(password),
                                                                                attempted_password == password)

An example output (without the password):

The function solve_password took 3.540999889373779 seconds to finish.
The password: *password is here*
Length of password was: 246416
Is correct? : True

So my questions are:

Am I following coding standards for Python 2 (like PEP8)
Is there anyway to improve performance, readability, etc.
Is there any way to make my code more "Pythonic" (like a native Python coder)?

I'll answer your first question separately. However, since your second and third questions are closely related, I'll give the same answers to both questions.

  Am I following coding standards for Python 2 (like PEP8)

For the most part, your code complies with PEP8,

Spaces between operators
Two newlines between function definitions
Variables are lowercase with underscores as needed
etc...

The only thing I'd suggest is to break some of your longer statements up - such as your print statement at the end of your script - onto separate lines, with each separate line being indented.

However, even if sometimes you choose not to comply with a certain coding standard, make sure you are consistent with your naming conventions. I've seen Python code which is written Java style, but is still easy to read because the author was consistent in their style.

  Is there any way to make my code more "Pythonic" (like a native Python coder)? and Is there anyway to improve performance, readability, etc.

Instead of having the list_of_chars variable, make use of the string module which already defines all alphanumeric characters:

>>> import string
>>> string.digits + string.ascii_letters
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>

Don't use global variables. There is rarely ever a good reason to use them. Instead of making attempted_password global, define it local to the solve_password() function. This makes much clearer where attempted_password is used.
Inside of your first for-loop, you never use the variable letter. Instead, simply use the variable _ which conveys to the reader that your only using this loop for code repetition:

for _ in range(0, random.randint(100000, 250000)):
    password += list_of_chars[random.randint(0, 61)]

The builtin range() function will already start from zero if no other start value is specified. So there is no need to explicitly do it yourself:

range(random.randint(100000, 250000)) # no need for setting 0


Implementing numerical integration in Python I have this Python code that implements a rectangular numerical integration. It evaluates the (K-1)-dimensional integral for arbitrary integer \$K \geq 1\$

$$\int_{u_K = 0}^{\gamma}\int_{u_{K-1} = 0}^{\gamma-u_K}\cdots\int_{u_2}^{\gamma-u_K-\cdots-u_3}F_U(\gamma-\sum_{k=2}^Ku_k)f_U(u_2)\cdots f_U(u_K)\,du_2\cdots du_K$$

where \$F_U\$ corresponds to the cdf function in the code, and \$f_U\$ to the pdf. I implemented it using recursion as follows:

    #************************** Import necessary libraries******************************************
import numpy as np
import matplotlib.pyplot as plt
import time
#******************************Set the constant scalars and vectors***************************
start_time = time.time()
KU = 3
eta_dB = 3
eta = 10**(eta_dB/10)
ExpanF = 50

tdB = np.arange(-5,11,4)
tVec = 10**(tdB/10)
thVec = (tVec/eta)*(ExpanF-eta*(KU-1))

N = 10000 # For simulation

du = 0.01

#******************************Define functions to be used***************************************
#Define the CDF of U
def CDF(u):
      return 1-1/(u+1)

#Define the PDF of U
def pdf(u):
     return 1/((1+u))**2

def FK(h, k):
    #print(f'h is {h}, and k is {k}')
    if k == 1:
        res = CDF(h)
    else:
        #n_iter = int(h/du)
        res =  0
        u = 0
        while u < h:
            res += FK(h-u, k-1)*pdf(u)*du
            u += du
    return res

#*******************Find the numerical and simulation values of the integral******************
ResultNum = []
ResultSim = []

if (ExpanF-eta*(KU-1)) > 0:
    for t in thVec:
    # Numerical
        ResultNum.append(1-FK(t, KU))
    # Simulation
        count = 0
        for n in range(0, N):
            if np.sum(np.random.exponential(1, (1, KU))/np.random.exponential(1, (1, KU))) <= t:
                count += 1
        ResultSim.append(1-count/N)

The parameter du is the resolution of the numerical integral, and the smaller, the more accurate the numerical approximation is. However, decreasing du comes at the expense of more computational time using the above code. For example I tried to run the above code on my machine Intel i5 @2.5 GH with 6 GB of RAM for du=0.0001, and it took 15 hours and didn't finish, at which case I had to abort it.

Is there anyway the above code can be optimized to run significantly faster? I tried C++, and I got a 30x speed factor using the same code and algorithm, but I was wondering if I can get a similar or better speed up factor in Python.

I have this Python code that implements a rectangular numerical integration.

In what sense "rectangular"? Or is that as opposed to contour integration?

  It evaluates the (K-1)-dimensional integral for arbitrary integer \$K \geq 1\$

  $$\int_{u_K = 0}^{\gamma}\int_{u_{K-1} = 0}^{\gamma-u_K}\cdots\int_{u_2}^{\gamma-u_K-\cdots-u_3}F_U(\gamma-\sum_{k=2}^Ku_k)f_U(u_2)\cdots f_U(u_K)\,du_2\cdots du_K$$

  where \$F_U\$ corresponds to the cdf function in the code, and \$f_U\$
  to the pdf.

It would probably help to rewrite it in fully symmetric form: $$\underset{\substack{u_i \ge 0 \\ u_1 + \cdots + u_K \le \gamma}}{\int \cdots \int} f_U(u_1)\cdots f_U(u_K) \textrm{d}u_1 \cdots \textrm{d}u_K$$

Then you can exploit the symmetry to divide the polytope of interest into equivalent chunks and only integrate each chunk once.

  I implemented it using recursion as follows:

    #************************** Import necessary libraries******************************************
import numpy as np
import matplotlib.pyplot as plt
import time
#******************************Set the constant scalars and vectors***************************
start_time = time.time()

So far I understand.

KU = 3
eta_dB = 3
eta = 10**(eta_dB/10)
ExpanF = 50

tdB = np.arange(-5,11,4)
tVec = 10**(tdB/10)
thVec = (tVec/eta)*(ExpanF-eta*(KU-1))

What do any of those mean? "constant scalars and vectors" is not an adequate description.

N = 10000 # For simulation

du = 0.01

#******************************Define functions to be used***************************************
#Define the CDF of U
def CDF(u):
      return 1-1/(u+1)

#Define the PDF of U
def pdf(u):
     return 1/((1+u))**2

If \$f_U\$ is that simple, it might make more sense to tackle it with symbolic integration rather than quadrature.

def FK(h, k):
    #print(f'h is {h}, and k is {k}')
    if k == 1:
        res = CDF(h)
    else:
        #n_iter = int(h/du)
        res =  0
        u = 0
        while u < h:
            res += FK(h-u, k-1)*pdf(u)*du
            u += du
    return res

This could use some comments. It seems to be first order quadrature. If you use a higher order, maybe a larger step size will give you equally accurate results much faster.

#*******************Find the numerical and simulation values of the integral******************
ResultNum = []
ResultSim = []

if (ExpanF-eta*(KU-1)) > 0:
    for t in thVec:
    # Numerical
        ResultNum.append(1-FK(t, KU))
    # Simulation
        count = 0
        for n in range(0, N):
            if np.sum(np.random.exponential(1, (1, KU))/np.random.exponential(1, (1, KU))) <= t:
                count += 1
        ResultSim.append(1-count/N)

I'm missing a lot of context here.


(Leetcode) Minesweeper game This is a Leetcode problem -

  Let's play the Minesweeper game
  (Wikipedia,
  online game)!

  You are given a 2D char matrix representing the game board. 'M'
  represents an unrevealed mine, 'E' represents an
  unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4
  diagonals) mines, digit (1 to 8) represents how many mines are
  adjacent to this revealed square, and finally 'X' represents a
  revealed mine.

  Now given the next click position (row and column indices) among all
  the unrevealed squares (M or E), return the board after
  revealing this position according to the following rules -

  If a mine (M) is revealed, then the game is over - change it to 'X'.
  If an empty square (E) with no adjacent mines is revealed, then change it to a revealed blank (B) and all of its adjacent
  unrevealed squares should be revealed recursively.
  If an empty square (E) with at least one adjacent mine is revealed, then change it to a digit (1 to 8) representing the
  number of adjacent mines.
  Return the board when no more squares will be revealed.

  Example 1 -

Input:

[['E', 'E', 'E', 'E', 'E'],
 ['E', 'E', 'M', 'E', 'E'],
 ['E', 'E', 'E', 'E', 'E'],
 ['E', 'E', 'E', 'E', 'E']]

Click : [3,0]

Output:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'M', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

  Explanation -

  Example 2 -

Input:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'M', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

Click : [1,2]

Output:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'X', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

  Explanation -

  Note -

  The range of the input matrix's height and width is [1,50].
  The click position will only be an unrevealed square (M or E), which also means the input board contains at least one clickable
  square.
  The input board won't be a stage when the game is over (some mines have been revealed).
  For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed
  mines when the game is over, consider any cases that you will win the
  game or flag any squares.

Here is my solution to this challenge -

class Solution:

    directions = [(-1, 0), (-1, -1), (-1, 1), (0,-1), (0, 1), (1, -1), (1, 0), (1, 1)]

    def updateBoard(self, board, click):
        """
        :type board: List[List[str]]
        :type click: List[int]
        :rtype: List[List[str]]
        """
        return self.dfs(board, click)

    def dfs(self, board, click):
        stack = [(click[0], click[1])]
        m, n = len(board), len(board[0])
        while stack:
            r, c = stack.pop() # last inserted element

            if board[r][c] == 'M':
                board[r][c] = 'X'
                break

            # check for adjacent mines
            mines = 0
            for i, j in self.directions:
                dr = r + i
                dc = c + j
                if 0 <= dr < m and 0 <= dc < n and board[dr][dc] == 'M':
                    mines += 1
            board[r][c] = str(mines) if mines else 'B'

            # add neighbors
            for i, j in self.directions:
                dr = r + i
                dc = c + j
                if 0 <= dr < m and 0 <= dc < n and board[r][c] == 'B' and board[dr][dc] == 'E':
                    stack.append((dr, dc))

        return board

Here is my Leetcode result (54 test cases) -

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.

An M field is never pushed. It may only happen as a result of an unfortunate click. Testing for board[r][c] == 'M' in the loop is a waste of time. Test it once, if board[click[0]][click[1]] == 'M', before the loop.
Similarly, you should not bother with neighbors if the field is not blank. A test for board[r][c] == 'B' happens too late. As implemented, for other fields code still compute neighbors - and does nothing with them.
The tests for 0 <= dr < m and 0 <= dc < n may also cause performance issues, and do not look Pythonic. Ask forgiveness not permission, e.g.

    try:
        if board[dr][dc] == 'M':
            mines += 1
    except IndexError:
        pass

Quite a few fields are pushed and inspected multiple times. I am not sure wether it is a bottleneck; however the right-hand and scanline methods of flood fill algorithm do worth investigation.


PHP get minDateTime from array I've written a function to get the smallest date from an date[ ] and check for null.
If null == infinity

    /**
     * @param DateTimeInterface|null ...$dates
     * @return DateTime|null
     */
    public static function minDateTime(?DateTimeInterface ...$dates)
    {
        $dateList = [];
        $dates = array_filter($dates);
        if (empty($dates)) {
            // all values where null
            return null;
        }

        foreach ($dates as $date) {
            $dateList[] = $date->getTimestamp();
        }

        return (new DateTime())->setTimeStamp(min($dateList));
    }

Its working but could this be written smaller or with more comments, so that external coworkers can read this?

Things to be aware of:

array_filter() does a full loop of the array.
foreach(), of course, does a full loop of the array.
min() does a full loop of the array.
empty() does a couple of things: it checks if a variable is not set AND if it is "falsey".  Because the $dates variable will be unconditionally set, there is no need to check this -- just use !$dates if you want to check if the array is empty.
array_filter(), like empty() is a "greedy" seeker of "falsey" values.  I assume that this is a non-issue for your task because there should be no 0 or false (etc.) values -- only datetime values or nulls.
datetime objects can be compared.
you don't need to make iterated calls to getTimestamp(), nor do you need to declare a new datetime object and set its time manually -- just use the one you found.

I suppose I'll recommend that you loop the data just one time.  No array generation, no function calls, very direct and concise.  Your custom method name is descriptive.  Go with this:

Code: (Demo)

public static function minDateTime(?DateTimeInterface ...$dates)
{
    $minDate = null;
    foreach ($dates as $date) {
        if ($date && (!$minDate || $date < $minDate)) {
            $minDate = $date;
        }
    }
    return $minDate;
}


Refactor code for API wrapper I am looking for ways to improve my API wrapper for Pocket. So far, my code is quite compact and nice (I think), but I feel like there must be a better way to do this.

This is the part where I think a lot of code redundancy due to different parameters that need to be serialized to Json and later send to server.

        public async Task<List<ItemRetrieved>> GetAllUnreadAsync(int sinceInUnixTime = 0)
        {
            var requestUrl = MakeRequestUri("v3/get");

            var request = new HttpRequest(HttpMethod.Post, requestUrl);

            request.AddBody(new
                {
                    consumer_key = _consumerKey,
                    access_token = _accessToken,
                    state = "unread",
                    sort = "newest",
                    since = sinceInUnixTime
                });

            var response = await SendAsync<ItemRetrievedWrapper>(request);

            return response.List.Values.ToList();
        }

    public async Task<List<ItemRetrieved>> GetFavoriteAsync(int sinceInUnixTime = 0)
    {
        var requestUrl = MakeRequestUri("v3/get");

        var request = new HttpRequest(HttpMethod.Post, requestUrl);

        request.AddBody(new
            {
                consumer_key = _consumerKey,
                access_token = _accessToken,
                favorite = 1,
                sort = "newest",
                since = sinceInUnixTime
            });

        var response = await SendAsync<ItemRetrievedWrapper>(request);

        return response.List.Values.ToList();
    }

I have few other methods that look like this as well but the only different is the anonymous object passed inside the AddBody. The anonymous object is the parameters that need to be set. AddBody will serialize the object into Json.

My idea currently is to create a separate class/object for the parameters and use method chaining to build up the parameters before passing it into AddBody.

Maybe looks something like this.

var requestParams = new RequestParams();
requestParams.SortBy("newest").Since(2312321312).IsFavorite(true);
request.AddBody(requestParams);

Are there any other good ways I can refactor my code?

If you need to see the big picture, you can take a look here at my Github https://github.com/shulhi/PocketNet

Thank you.

Well, you should refactor your code so that you don't repeat yourself:

private async Task<List<ItemRetrieved>> GetValuesAsync(object parametersAsAnonymousObject)
{
    var requestUrl = MakeRequestUri("v3/get");

    var request = new HttpRequest(HttpMethod.Post, requestUrl);
    request.AddBody(parametersAsAnonymousObject);

    var response = await SendAsync<ItemRetrievedWrapper>(request);
    return response.List.Values.ToList();
}

public Task<List<ItemRetrieved>> GetAllUnreadAsync(int sinceInUnixTime = 0)
{
    return GetValuesAsync(new
        {
            consumer_key = _consumerKey,
            access_token = _accessToken,
            state = "unread",
            sort = "newest",
            since = sinceInUnixTime
        });
}

public Task<List<ItemRetrieved>> GetFavoriteAsync(int sinceInUnixTime = 0)
{
    return GetValuesAsync(new
        {
            consumer_key = _consumerKey,
            access_token = _accessToken,
            favorite = 1,
            sort = "newest",
            since = sinceInUnixTime
        });
}

This sill repeats consumer_key and access_token, but I think getting rid of that repetition would be too complicated, so it's not worth it (unless you have big number of these methods).


change space to underscore in filename using C I have written my first C program that renames spaces in filenames to underscores. I wonder if there is an easier or more efficient way:

#include <stdio.h>
#include <string.h>

int main( int argc, char *argv[] ) {

    if ( argc != 2 ) {
        printf("Format is: NoSpace <filename>\n");
        return(0);
    }
    else if ( strstr( argv[1], " ") == NULL) {
        printf("No space character in file: %s\n",argv[1]);
        return(0);
    }

    int filename_size = strlen(argv[1]);
    char file_name_old[filename_size], file_name_new[filename_size];

    strcpy(file_name_old, argv[1]);
    strcpy(file_name_new, argv[1]);

    // ASCII 32 = space; ACII 95 = underscore
    for( int pos = 0; pos < filename_size; pos++) {
        if ( file_name_new[pos] == 32)  {
            file_name_new[pos] = 95;
        }
    }

    rename(file_name_old,file_name_new);
    return(0);
}

Thanks!

Although this indeed does something similar to your goal, here are some criticisms / improvements:

There's absolutely no need to take a copy of the original filename.
If you meet an error condition, return 1 (or better EXIT_FAILURE from stdlib.h), so scripts calling your tool get a chance to detect the error.
Use functions; this helps your code to keep structure
Your tool will not work correctly for filenames with paths, so better search from the end and stop replacing when you hit a path separator character.
When iterating through a string, it's often easier to just use pointers instead of array indexing.

I'd suggest something like this:

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

#ifdef _WIN32
#define isPathSep(x) ((x) == '\\' || (x) == '/')
#else
#define isPathSep(x) ((x) == '/')
#endif

char *sanitizeFileName(const char *filename)
{
    size_t namelen = strlen(filename);

    char *sanitized = malloc(namelen + 1);
    if (!sanitized)
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    strcpy(sanitized, filename);

    char *p = sanitized + namelen - 1;
    while (p >= sanitized)
    {
        if (isPathSep(*p)) break;
        if (*p == ' ') *p = '_';
        --p;
    }

    return sanitized;
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s [filename]\n", argv[0]);
        return EXIT_FAILURE;
    }

    char *safename = sanitizeFileName(argv[1]);

    // instead of rename(), for demonstration:
    printf("%s -> %s\n", argv[1], safename);

    free(safename);

    return EXIT_SUCCESS;
}


Sequential execution I made a class that I think satisfies the conditions:

Actions can be added to the queue at any time by any number of clients.
Action's executing in the order in which were added.
Only one Action executing at time.

public sealed class SequentialTaskScheduler
{
    private static volatile SequentialTaskScheduler instance = null;

    private static readonly object padlock = new object();

    private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();

    SequentialTaskScheduler()
    {
        var task = Task.Factory.StartNew(ThreadProc);
    }

    public static SequentialTaskScheduler Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new SequentialTaskScheduler();
                    }
                }
            }
            return instance;
        }
    }

    public void AddToQueueForExecution(Action action)
    {
        queue.Enqueue(action);
    }

    private void ThreadProc()
    {
        while (true)
        {
            Action item;
            bool isSuccessfull = false;
            isSuccessfull = queue.TryDequeue(out item);
            if (isSuccessfull)
            {
                item();
            }
            System.Threading.Thread.Sleep(100);
        }
    }
}

I will be grateful for the advice about dangers of such an implementation. And also will be grateful for the advice how to improve it.

Update:

I get feedback on this task from company.

uncertain use of volatile
use threadsafe singleton or singleton
Task.Factory.StartNew take pool from thread but does not return it.
use busy loop with Thread.Sleep is not elegant solution.

How to improve code with those remark's? I think that first two reason are non constructive, but the third and four are constructive. i will be grateful for the advices.

I have few suggestions, and modified the code.

Use Lazy singleton pattern instead of Double check singleton, avoid usage of volatile

private static readonly Lazy<SequentialTaskExecutor> _lazy = new
Lazy<SequentialTaskExecutor>(() => new SequentialTaskExecutor());

Tasks should be cancelled and disposed properly. Since the task we want to run for long time, create a new task using Task.Factory.StartNew with Cancellation tokens and TaskCreationOptions.LongRunning

Task.Factory.StartNew(this.ExecuteTask, _token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

Class should implement IDisposable interface, so created threads can be cancelled properly and items in the queue are cleared

public class SequentialTaskExecutor : IDisposable

protected virtual void Dispose(bool disposing)
{
    try
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // clear the items in queue.
                Action item;
                while (_queue.Count != 0)
                {
                    if (_queue.TryDequeue(out item))
                    {
                    }
                }

                _tokenSource.Cancel();
                _executionTask.Wait();
                _tokenSource.Dispose();
                _executionTask.Dispose();
            }

            disposedValue = true;
        }
    }
    catch
    {
    }
    finally
    {
        _tokenSource = null;
        _executionTask = null;
    }
}

Use Smart waiting instead of Busy waiting in tasks.

private void ExecuteTask()
{
    bool isTaskCompleted = true;
    while (true)
    {
        Action item;
        if (_token.IsCancellationRequested)
        {
            while (_queue.Count != 0)
            {
                if (_queue.TryDequeue(out item))
                {
                }
            }

            break;
        }

        if (isTaskCompleted)
        {
            isTaskCompleted = false;
            var innerTask = Task.Factory.StartNew(() =>
            {
                if(_token.IsCancellationRequested)
                {
                    return;
                }
                if(_queue.TryDequeue(out item))
                {
                    item();
                }

            }, _token).ContinueWith((ants) =>
            {
                if(ants.IsCanceled || ants.IsFaulted)
                {
                    isTaskCompleted = true;
                }
                else if(ants.IsCompleted)
                {
                    isTaskCompleted = true;
                }
                _currentInterval = _minimumInterval;
                System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task execution complted _currentInterval : " + _currentInterval);
            });
        }
        else
        {
            // Raise the interval till maximum value
            if (_currentInterval < _maximumInterval)
            {
                _currentInterval++;
            }

            System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task waiting complted _currentInterval : " + _currentInterval);
            Thread.Sleep(TimeSpan.FromSeconds(_currentInterval));
        }
    }
}

Complete source code is as follows

public class SequentialTaskExecutor : IDisposable
{
    private static readonly Lazy<SequentialTaskExecutor> _lazy = new Lazy<SequentialTaskExecutor>(() => new SequentialTaskExecutor());
    private readonly ConcurrentQueue<Action> _queue = null;
    private CancellationTokenSource _tokenSource = null;
    private CancellationToken _token;
    private int _maximumInterval = 10;
    private int _minimumInterval = 1;
    private int _currentInterval = 0;
    private bool disposedValue = false;
    Task _executionTask = null;

    private SequentialTaskExecutor()
    {
        _queue = new ConcurrentQueue<Action>();
        _tokenSource = new CancellationTokenSource();
        _token = _tokenSource.Token;
        _executionTask = Task.Factory.StartNew(this.ExecuteTask, _token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
    }

    public static SequentialTaskExecutor Instance
    {
        get
        {
           return _lazy.Value;
        }
    }

    public void AddToQueueForExecution(Action action)
    {
        _queue.Enqueue(action);
        System.Diagnostics.Debug.WriteLine("Task added " + _queue.Count);
    }

    private void ExecuteTask()
    {
        bool isTaskCompleted = true;
        while (true)
        {
            Action item;
            if (_token.IsCancellationRequested)
            {
                while (_queue.Count != 0)
                {
                    if (_queue.TryDequeue(out item))
                    {
                    }
                }

                break;
            }

            if (isTaskCompleted)
            {
                isTaskCompleted = false;
                var innerTask = Task.Factory.StartNew(() =>
                {
                    if(_token.IsCancellationRequested)
                    {
                        return;
                    }
                    if(_queue.TryDequeue(out item))
                    {
                        item();
                    }

                }, _token).ContinueWith((ants) =>
                {
                    if(ants.IsCanceled || ants.IsFaulted)
                    {
                        isTaskCompleted = true;
                    }
                    else if(ants.IsCompleted)
                    {
                        isTaskCompleted = true;
                    }
                    _currentInterval = _minimumInterval;
                    System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task execution complted _currentInterval : " + _currentInterval);
                });
            }
            else
            {
                // Raise the interval till maximum value
                if (_currentInterval < _maximumInterval)
                {
                    _currentInterval++;
                }

                System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task waiting complted _currentInterval : " + _currentInterval);
                Thread.Sleep(TimeSpan.FromSeconds(_currentInterval));
            }
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        try
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // clear the items in queue.
                    Action item;
                    while (_queue.Count != 0)
                    {
                        if (_queue.TryDequeue(out item))
                        {
                        }
                    }

                    _tokenSource.Cancel();
                    _executionTask.Wait();
                    _tokenSource.Dispose();
                    _executionTask.Dispose();
                }

                disposedValue = true;
            }
        }
        catch
        {
        }
        finally
        {
            _queue = null;
            _tokenSource = null;
            _executionTask = null;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
 }
}


How can this python regex file finder be improved? I've just spent a good hour or so developing a python script that hunts down and removes .php files depending on the regex expression the situation was a client has got several sites and got hacked recently and as a result a large portion of 8 character random php files have created, so in order to remove them all I made a python script to hunt and find the files whilst avvoiding the files needed also which are 8 characters.
Target:
n1qv0iop.php
e7wo0sb8.php
sdt24g9o.php
9ktrhstu.php
2cvgc7qa.php
nlrgnwzt.php
pyj67osr.php
Script:
import os
import re

rootdir = "/ROOTDIRECTORY"
regex = re.compile('^((((?!absolute|abstract|accounts|activate|activity|advanced|archives|autoload|autoplay|basiccss|bookmark|calendar|captions|category|checkbox|comments|compiled|conntest|controls|counters|courierb|courieri|creative|cronview|database|defaults|disabled|document|dropcaps|elements|embedded|error404|external|facebook|features|fieldset|flamingo|flipcard|freedoms|frontend|getcombo|getnodes|groupped|gzdecode|homepage|icongrid|iconlist|igniteup|importer|includer|launcher|lazyload|licenses|lightbox|location|magazine|mailpoet|manifest|mappings|myticket|optimize|packager|password|phpthumb|platform|pointers|products|progress|promobox|radiotab|redirect|register|renderer|repeater|required|response|revision|richtext|rollback|rollover|security|services|settings|sidebars|sitemaps|switcher|taxonomy|template|testmail|textarea|thankyou|timeline|tracking|upgrader|upgrades|variable|videobox|whatsnew|payments|donation|checkout|readmore|overview|tooltips|purchase|endpoint|firewood|pagepost|jwplayer|analytic|builders|bulkedit|carousel|delivery|featured|feedback|fontello|fontpack|headline|honeypot|messages|metadata|position|registry|sendaway|sections|singular|siblings|subpages|tabgroup|thickbox|turfmail|webfonts|networks|htaccess))[a-z0-9]{8})).php$')

for root, dirs, files in os.walk(rootdir):
  for file in files:
    if regex.match(file):
   print(os.path.join(root,file))
   #os.remove(os.path.join(root,file))

   print "END";

My question is can this be improved? is there a better way to write the regex pattern?just looking for advice :)

I think a regex is overkill here. There comes a point where evaluating all these or'ed exceptions becomes just too slow. I would instead use a simple glob and a blacklist:
from pathlib import Path

IGNORE = {"absolute", "abstract", ...}

root = Path("/ROOTDIRECTORY")
for file in root.glob("**/*.php"):
    if len(file.stem) == 8 and file.stem not in IGNORE:
        print(file)

Note that I used a set for a fast check with in.
You could also use the glob "**/????????.php", as suggested by @RootTwo in the comments, then you wouldn't have to do the length check, although that is quite fast.
Indeed, what you should ideally do is not take my or anyone else's word for it, but measure. Measure how fast your approach is, how fast an optimized regex is, how fast mine is and how fast using a different glob is. Maybe it matters, or maybe all of this is premature optimization and it doesn't actually matter that one takes a millisecond and the other a second (or whatever the actual results are). That depends entirely on your use case.


Script to temporarily drop admin privileges Description

The aim of my project is to allow administrators to drop privileges for reasons of self-control. Currently, it works only on MacOS Sierra but the concept should be extensible to any Unix compatible system.

The sudoers mechanism is the workhorse. By adding a file in sudoers.d/ the administrator user (let's call him my-admin) is given permissions to run the script admin-helper as root.

The admin-helper script when run, toggles my-admin's membership from the admin group. When the my-admin is not in the admin group, the user is only added after the script sleeps for 20 min.

Files

admin-helper

#!/bin/bash

set -e -u
username=$SUDO_USER
delay=$((60*20)) #20 minutes
uGuid=$(dscl . -read /Users/$username/ GeneratedUID | sed -nE 's/GeneratedUID: (.*$)/\1/p')

if groups "$username" | grep -q -w admin; then
    dscl . -delete /Groups/admin GroupMembers "$uGuid"
    echo "Removed '$username' from admin. You may need to logout for changes to take effect."
else
    echo "'$username' is not an admin"
    echo "Sleeping for $delay seconds staring from $(date '+%D %T')"
    sleep "$delay"

    if [[ -z "${1+x}" ]]; then
       echo "Adding '$username' to admin group"
       dscl . -append /Groups/admin GroupMembers "$uGuid"
    else
       echo "Executing command as root"
       $1
    fi
fi

admin.sudoers

  User_Alias DELAYED_ADMINS = my-admin
  Cmnd_Alias ADMIN_HELPERS = /usr/local/bin/admin-helper

  DELAYED_ADMINS ALL=(root) ADMIN_HELPERS

Usage

This is the installation process:

  sudo mkdir -p /private/etc/sudoers.d/
  EDITOR="cp admin.sudoers" sudo visudo -f /private/etc/sudoers.d/admin
  sudo cp admin-helper /usr/local/bin/admin-helper

The subsequent usage is:

sudo admin-helper

or

sudo admin-helper "whoami"

Review

Some of the points I want a review for include:

The way to add/remove user from the admin group. Perhaps there is a better cross-platform way of doing this.
Potential security issues. Possibility of locking oneself out from the admin privilages.
Better/safer way to do implement installation or uninstallation.

EDIT:

The way I use this script is to have my privileges dropped most of the time, and only regain them (by running the script 20min before) when I need to do admin stuff.

Purpose/Example usage

The whole reason behind having the delay before gaining admin privileges is to prevent  my-admin from gaining them at whim. As a concrete example, suppose my-admin wishes to use MacOS parental control settings on himself.  He can do so by dropping admin privileges using admin-helper,  then setting parental controls for my-admin using another administrator account (and then forgo access to the other admin account). Now suppose my-admin wants to disable the parental-controls, he must regain privileges by running admin-helper script again, and only then he can disable parental-controls. For this he has to wait for 20min which is a good thing. Say parental-controls prevented him from viewing Facebook. This means that he can no longer open that Facebook tab on whim while he is still doing important work. He can always decide that, "I will run Facebook after 20min", but that decision too can be changed anytime within 20 minutes by interrupting the admin-helper script while it is sleeping.

An analogy would be that you have a box of candies that only opens 20min after you tell it to. Will you eat the same amount of candies that you would eat if you could open the box instantly?

Usability

The current script works in a dual mode:

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

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

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

Cross-platform way to add/remove users

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

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

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

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

Minor technical improvements

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

This seems to check if $1 empty:

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

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

if [ -z "$1" ]; then

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

cmd=$1


Displaying a list of attributes and differentiate them from attributes already selected attributes is an array with all attributes selected by the user.

attributeList is a Mongo collection declared in [root]/lib and contains all possible attributes.

I'm using two loops in order to match attributes. For those that match, new fields "operator" and "value" are added and will be used in the template.

Do you see a way how to improve these two loops in terms of speed?

var attibutes = attrInfo2.findOne({}, {"fields": {"metric": 1}, reactive: false});
var result = attributeList.find(query).map(function (attr) {
    if(attr.inputType) {
        if (attr.inputType === "int" || attr.inputType === "double") {
            _.map(attibutes.metric, function (m) {
                var operator;
                if (m.attrType === "filter" && attr.field === _.values(m.attrField)[0]) {
                    if (_.isObject(m.attrData)) {
                        operator = _.keys(m.attrData)[0];
                        if (operator !== "in") {
                            attr.operator = operator;
                        }
                        attr.value = _.values(m.attrData)[0];
                    } else {
                        attr.value = m.attrData;
                    }
                }
                return m;
            });
        } else if (attr.inputType === "string"){
            _.map(attibutes.metric, function (m) {
                if (m.attrType === "filter" && attr.field === _.values(m.attrField)[0]) {
                    if (_.isObject(m.attrData)) {
                        attr.value = _.values(m.attrData)[0];
                    } else{
                        attr.value = m.attrData;
                    }
                }
                return m;
            });
        }
    }
    return attr;
});

Generally speaking, I'd avoid relying heavily on function calls if speed is important. Specifically:

_.map(attibutes.metric, function (m)

If attibutes.metric is an array I'd do

var i = attibutes.metric.length;
while(i--) {
/* your code here */
}

or

var i, length = attibutes.metric.length;
for (i = 0; i < length; i++) {
/* your code here */
}

depending on the engine, the while loop will be faster than the for or vice-versa.

if attibutes.metric is an object I'd do

keys = Object.keys(attibutes.metric);
for (var key in keys) {
/* your code here */
}

Any of those constructs is probably faster than calling _.map (you should still profile it, YMMV).

second, i'd invert

if (_.isObject(m.attrData) {

if the alternative is m.attrData is a primitive type, so

if (typeof m.attrData === 'string') { // replace string with whatever primitive
    attr.value = _.values(m.attrData)[0];
} else {
    operator = _.keys(m.attrData)[0];
    if (operator !== "in") {
        attr.operator = operator;
    }
    attr.value = m.attrData;
}


Performing insertion sort in C# This is my code in C# for performing insertion sort:

static int[] performInsertionSort(int[] inputarray)
{
    for (int i = 0; i < inputarray.Length-1; i++)
    {
        int j = i+1;

        while (j>0)
        {
            if (inputarray[j-1] > inputarray[j])
            {
                int temp = inputarray[j-1];
                inputarray[j - 1] = inputarray[j];
                inputarray[j] = temp;

            }
            j--;
        }
    }
    return inputarray;
}

Is there a way to optimize this code? Can I make further changes to it?

Your sorting logic is dependent upon the specific type.

"Separate your data representation from logic." you must take advantage of the generic to reuse the same component to sort any kind of object. In case of class you can specify comparer to sort the values.

Naming convention should be followed. i and j does not make sense and in c# standard method naming convetion should Pascal case , should not start with lowercase.

Rest logic looks good.

public static T[] PerformInsertionSort<T>(T[] inputarray, Comparer<T> comparer=null)
    {
        var equalityComparer = comparer ?? Comparer<T>.Default;
        for (var counter = 0; counter < inputarray.Length - 1; counter++)
        {
            var index = counter + 1;
            while (index > 0)
            {
                if(equalityComparer.Compare(inputarray[index - 1],inputarray[index])>0)
                {
                    var temp = inputarray[index - 1];
                    inputarray[index - 1] = inputarray[index];
                    inputarray[index] = temp;
                }
                index--;
            }
        }
        return inputarray;
    }


Parse the phone balance from the operator site How can I write this code better?

$cookieUrl = 'https://-------------/ps/scc/login.php';
$sessionUrl = 'https://-------------/ps/scc/php/check.php';
$balanceUrl = 'https://-------------/SCWWW/ACCOUNT_INFO';
$vars = "LOGIN={$this->login}&PASSWORD={$this->password}";
$response = $this->_sendPostRequest($cookieUrl, '', null, 1);
preg_match_all("/PHPSESSID.*;/isU",
            $response, $matches, PREG_PATTERN_ORDER);
$phpsessid = $matches[0][0];
$response = $this->_sendPostRequest($sessionUrl, $vars, $phpsessid);
preg_match_all("/<SESSION_ID>.*<\/SESSION_ID>/isU",
        $response, $matches, PREG_PATTERN_ORDER);
$sessionId = strip_tags($matches[0][0]);
$vars = "SESSION_ID={$sessionId}";
$response = $this->_sendPostRequest($balanceUrl, $vars);
preg_match_all("/
.*<\/div>/isU",
        $response, $matches, PREG_PATTERN_ORDER);
if (count($matches[0]) == 0) {
    preg_match_all("/
.*<\/div>/isU",
            $response, $matches, PREG_PATTERN_ORDER);
}
$this->balance = strip_tags($matches[0][0]);
$this->updated = date(Settings_Constants::DATETIME_DATABASE_FORMAT);
$this->save();
$this->balance;

It is not perfect example, but your code might be like this:

function __construct()
{
//...
    $this->cookieUrl = 'https://-------------/ps/scc/login.php';
    $this->sessionUrl = 'https://-------------/ps/scc/php/check.php';
    $this->balanceUrl = 'https://-------------/SCWWW/ACCOUNT_INFO';
//...
}

function loginToService()
{
    $response = $this->_sendPostRequest($this->cookieUrl, '', null, 1);
    preg_match_all("/PHPSESSID.*;/isU",
                $response, $matches, PREG_PATTERN_ORDER);
    $this->phpsessid = $matches[0][0];
    if (!this->phpsessid) {
        throw new Exception ('Could not retrieve PHP session id');
    }
}

function getServiceSessionId()
{
    $vars = array(
        'LOGIN' => $this->login,
        'PASSWORD' => $this->password,
    );
    $response = $this->_sendPostRequest($this->sessionUrl, implode('&', $vars), $this->phpsessid);
    preg_match_all("/<SESSION_ID>.*<\/SESSION_ID>/isU",
            $response, $matches, PREG_PATTERN_ORDER);
    $this->sessionId = strip_tags($matches[0][0]);
    if (!$this->sessionId) {
        throw new Exception ('Could not retrieve Service session id');
    }
}

function getBalanceMessage()
{
    $vars = "SESSION_ID={$sessionId}";
    $response = $this->_sendPostRequest($balanceUrl, $vars);
    preg_match_all("/
.*<\/div>/isU",
            $response, $matches, PREG_PATTERN_ORDER);
    if (count($matches[0]) == 0) {
        preg_match_all("/
.*<\/div>/isU",
                $response, $matches, PREG_PATTERN_ORDER);
    }
    retrun strip_tags($matches[0][0]);
}

/* begin */
try {
    $this->loginToService();
    $this->getServiceSessionId();
} catch Exception $e {
    return $e->getMessage();
}
$this->balance = $this->getBalanceMessage();;
$this->updated = date(Settings_Constants::DATETIME_DATABASE_FORMAT);
$this->save();
$this->balance; //What the hell is this?
/* end */


Simplify JavaScript collision detection with offset I am working on a background project that is a little interactive. Now I am using some collision detection to draw some lines and stuff.

The code I have works great but it is very bulky and hard to read.

if (background.allPixels[i].location.x - drawLineBetweenPixelRange < background.allPixels[j].location.x + background.allPixels[j].width &&
    background.allPixels[i].location.x + background.allPixels[i].width + drawLineBetweenPixelRange > background.allPixels[j].location.x &&
    background.allPixels[i].location.y - drawLineBetweenPixelRange < background.allPixels[j].location.y + background.allPixels[j].height &&
    background.allPixels[i].location.y + background.allPixels[i].height + drawLineBetweenPixelRange > background.allPixels[j].location.y)

It comes down to running this for the x and y coordinates:

var result = (x - a < y + b) && (x + b + a > y)

Can this be simplified?

I was hoping if the check itself could be shortened by taking stuff out that might counter eachother.

Bug #1

Your code does not follow pattern (x - a < y + b) && (x + b + a > y) but (x - a < y + b1) || (x + b2 + a > y) instead. So our refactored formula is moot! obsolete

Bug #2

A collision is detected when any of the guards trigger, not when all.

Proposed Solution

Solving both bugs, we could refactor Nikko Khresna's method:

function detectCollision(source, target, line) {
  return
       source.location.x < target.location.x + target.width + line
    || source.location.x + source.width + line > target.location.x
    || source.location.y < target.location.y + target.height + line
    || source.location.y + source.height + line > target.location.y
  ;
}

and you can call it as follows

const collision = detectCollision(
  background.allPixels[i], background.allPixels[j], drawLineBetweenPixelRange);

Obsolete section because OP made a mistake in the formula: I'll keep it for historical reasons :)

Formula (Obsolete)

The way I see it, we could rewrite your expression:

var result = (x - a < y + b) && (x + b + a > y)

as

var result = (x - a - b < y) && (x + b + a > y)

and further as

var result = (x - (a + b) < y) && (x + (a + b) > y)

now we can substitute (a + b) with offset

var result = (x - offset < y) && (x + offset > y)

which means x and y have to be within offset distance of each other (|x-y| = abs(x-y))

var result = Math.abs(x - y) < offset

Now you can substitute x, y and offset with your variables, and - as suggested in the other answer - use a method that calculates this collision for you.


Project Euler # 7 in C++ I attempted the Project Euler question #7 in C++ ("What is the 10 001st prime number?").

I took into account what I've been told about primes in order to create the most efficient algorithm I could in order to solve this. I would like to know if there is anything else I can do to check even fewer numbers for an even more efficient algorithm.

Also, I'm wondering if creating and using functions would be good practice in this scenario, and how I could go using functions more in coding.

#include <iostream>
#include <vector>

using namespace std;

// What is the 10 001st prime number?
int main()
{
    int countPrimes = 2;
    int checkIfPrime = 6;       // multiples of 6

    // sees if numbers adjacent to 6 are prime
    bool lessOnePrime = true;
    bool plusOnePrime = true;

    vector<int> primeVector;    // for holding primes to check for future primes
    //account for primes 2 and 3 beforehand:
    primeVector.push_back(2);
    primeVector.push_back(3);

    while (countPrimes < 10001)                 // checks until the 10001st prime has been found
    {
        for (int i = 0; primeVector[i] <= sqrt(checkIfPrime + 1); i++)      //checks only prime factors up to the square root
        {
            // checks if numbers adjacent to 6 have prime factors
            // if so, makes their respective booleans false
            if ((checkIfPrime - 1) % primeVector[i] == 0)
            {
                lessOnePrime = false;
            }
            if ((checkIfPrime + 1) % primeVector[i] == 0)
            {
                plusOnePrime = false;
            }
            // if both adjacent numbers to multiples of 6 aren't prime, exits loop
            if (lessOnePrime == false && plusOnePrime == false)
            {
                break;
            }
        }

        if (lessOnePrime)
        {
            primeVector.push_back(checkIfPrime - 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime - 1 << endl;
        }
        if (plusOnePrime)
        {
            primeVector.push_back(checkIfPrime + 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime + 1 << endl;
        }
        lessOnePrime = true;
        plusOnePrime = true;
        checkIfPrime += 6;
    }

    cout << "The " << countPrimes << "st prime number is:\n" << primeVector[countPrimes - 1] << endl;

    return 0;
}   // end main()

I would like to know if there is anything else I can do to check even fewer numbers for an even more efficient algorithm.

The general recommendation is to use a

   sieve for this.  The one that comes to mind is the Sieve of Eratosthenes.

That said, there are some other comments that I can make on the code as it stands.

    int checkIfPrime = 6;       // multiples of 6

Often, your code will read more naturally if you give variables noun names.  This tells what you should do with the variable.  I'd prefer a name like primeCandidate which describes what it is.  Or should be, since 6 isn't actually a number that you want to check.

    int primeCandidate = 7;

It can save calculations if you start with 7 rather than 6.  Rather than saying primeCandidate-1 and primeCandidate+1, you can just say primeCandidate-2 and primeCandidate.  Note that you need the larger number slightly more often.

    bool lessOnePrime = true;
    bool plusOnePrime = true;

Since you don't use these outside the while loop nor across iterations, you should define these inside the loop instead.  Of course, as we'll discuss later, these aren't actually necessary.

    vector<int> primeVector;

This is called Hungarian notation, where you put the type in the name.  This can cause difficulty in changing code later.  For example, what if you wanted to change from std::vector to a type called List?  Should you rename this variable as well?  A better name might be primes which works regardless of type.

    while (countPrimes < 10001)                 // checks until the 10001st prime has been found

You don't have to track a counter manually.  You can just say

    while (primes.size() < 10001)

The type already maintains a count for you.  You might as well use it rather than duplicate it manually.

        for (int i = 0; primeVector[i] <= sqrt(checkIfPrime + 1); i++)      //checks only prime factors up to the square root

You don't need to start at 0 each time.  By starting with 5 and 7 and always incrementing by 6, you ensure that it will never be divisible by 2 or 3.  So you can skip the first two elements in the vector.

        for (int i = 2, n = sqrt(primeCandidate); primes[i] <= n; i++)

You don't need to calculate the square root on each iteration.  You can do it once at the beginning of the loop.

You don't need to comment saying that you are only checking to the square root.  The code says this.  You might want to comment on why it is safe to only check up to the square root.

        {
            if ((checkIfPrime - 1) % primeVector[i] == 0)
            {
                lessOnePrime = false;
            }
            if ((checkIfPrime + 1) % primeVector[i] == 0)
            {
                plusOnePrime = false;
            }

            if (lessOnePrime == false && plusOnePrime == false)
            {
                break;
            }
        }

        if (lessOnePrime)
        {
            primeVector.push_back(checkIfPrime - 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime - 1 << endl;
        }
        if (plusOnePrime)
        {
            primeVector.push_back(checkIfPrime + 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime + 1 << endl;
        }
        lessOnePrime = true;
        plusOnePrime = true;

This is more complicated than it needs to be.  It would be much simpler to use two function calls instead of this for loop.

        if (isPrime(primeCandidate - 2, primes))
        {
            primes.push_back(primeCandidate - 2);
        }

        if (isPrime(primeCandidate, primes))
        {
            primes.push_back(primeCandidate);
        }

Yes, this repeats the for loop, but it saves you the internal scaffolding.  It also means that if one is a prime and the other isn't, it doesn't keep trying to divide the non-prime one by each potential factor.  That loop can exit early.  You'd have to profile to be sure, but I'd expect this to be faster.

The function would look something like

bool isPrime(const int candidate, const std::vector<int>& primes)
{
    for (int i = 2, n = sqrt(candidate); primes[i] <= n; i++)
    {
        if (candidate % primes[i] == 0)
        {
            return false;
        }
    }

    return true;
}

I haven't tried to compile it though.

Note that it might be more efficient to use an iterator rather than an index variable.  The notation would be more complicated in this case though.

I'll leave writing the actual function to you.  Note that even with the overhead of writing the function, you'll still likely shorten the code a bit.  You do a lot of effort just to make the single for loop work.

        checkIfPrime += 6;
    }

The only change I'd make to this is the variable name.  Although if you wanted to simplify the code in the loop at the cost of making this more complicated, you could change this to

         primeCandidate += increment;
         increment = 6 - increment;
     }

Where increment would be initialized as

     int increment = 2;

And you'd start primeCandidate at 5.  You'd also only do one isPrime check per iteration of the while loop.


Finding a path from one wikipedia page to another using semantic similarity of links (Spacy) I've just picked coding back up for the first time in a long time, so I understand if your eyes bleed looking at this code. It all works, but I'd be grateful for any tips (how to improve the python code, how to use Spacy's semantic similarity vector feature better, how to make it work faster, etc).
The main product of the code is the list_of_matches list, which shows how I got from one page to another. Clearly this example goes from "frog" to "crystal", but theoretically those could be anything.
import spacy
import wikipedia
import en_core_web_lg
nlp = en_core_web_lg.load()

word_1 = 'frog'
word_2 = 'crystal'
count = 0
closest_match = word_1
list_of_matches = []

link_list_1 = [nlp(word) for word in(wikipedia.page("Frog", auto_suggest=False).links)]

for item in link_list_1:
    print(item)

while float(item.similarity(nlp(word_2))) != 1.0 and count != 20:
    if closest_match.lower() == word_2:
        list_of_matches.append(word_2)
        break

    list_of_matches.append(closest_match)
    try:
        link_list = [nlp(word) for word in wikipedia.page(closest_match, auto_suggest=False).links]
    except wikipedia.exceptions.DisambiguationError:
        pass
    count += 1
    highest_match = 0
    for item in link_list:
        if(item.vector_norm):
            if float(item.similarity(nlp(word_2))) != 0.0:
                similarity = (item.text, word_2, item.similarity(nlp(word_2)))
                #print(similarity)
                link, word_2, vector = similarity
                if vector > highest_match and link not in list_of_matches:
                    highest_match = vector
                    closest_match = link
                    print(closest_match, highest_match)

print(list_of_matches)

First a few observations, then we'll try to improve things.

"Frog" in the first list comprehension should be closest_match (which is initialized to 'frog').
The two list comprehensions are identical, which suggests the code could be rearranged to eliminate the redundancy.
In the while loop, item.similarity() already returns a float, so the float() call is redundant. Also, it seems fishy that the test involves whatever happend to be the last item in link_list_1 or linked_list.
Avoid hard coding "magic numbers" like 1.0, 0.0, and 20 in the code. Use a defined constants with meaningful names to make the code clearer. For example, while item.similarity(nlp(word_2))) != PERFECT_MATCH.
I suspect calling nlp() is computationally expensive, but the code calls nlp(word_2) repeatedly.
word is a poor variable name, particularly when the page titles or links often have multiple words.
If a DisambiguationError is raised, the error is ignored. But, closest_match isn't changed, so the error will repeat the next time through the loop...until the loop count limit is reached.

Now let's try to improve the code.
It looks like the basic idea behind your code is to try to get from one Wikipedia page to a target page by following links. The strategy for picking which link to follow is to pick the one with text that is most similar to the target page name.  There doesn't appear to be any kind of breadth first search or back tracking or anything.
You got the code to grab the links on a page. Right now, the code runs nlp() on each link and check if it is similar to the target before checking if it's already been visited.
raw_links = wikipedia.page(current_page, auto_suggest=False).links
new_links = (link for link in raw_links if link not in path)

According to the spacy documentation it is more efficient to use nlp.pipe(), to process a sequence of texts. nlp.pipe() is a generator that yields a spacy.Doc for each text in the input.
next_pages = nlp.pipe(new_links)

But we want the page with the highest similarity to the target page. The Python builtin max() should work with an approriate key function:
target_page = nlp(target)  # this is done once outside the loop

next_page = max(nlp.pipe(new_links), key=target_page.similarity)

Of course, package it all up in a function:
def find_path(start, target, limit=20):
    start = start.lower()
    target = target.lower()

    try:
        target_page = nlp(target)

        current = start
        path = [start]

        for _ in range(limit):
            raw_links = wikipedia.page(current, auto_suggest=False).links
            new_links = (link.lower() for link in raw_links if link not in path)
            best_page = max(nlp.pipe(new_links), key=target_page.similarity)

            current = best_page.text
            path.append(current)

            if current == target:
                return path

    except wikipedia.exceptions.DisambiguationError as e:
        print(e)

    return []

START = "frog"
TARGET = "crystal"

print(find_path(START, TARGET))

Note: I don't have spacy so I couldn't test this code. It may have some bugs, but based on the docs, I think it should point you in the right direction.


Project Euler 2 - Fibonacci sequence I lately spend a lot of time at Project Euler programming challenges. I have following problem which I should solve:

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

I wrote Java code and I submitted it.

Implementation

First, I wrote helper method fibonacci(int n) which calculates a n-th word of fibonacci sequence and returns it. In main method I created a list of numbers and a n variable, that would be incremented in a loop. In the loop I was looking for all numbers that are even-valued that are added to the list. Next, I created result variable and I sum all numbers in the list and then, finally I printed it out to console.

Main.java:

package pl.hubot.projecteuler.problem2;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        int n = 0;
        while (fibonacci(n) < 4_000_000) {
            if (fibonacci(n) % 2 == 0) numbers.add(fibonacci(n));
            n++;
        }
        int result = 0;
        for (Integer number : numbers) {
            result += number;
        }
        System.out.print(result);
    }

    private static int fibonacci(int n) {
        if (n == 0) return 0;
        else if (n == 1) return 1;
        else return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

The recursive definition of Fibonacci is an elegant one, but in practice it's something you would never want to use. Let's say you want to get fibonacci(5). How often does fibonacci get called?

fibonacci(5)
 =    fibonacci(4) + fibonacci(3)
 =   (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
 =   ((fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0)))
   + ((fibonacci(1) + fibonacci(0)) + fibonacci(1))
 =   (((fibonacci(1) + fibonacci(0)) + fibonacci(1))
        + (fibonacci(1) + fibonacci(0))
     )
   + ((fibonacci(1) + fibonacci(0)) + fibonacci(1))

That seems a lot for 0 + 1 + 1 + 2 + 3 + 5. Indeed, the recursive variant without memoization has exponential runtime. You have several options to reduce the time:

use an iterative variant (which leads to \$ \mathcal O(n)\$ instead of \$ \mathcal O(2^n)\$ per call of fibonacci),
use memoization (which, if done correctly, leads to \$ \mathcal O(n)\$ in worst case and \$ \mathcal O(1)\$ if the number was already calculated).

But that begs the question: do we actually need fibonacci? For a programming challenge, it's enough to calculate the sum in main, while you're calculating the numbers iteratively. If you're looking for performance, that would be the fastest variant (that doesn't use the closed form).


Manual slide-in animation using delta time I created a simple slide-in animation for my game. The box is shown at the bottom with character dialog.

The animation is as follows:

A square slides in from the left, then waits a bit, then expands to its full width.

The box is made using Unity's GUI Box. The timing is extended for debugging purposes (I need to be able to clearly see the animation).

It isn't coded spectacularly (I wrote it in 5 minutes in the first way that occurred to me), but I can't really think of another way to write it at the moment. What would you improve?

private string boxString = "Hello, world! I am sample character dialog.";

private float elapsedTime = 0.0f;

private float initialSlideInDuration = 1.333f;
private float waitBetweenSlideAndExpand = 0.666f;
private float expansionDuration;

private float boxHeightPercentage = 0.10f;
private float boxWidthPercentage = 0.95f;
private float positionFromLeft;
private float positionFromBottom;
private float boxWidth;
private float boxHeight;

// instantiate variables before any frames are drawn
void Start () {
    expansionDuration = initialSlideInDuration + waitBetweenSlideAndExpand + 3.333f;
    boxWidth = Screen.width*boxWidthPercentage;
    boxHeight = Screen.height*boxHeightPercentage;
    positionFromLeft = (Screen.width - (Screen.width * boxWidthPercentage)) / 2;
    positionFromBottom = Screen.height - (positionFromLeft + boxHeight);
}

// called once per frame
void Update () {
    elapsedTime += Time.deltaTime;
}

// render and handle GUI events
void OnGUI() {
    // slide in square
    if (elapsedTime <= initialSlideInDuration) {
        float initialLeftPadding = -positionFromLeft - boxHeight;
        float finalLeftPadding = positionFromLeft;
        float movementDistance = (2 * positionFromLeft) + boxHeight;
        float progress = elapsedTime / initialSlideInDuration;

        GUI.Box (new Rect ((progress * movementDistance) + initialLeftPadding, positionFromBottom, boxHeight, boxHeight), boxString);
    }
    // if square is ready and we have waited, animate to rectangle
    else if (elapsedTime > initialSlideInDuration+waitBetweenSlideAndExpand && elapsedTime <= expansionDuration) {
        float initialWidth = boxHeight;
        float finalWidth = boxWidth;
        float growth = finalWidth - initialWidth;
        float progress = elapsedTime / expansionDuration;

        GUI.Box(new Rect(positionFromLeft, positionFromBottom, (progress * growth) + initialWidth, boxHeight), boxString);
    }
    // stay as full width rectangle
    else if(elapsedTime > expansionDuration){
        GUI.Box (new Rect (positionFromLeft, positionFromBottom, boxWidth, boxHeight), boxString);
    }
    // we are waiting, display the square with left padding
    else {
        GUI.Box (new Rect (positionFromLeft, positionFromBottom, boxHeight, boxHeight), boxString);
    }
}

The following makes the assumption  that all durations are totaled together (as duration) and should give a smoother animation. with a pause based on the original box width (presently height);

void OnGUI() {
    float progress = elapsedTime / duration;
    float leftPositon = progress * positionFromLeft - boxHeight;
    float width = (progress * (boxWidth + positionFromLeft)) - positionFromLeft;

    if (leftPositon > positionFromLeft){
        leftPositon = positionFromLeft;
    }

    if (width < boxHeight) {
        width = boxHeight;
    }
    else if ( width > boxWidth){
        width = boxWidth;
    }

    GUI.Box (
        new Rect (
            leftPositon,
            positionFromBottom,
            width,
            boxHeight
        ),
        boxString
    );
}


Remove Duplicates from Sorted List -- LeetCode Solution in C Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
    struct ListNode* deleteDuplicates(struct ListNode* head) {
    }

I have the written the solution for it, but looking for more ideas and suggestions. This solution has passed all the 166 test cases from leetcode.

    /**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
 struct ListNode * current = head, *nextNode, *temp;

 //No elements
 if(head == NULL)
 {
     return NULL;
 }

 //Single element linked list
 if(head->next == NULL)
 {
     return head;
 }

     //if the numbers are repeating from the beginning;;
     //then we need to move head;
     while(head !=NULL && head->next !=NULL && head->val == head->next->val){
     if( head->val == head->next->val)
     {
         nextNode = head->next;
         while(nextNode !=NULL  && head->val == nextNode->val){
            temp = nextNode;
        nextNode = nextNode->next;
            free(temp);
         }

         temp = head;
         head = nextNode;
         current = head;
         free(temp);
     }

     }
     //Again a check to see if the list is empty

         if(head == NULL)
         {
             return NULL;
         }

    while(current->next != NULL){

     nextNode = current->next;

        if(nextNode->next !=NULL  && nextNode->val == nextNode->next->val){

         while(nextNode->next !=NULL  && nextNode->val == nextNode->next->val){
            temp = nextNode->next;
        nextNode->next = temp->next;
         }
        current->next = nextNode->next;

        }else {
            current = nextNode;
        }

 }

return head;

}

You can use a simple recursive method like this: basically, we only need to care about the previous node and current node when deleting a node.

ListNode* deleteDuplicates(struct ListNode* head) {
     deleteDuplicates(NULL, head);
     return head;
}

void deleteDuplicates(struct ListNode* pre, struct ListNode* cur) {
   if(cur == NULL)
      return;
   if(pre == NULL){
      deleteDuplicates(cur, cur->next);
   }else if(pre->val == cur->val){//Delete duplicate node
      pre->next = cur->next;
      deleteDuplicates(pre, pre ->next);
   }else{//The current node doesn't need to be deleted, move forward
      deleteDuplicates(cur, cur->next);
   }
}


For loop that iterates through files and iteratively appends lists storing values from the read file How can I fasten this code, that reads a text file sequentially and appends a list? fp and fp_2 reads two different files from the same sub-sirectory here

import os
import glob
from IPython import embed
import numpy as np

dirs = os.listdir("/home/Set/")

poseList = [] #Store poses for all files
featuresList = [] # Store features

def data():
    for dir_name in dirs:
        fp = '/home/Set/left'
        fp_2 =  '/home/Set/fc/fc2_0.npy'
        if os.path.exists(fp) and os.path.exists(fp_2):
            files = glob.glob(fp+"/*.txt")
            curr_pose = []  #Store curr pose
            for f in files:
                with open(f) as pose:
                    pl = pose.readlines()
                    pl = [p.strip() for p in pl]
                    pl = map(float, pl)  # str ->float
                    curr_pose.append((pl))
            poseList.append(curr_pose)   #append to main list
            featuresList.append(np.load(fp_2))
        print "Not available", dir_name

data()
embed()

Variable naming

Your variable's names do not convey their purpose and are even misleading.
E.g. fp and fp_2 suggest file pointers, but are actually strings.
Notwithstanding, for a better reference, I will use your variable names below.

You should also implement PEP8 (poseList vs. pose_list etc.).

Recurring declaration

You keep redefining the same constants fp and fp_2 in a loop:

for dir_name in dirs:
    fp = '/home/Set/left'
    fp_2 =  '/home/Set/fc/fc2_0.npy'

Better declare them beforehand:

fp = '/home/Set/left'
fp_2 =  '/home/Set/fc/fc2_0.npy'

for dir_name in dirs:

Avoiding race conditions

By checking for existing files and folders using

if os.path.exists(fp) and os.path.exists(fp_2):

you've created yourself a race condition.
It is better to just try to open the file and handle the respective exception raised if something goes wrong.

Joining paths

Your path concatenation

fp+"/*.txt"

might work for you.
But there is os.path.join to do this safely and get a sanitized path:

os.path.join(fp, "*.txt")  # Leading "/" removed!

Just for the record: In Python 3 (which you are not using assuming from your print statement) you can use pathlib.Path to handle your paths:

fp = Path('/home/Set/left')
…
str(fp.joinpath('*.txt'))

Reading lines

Files are iterable, so you can get a file's lines more easily:

for f in files:
    with open(f) as pose:
        pl = [line.strip() for line in pose]
        …


Interface Segregation Principle in constructor I'm wondering if providing default behavior is ever worth the confusion caused by ignoring generic type passed in. Another question brought up this issue:

public class Activate<D extends CanQuack & CanWalk> {
    D d;

    //Must match D's type
    Activate(D d) {
        this.d = d;
    }

    //Completely ignore D's type
    Activate() {
        this.d = (D)new MyWaterFowl(); //Provide default behavior.
    }

    void setDuckLikeThing(D d) {
        this.d = d;
    }

    void doDuckLikeThings() {
        d.quack();
        d.walk();
        //d.swim(); //Doesn't work
        //And shouldn't since that was the whole point of ISP.
    }
}

interface CanWalk { public void walk(); }
interface CanQuack { public void quack(); }
interface CanSwim { public void swim(); }

public class MyWaterFowl implements CanWalk, CanQuack {

    public void walk() { System.out.println("I'm walkin` here!"); }
    public void quack() { System.out.println("Quack!"); }
    public void swim() { System.out.println("Stroke! Stroke! Stroke!"); }
}

public class MainClass {

    public static void main(String[] args) {
       //Works
       Activate<MyWaterFowl> a = new Activate<>(new MyWaterFowl());
       a.doDuckLikeThings();

       //Works
       Activate<MyAmericanEagle> ae = new Activate<>( new MyAmericanEagle() );
       ae.doDuckLikeThings();

       //Works but nothing to do with MyAmericanEagle is happening here
       Activate<MyAmericanEagle> ad = new Activate<>();
       ad.doDuckLikeThings();

       //Rightly produces an error
       //Activate<MyAmericanEagle> aw = new Activate<>( new MyWaterFowl() );
       //ae.doDuckLikeThings();

       //Rightly produces an error
       //Activate<MyWaterFowl> wa = new Activate<>( new MyAmericanEagle() );
       //ae.doDuckLikeThings();

    }
}

So would you ever want a library to leave you wondering why MyAmericanEagle gets completely ignored just to provide some default behavior?

No, this is all broken. The basic issue is the cast-to-D in the following line:

this.d = (D)new MyWaterFowl();

That gives the warning:

Type safety: Unchecked cast from MyWaterFowl to D

Ignoring Generics warnings normally means you are doing something wrong. In this case, you are.

You are doing a cast to a type where you have no certainty, in fact, you are certain that it will fail....

.... the solution here, is to not have a default constructor. It does not make sense for you. Why do you think you need one?

Also, why does MyAmericanEagle extend CanQuack ?


Printing mutual anagrams Question:

  An anagram is a word that can be written as a permutation of the
  characters of another word, like "dirty room" and "dormitory"(ignore
  spaces). However, "the" and "thee" are not anagrams, since "the" only
  has a single "e" whereas "thee" has two "e" characters (spaces can
  occur zero, or multiple times, however).

  Give a list of words as input, you should output another list of
  strings, each containing words that are mutual anagrams.

  Each string of the output should be a single group of anagrams joined
  with commas.

  Within an output string, the expressions should be sorted
  lexicographically. If a group contains only a single element, output
  that one-element group as a single string. And the strings should also
  be output in lexicographical order.

  Given e.g.:

  pear
  amleth
  dormitory
  tinsel
  dirty room
  hamlet
  listen
  silent

  The output would be:

amleth,hamlet
dirty room,dormitory
listen,silent,tinsel
pear

My solution is:

Convert into each string to a char array, and in the meantime, compare to each char array group. After that, get how many groups for an input string array, and divide them into a respective group.
Sort each group alphabetically, and eventually order by group.

Time-complexity is \$O(n^2)\$

I wrote code for this question, and it has a poor time-complexity. Are there any suggestions for this?

ArrayList<char[]> group = new ArrayList<char[]>();
    ArrayList<ArrayList<String>> originalList = new ArrayList<ArrayList<String>>();
    String[] tempstr = str.clone(); //clone could do deep copy, and avoid to change str.

    //Category group for str.
    outerloop:
    for(int pos=0; pos<tempstr.length; pos++){
        tempstr[pos]= tempstr[pos].trim().replaceAll(" ", "");
        char[] c = new char[tempstr[pos].length()];
        tempstr[pos].getChars(0,tempstr[pos].length(),c,0); //last character is at index srcEnd-1
        Arrays.sort(c);//ignore character's order in string.
        ArrayList<String> sArrList = new ArrayList<String>();

        Iterator<char[]> it = group.iterator();
        while(it.hasNext()){
            sArrList.clear();
            char[] comparedChars = (char[])it.next();
            if(Arrays.equals(comparedChars,c)){//only compare character in same index.
                sArrList = originalList.get(group.indexOf(comparedChars));
                sArrList.add(str[pos]);
                continue outerloop;
            }
        }
        // can not find group
        sArrList.add(str[pos]);
        originalList.add(sArrList);
        group.add(c);
    }

    //Following begin to do sorting.
    String[] groupStr = new String[group.size()];
    Iterator<ArrayList<String>> it2 = originalList.iterator();
    for(int groupId=0 ; groupId<group.size() && it2.hasNext(); groupId++){
        ArrayList<String> temp = it2.next();
        Collections.sort(temp); // let string in each single row sort by alphabet.
        for(Iterator it3 = temp.iterator();it3.hasNext();){
            String ss = (String) it3.next();
            if(groupStr[groupId]==null || groupStr[groupId].length()==0) groupStr[groupId] = ss;
            else groupStr[groupId] += "," + ss;
        }
    }

A different way would be to use primeHashes  (see https://stackoverflow.com/a/4237875/461499).

This prevents the need to sort.

private static void printAnagrams2(List<String> input) {

    // our result structure.
    // key in the map is the sorted list of characters of the string
    // value is the list of anagrams found for this key
    Map<BigInteger, List<String>> result = new HashMap<BigInteger, List<String>>();

    for (String s : input) {
        BigInteger primeHash = calcPrimeHash(s);

        // Then add-or-create this in the resultmap
        if (result.containsKey(primeHash)) {
            result.get(primeHash).add(s);
        } else {
            List anagrams = new ArrayList<String>();
            anagrams.add(s);
            result.put(primeHash, anagrams);
        }
    }

    // sort each anagram-list
    result.values().forEach(Collections::sort);

    // and print
    result.values().forEach(System.out::println);
}

private static int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};

private static BigInteger calcPrimeHash(String s) {
    BigInteger i = BigInteger.valueOf(1);
    for (char ch : s.toCharArray())
    {
        if (Character.isLetter(ch))
        {
            char c = Character.toLowerCase(ch);
            i = i.multiply(BigInteger.valueOf(primes[c - 'a']));
        }
    }
    return i;
}


Refactoring a HTML class collector? I have following HTML class collector. Is there a better way than []tap for this?

def tr_classes(user)
  classes = [].tap do |c|
    c << "error" if user.company.nil?
    c << "disabled" if user.disabled?
  end
  if classes.any?
    " class=\"#{classes.join(" ")}\""
  end
end

<tr<%= tr_classes(user) %>>
  <%= user.name %>

Notes:

This tap usage is not uncommon to see but IMHO it's very, very dubious. You can use a functional approach (see code below).
I wouldn't return the string along with the attribute, just the array of classes (which Rails3 helpers understand).

I'd write:

def tr_classes(user)
  [
    ("error" if !user.company),
    ("disabled" if user.disabled?),
  ].compact.presence
end

Tables are usually easier to build from helpers. You now would use the function that way:

content_tag(:tr, :class => tr_classes(user)) do
  content_tag(:td, user.name)
end


JavaScript idle managing structure I am just getting into the world of javascript, coming from the world of classical inheritance. The following is a library I wrote to track when a webapp is idling and I wrote it like I write classical inheritance. But what I have heard about javascript is you have to completely forget how classical inheritance works.

I would love to see how a real javascript developer would write the following using prototypes and the likes.

var IdleListeners = new function(){
  var self = this;

  window.onmousemove = resetTimer;
  window.onmousedown = resetTimer;
  window.onclick = resetTimer;
  window.onscroll = resetTimer;
  window.onkeypress = resetTimer;

  function resetTimer() {
    for (var i = 0; i < self.listeners.length; i++) {
        self.listeners[i].reset();
    }
  }
}

IdleListeners.listeners = [];

IdleListeners.add = function(idleFunction, timeout){
  this.listeners.push(new IdleListener(idleFunction, timeout));
}

var IdleListener = function(idleFunction, timeout){
  this.idleFunciton = idleFunction;
  this.timeout = timeout;

  this.reset = function(){
    if (this.hasOwnProperty('interval')){
      clearInterval(this.interval);
    };
    this.interval = setInterval(this.idleFunciton, this.timeout);
  }
}

It is used by simply calling the following in your html/js file

IdleListeners.add(function(){
    console.log("Idle!")
}, 1000);

"Idle!" would be called once every 1000 miliseconds when the mouse hasn't moved or no keys have been pressed.

window.onmousemove = resetTimer;
window.onmousedown = resetTimer;
window.onclick = resetTimer;
window.onscroll = resetTimer;
window.onkeypress = resetTimer;

First, I'd suggest not binding handlers this way. The problem is that some other code might override the property and completely replace the handler. Even if you take steps not to override an existing one, there's no guarantee that yours won't get overridden. Use addEventListener instead.

Also, document and window have different events. document related to the DOM elements (i.e.: click, mouseover) and window related to window events (i.e. resize, scroll etc.). See this answer for details.

var IdleListeners = new function(){

You're not benefiting from the perks of constructor-created objects. What your code essentially does is create an instance of an anonymous constructor which has no methods nor properties. You merely created a closure that wraps the initialization code and your timer reset.

var IdleListener = function(idleFunction, timeout){

For this one, you almost got it, except for the this.reset. The goal of prototypal inheritance is to share methods among instances. Defining reset in this instead of the prototype means that each instance gets its own copy of reset, not shared.

this.interval = setInterval(this.idleFunciton, this.timeout);

I believe you want setTimeout. You wouldn't want the handlers to fire periodically, especially when they're bound to an alert. It would be endless.

  But what I have heard about javascript is you have to completely forget how classical inheritance works.

Not really. You just need to know how classical inheritance is different from prototypal inheritance. Also, you shouldn't force JS to do what it doesn't do natively. While it can emulate, it's not pretty.

Keep the code simple. As much as possible, work with just functions, objects (maps) and arrays (lists). Don't jump into OOP or inheritance directly. For instance, I can simplify your code with a singleton and a list of handlers.

;(function(ns){

  // An array for our "listeners"
  var listeners = [];

  // An add function which accepts a delay and handler
  ns.add = function add(handler, timeout){

    // All we're doing here is create an entry in the array containing our
    // settings, and preparing the timer as null. Reset will build it for us.
    listeners.push({
      handler: handler,
      timeout: timeout,
      timer: null
    });
  }

  // Now when you call reset (as a result of an action), it loops through all
  // the handler definitions, clears any existing timers, and rebuilds them.
  ns.reset= function reset(){
    listeners.forEach(function(listener){
      clearTimeout(listener.timer);
      listener.timer = setTimeout(listener.handler, listener.timeout);
    });
  }

  // Add handlers
  document.addEventListener('click', reset);

// Use an existing global or create one
}(this.IdleListener = this.IdleListener || {}));

// Usage
IdleListener.add(function(){
  console.log('idle!');
}, 1000);


Apache log4j in play framework I have converted this code from Java to Scala, and I need reviews.  This works fine, but I am sure that something is wrong with this coding pattern.

package models

import org.apache.log4j.ConsoleAppender
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.PatternLayout
import org.apache.log4j.RollingFileAppender

import me.prettyprint.cassandra.serializers.StringSerializer

object LogFile extends CassandraConnection {

  val loger = Logger.getRootLogger()
  def exceptionLogs(qName: String, data: String) {
    //data is json String
    val logg = Logger.getLogger(qName + "-" + data)
    loger.setLevel(Level.ERROR)
    val layout = new PatternLayout("[%t] %-5p %c %x - %m %d{ISO8601} %n")
    loger.addAppender(new ConsoleAppender(layout))
    try {
      val fileAppender = new RollingFileAppender(layout, "QLog.txt")
      loger.addAppender(fileAppender)
      logg.error("")
      loger.removeAppender(fileAppender)
    } catch {
      case e: Exception =>
        println(e)
        logg.error("");
    }
  }

}

I'm not exactly sure what you mean with coding pattern, but there are some things that strike me as odd:

you only log empty messages ... in some of the cases encoding the message in the logger name. This certainly isn't the way log4j is intended to be used.
When ever you call this method basically the same Appender is created added and removed again. This again is a strange way to use log4j. And I'm not even sure what will happen when two threads call this method at the same time.
You are setting the ConsoleAppender and the Pattern over and over again. This at least is superfluous, and might actually be harmful.
The naming is ... suboptimal ... You have two loggers one, is missing a g in its name, the other is abbreviated. None really tells the reader what these loggers are about.
You never ever actually log with loger

So if this doesn't depend on some weird side effect this logs one empty String when it is called and two empty Strings when creating/adding/removing an Appender throws and exception. If this is really what this is supposed to do, it better made it clear in its names and comments.


More groovifed way of sublist with varying range Student list of 50 students and a teacher list of 3 teachers.

Section XML as the output where each teacher is assigned to a section, and up to 20 students are assigned in that section.

Need to loop on each teacher element, and for each teacher element, loop on the student name from 1-20, than for 2nd teacher, students 21-40 etc.

The following is working code. However, feeling that there could be better groovified way to get 20 students for a teacher

def students = """<Students>
    <name> st name 1</name>
    <name> st name 2</name>
    <name> st name 3</name>
    <name> st name 4</name>
    <name> st name 5</name>
    <name> st name 6</name>
    <name> st name 7</name>
    <name> st name 8</name>
    <name> st name 9</name>
    <name> st name 10</name>
    <name> st name 11</name>
    <name> st name 12</name>
    <name> st name 13</name>
    <name> st name 14</name>
    <name> st name 15</name>
    <name> st name 16</name>
    <name> st name 17</name>
    <name> st name 18</name>
    <name> st name 19</name>
    <name> st name 20</name>
    <name> st name 21</name>
    <name> st name 22</name>
    <name> st name 23</name>
    <name> st name 24</name>
    <name> st name 25</name>
    <name> st name 26</name>
    <name> st name 27</name>
    <name> st name 28</name>
    <name> st name 29</name>
    <name> st name 30</name>
    <name> st name 31</name>
    <name> st name 32</name>
    <name> st name 33</name>
    <name> st name 34</name>
    <name> st name 35</name>
    <name> st name 36</name>
    <name> st name 37</name>
    <name> st name 38</name>
    <name> st name 39</name>
    <name> st name 40</name>
    <name> st name 41</name>
    <name> st name 42</name>
    <name> st name 43</name>
    <name> st name 44</name>
    <name> st name 45</name>
    <name> st name 46</name>
    <name> st name 47</name>
    <name> st name 48</name>
    <name> st name 49</name>
    <name> st name 50</name>
</Students>"""

def teachers = """<Teachers>
    <name> Teacher name 1</name>
    <name> Teacher name 2</name>
    <name> Teacher name 3</name>
</Teachers>"""

def getData  = { xml, elementName ->
    def parseXml = new XmlSlurper().parseText(xml)
    parseXml.'**'.findAll { it.name() == elementName }
}

def teacherNodes = getData( teachers, 'name')
def studentNodes = getData( students, 'name')

def sublist (data, start, end) {
    start == 0 ? data.take(end) : data.drop(start).take(end-start)
}

def incrementBy = 20
def startStudents = 0
def endStundents = incrementBy
def builder = new groovy.xml.StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def xml = builder.bind {
    mkp.xmlDeclaration()
    Assignments {
        teacherNodes.eachWithIndex { teacherNode, index ->
            Section {
                id (index+1)
                teacher (teacherNode.text())
                studentList {
                    sublist(studentNodes, startStudents, endStundents).each { studentNode ->
                        name (studentNode.text())
                    }
                }
            }
            startStudents = endStundents
            endStundents += incrementBy
        }
    }
}

println groovy.xml.XmlUtil.serialize(xml)

You could start with:

def groups = [:]
teacherNodes.each { teacher ->
    groups[teacher] = studentNodes.take(incrementBy)
    studentNodes    = studentNodes.drop(incrementBy)
}


Repetitive controller with all methods nearly identical I have an API with the following code

    class API::V1::ReceptionController < API::V1::APIController
      before_filter :ensure_document_exists

      def produto
        jid = ProdutoWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def cliente
        jid = ClienteFornecedorWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def nota_fiscal
        jid = NotaFiscalWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def venda
        jid = VendaWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def reducaoz
        jid = ReducaoZWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def impressora_fiscal
        jid = ImpressoraFiscalWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end
..............

and so on. What happens is: every method call a different worker, but all the body's methods are pretty much the same. My question is: how can I reduce this methods to maybe just one?

Some notes:

I don't know if there is an agreement on the community on that, but I would definitely use the de-facto language of the computer industry (translating the API routes if needed, of course).
I'd write parens on "normal" (non-DSL) method calls.
That's a lot of actions. Why don't you refactor it to have a unique action with a param?

I'd write:

class API::V1::ReceptionController < API::V1::APIController
  before_filter :ensure_document_exists
  WorkerClasses = {:produto => ProdutoWorker, ....}

  def process
    worker_class = WorkerClasses[params[:key].to_sym]
    if worker_class
      jid = worker_class.perform_async(params[:document])
      render(json: {jid: jid}, :status => 200)
    else
      render(json: {errors: "Unknown key: #{params[:key]}"}, :status => 400)
    end
  end

(and change the routes accordingly, of course)


Find the sum of the digits in factorial of 100 in Erlang This is a problem in poject Euler:

  n! means n × (n − 1) × ... × 3 × 2 × 1

  For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of
  the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

  Find the sum of the digits in the number 100!

I decided to solve it using erlang.
This is what I've come up with.

-module(fact).
-compile(export_all).

fact(1) -> 1;
fact(N) -> N*fact(N-1).

tolist(N) when N < 10 -> [N];
tolist(N) when N >= 10 -> tolist(N div 10)++[N rem 10].

sum(List) -> sum(List, 0).
sum([H|T], C) -> sum(T, C + H);
sum([], C) -> C.

factfinds the factorial of the number. toList converts it to a list of integers and sum gets the sum of the integers in the list. I run this program like this:

fact:sum(fact:tolist(fact:fact(100))).

Do I have to use 3 functions? Is there a problem with me doing so?

Should I make another function that calls all 3 functions?

Don't need rewrite functions which already exist in standard library. Almost always it's will give worse result and just take away your time for writing and testing.

For converting from integer to list (string) - integer_to_list/1
For getting some single result from set data in a list - use lists:foldl/3
For extracting the numerical value from digit symbol - just subtract zero-value($0, number representation in Erlang).

So, if accumulate all of this points, get:

task_(N)->
lists:foldl(fun(X,Sum)->Sum+X-$0 end,0,integer_to_list(fact(N))).

If saying generally, I don't see any problem in rule - "one function for one task". It will make your code more readable, flexible and good for testing.


More protection needed? PHP secure I am busy on a protected page with login and I want know if there is more protection needed. It is a very simple system without database etc...

authentication.php

<?php
session_start();

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $account = array (
        'sebas' => '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
        'bert' => '$3g$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
    );

    if(array_key_exists($_POST['user'], $account)){
        if(password_verify($_POST['password'], $account[$_POST['user']])){
                session_regenerate_id();
                $_SESSION['username'] = $_POST["user"];
                $_SESSION["loggedin"]) = true;
                header("location: protected_page.php");
        }else{
            echo 'Something wrong';
        }
    }else{
        echo 'Something wrong';
    }
}
?>

protected.php

<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo 'welcome';
}else{
    header("location: login.php");
    exit;
}
?>

Please let me know and give me any feedback for a better secure system without database.

One major concern is that you define the array of account names and their associated hashed passwords in the file that, presumably, is publicly accessible through a web server.

You might be tempted to think this is not a concern, because users will not be able to see the source code, right? Generally speaking, that's correct. However, if the web server somehow becomes misconfigured at some point, where .php files are not executed by the PHP engine, but in stead are served as plain text, you have a big security issue: any visitor will now be able to view the account info.

To deal with this, you should keep this sensitive information outside of the server's public directory.

So, let's imagine this is your web server's directory structure:

 - etc/
 - private/ <-- A hidden private directory, outside of the public directory
 - public/ <-- The public root directory from which your .php pages are served
   - img/
   - js/
   - authentication.php
   - protected.php

...then you should, for instance, put your account info in private:

 - etc/
 - private/
   - accounts.php
 - public/
   - img/
   - js/
   - authentication.php
   - protected.php

accounts.php would then look like this:

<?php
return array (
    'sebas' => '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
    'bert' => '$3g$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
);

authentication.php would then do something like this:

<?php
session_start();

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    // I personally prefer to name this variable as plural
    $accounts = include '../private/accounts.php';

    // if include has failed, it will return false
    if(is_array($accounts)) {
       // continue your authentication procedure
    }

... etc.